From d71e28f61c02e76cbcdc59d22826fd1bd733fcda Mon Sep 17 00:00:00 2001 From: Benjamin Baudel Date: Thu, 16 Nov 2017 11:14:05 +0100 Subject: [PATCH 01/19] Add HLS.js library (v0.8.7) --- lib/hls.js/LICENSE.md | 28 + lib/hls.js/hls.js | 15835 ++++++++++++++++++++++++++++++++++++++++ lib/hls.js/hls.js.map | 1 + lib/hls.js/hls.min.js | 1 + 4 files changed, 15865 insertions(+) create mode 100644 lib/hls.js/LICENSE.md create mode 100644 lib/hls.js/hls.js create mode 100644 lib/hls.js/hls.js.map create mode 100644 lib/hls.js/hls.min.js diff --git a/lib/hls.js/LICENSE.md b/lib/hls.js/LICENSE.md new file mode 100644 index 00000000..45c8d5dc --- /dev/null +++ b/lib/hls.js/LICENSE.md @@ -0,0 +1,28 @@ +Copyright (c) 2017 Dailymotion (http://www.dailymotion.com) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +src/remux/mp4-generator.js and src/demux/exp-golomb.js implementation in this project +are derived from the HLS library for video.js (https://github.com/videojs/videojs-contrib-hls) + +That work is also covered by the Apache 2 License, following copyright: +Copyright (c) 2013-2015 Brightcove + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/lib/hls.js/hls.js b/lib/hls.js/hls.js new file mode 100644 index 00000000..c0bef8a5 --- /dev/null +++ b/lib/hls.js/hls.js @@ -0,0 +1,15835 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["Hls"] = factory(); + else + root["Hls"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/dist/"; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 8); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return enableLogs; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return logger; }); +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +function noop() {} + +var fakeLogger = { + trace: noop, + debug: noop, + log: noop, + warn: noop, + info: noop, + error: noop +}; + +var exportedLogger = fakeLogger; + +/*globals self: false */ + +//let lastCallTime; +// function formatMsgWithTimeInfo(type, msg) { +// const now = Date.now(); +// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0'; +// lastCallTime = now; +// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )'; +// return msg; +// } + +function formatMsg(type, msg) { + msg = '[' + type + '] > ' + msg; + return msg; +} + +function consolePrintFn(type) { + var func = self.console[type]; + if (func) { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (args[0]) { + args[0] = formatMsg(type, args[0]); + } + func.apply(self.console, args); + }; + } + return noop; +} + +function exportLoggerFunctions(debugConfig) { + for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + functions[_key2 - 1] = arguments[_key2]; + } + + functions.forEach(function (type) { + exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type); + }); +} + +var enableLogs = function enableLogs(debugConfig) { + if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') { + exportLoggerFunctions(debugConfig, + // Remove out from list here to hard-disable a log-level + //'trace', + 'debug', 'log', 'info', 'warn', 'error'); + // Some browsers don't allow to use bind on console object anyway + // fallback to default if needed + try { + exportedLogger.log(); + } catch (e) { + exportedLogger = fakeLogger; + } + } else { + exportedLogger = fakeLogger; + } +}; + +var logger = exportedLogger; + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony default export */ __webpack_exports__["a"] = ({ + // fired before MediaSource is attaching to media element - data: { media } + MEDIA_ATTACHING: 'hlsMediaAttaching', + // fired when MediaSource has been succesfully attached to media element - data: { } + MEDIA_ATTACHED: 'hlsMediaAttached', + // fired before detaching MediaSource from media element - data: { } + MEDIA_DETACHING: 'hlsMediaDetaching', + // fired when MediaSource has been detached from media element - data: { } + MEDIA_DETACHED: 'hlsMediaDetached', + // fired when we buffer is going to be reset - data: { } + BUFFER_RESET: 'hlsBufferReset', + // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }} + BUFFER_CODECS: 'hlsBufferCodecs', + // fired when sourcebuffers have been created - data: { tracks : tracks } + BUFFER_CREATED: 'hlsBufferCreated', + // fired when we append a segment to the buffer - data: { segment: segment object } + BUFFER_APPENDING: 'hlsBufferAppending', + // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent} + BUFFER_APPENDED: 'hlsBufferAppended', + // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { } + BUFFER_EOS: 'hlsBufferEos', + // fired when the media buffer should be flushed - data { startOffset, endOffset } + BUFFER_FLUSHING: 'hlsBufferFlushing', + // fired when the media buffer has been flushed - data: { } + BUFFER_FLUSHED: 'hlsBufferFlushed', + // fired to signal that a manifest loading starts - data: { url : manifestURL} + MANIFEST_LOADING: 'hlsManifestLoading', + // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}} + MANIFEST_LOADED: 'hlsManifestLoaded', + // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest} + MANIFEST_PARSED: 'hlsManifestParsed', + // fired when a level switch is requested - data: { level : id of new level } // deprecated in favor LEVEL_SWITCHING + LEVEL_SWITCH: 'hlsLevelSwitch', + // fired when a level switch is requested - data: { level : id of new level } + LEVEL_SWITCHING: 'hlsLevelSwitching', + // fired when a level switch is effective - data: { level : id of new level } + LEVEL_SWITCHED: 'hlsLevelSwitched', + // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded} + LEVEL_LOADING: 'hlsLevelLoading', + // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} } + LEVEL_LOADED: 'hlsLevelLoaded', + // 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 } + LEVEL_UPDATED: 'hlsLevelUpdated', + // 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 } + LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated', + // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks } + AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated', + // fired when an audio track switch occurs - data: { id : audio track id } // deprecated in favor AUDIO_TRACK_SWITCHING + AUDIO_TRACK_SWITCH: 'hlsAudioTrackSwitch', + // fired when an audio track switching is requested - data: { id : audio track id } + AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching', + // fired when an audio track switch actually occurs - data: { id : audio track id } + AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched', + // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id } + AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading', + // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } } + AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded', + // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks } + SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated', + // fired when an subtitle track switch occurs - data: { id : subtitle track id } + SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch', + // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id } + SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading', + // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } } + SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded', + // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag } + SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed', + // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object } + INIT_PTS_FOUND: 'hlsInitPtsFound', + // fired when a fragment loading starts - data: { frag : fragment object } + FRAG_LOADING: 'hlsFragLoading', + // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } } + FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress', + // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object } + FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted', + // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } } + FRAG_LOADED: 'hlsFragLoaded', + // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } } + FRAG_DECRYPTED: 'hlsFragDecrypted', + // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment } + FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment', + // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] } + FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata', + // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] } + FRAG_PARSING_METADATA: 'hlsFragParsingMetadata', + // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null} + FRAG_PARSING_DATA: 'hlsFragParsingData', + // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object } + FRAG_PARSED: 'hlsFragParsed', + // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } } + FRAG_BUFFERED: 'hlsFragBuffered', + // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object } + FRAG_CHANGED: 'hlsFragChanged', + // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames } + FPS_DROP: 'hlsFpsDrop', + //triggered when FPS drop triggers auto level capping - data: { level, droppedlevel } + FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping', + // 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 } + ERROR: 'hlsError', + // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { } + DESTROYING: 'hlsDestroying', + // fired when a decrypt key loading starts - data: { frag : fragment object } + KEY_LOADING: 'hlsKeyLoading', + // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } } + KEY_LOADED: 'hlsKeyLoaded', + // fired upon stream controller state transitions - data: { previousState, nextState } + STREAM_STATE_TRANSITION: 'hlsStreamStateTransition' +}); + +/***/ }), +/* 2 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ErrorTypes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ErrorDetails; }); +var ErrorTypes = { + // Identifier for a network error (loading error / timeout ...) + NETWORK_ERROR: 'networkError', + // Identifier for a media Error (video/parsing/mediasource error) + MEDIA_ERROR: 'mediaError', + // Identifier for a mux Error (demuxing/remuxing) + MUX_ERROR: 'muxError', + // Identifier for all other errors + OTHER_ERROR: 'otherError' +}; + +var ErrorDetails = { + // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }} + MANIFEST_LOAD_ERROR: 'manifestLoadError', + // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }} + MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut', + // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason} + MANIFEST_PARSING_ERROR: 'manifestParsingError', + // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason} + MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError', + // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }} + LEVEL_LOAD_ERROR: 'levelLoadError', + // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }} + LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut', + // Identifier for a level switch error - data: { level : faulty level Id, event : error description} + LEVEL_SWITCH_ERROR: 'levelSwitchError', + // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }} + AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError', + // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }} + AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut', + // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }} + FRAG_LOAD_ERROR: 'fragLoadError', + // Identifier for fragment loop loading error - data: { frag : fragment object} + FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError', + // Identifier for fragment load timeout error - data: { frag : fragment object} + FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut', + // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description } + FRAG_DECRYPT_ERROR: 'fragDecryptError', + // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description } + // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release + FRAG_PARSING_ERROR: 'fragParsingError', + // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text } + REMUX_ALLOC_ERROR: 'remuxAllocError', + // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }} + KEY_LOAD_ERROR: 'keyLoadError', + // Identifier for decrypt key load timeout error - data: { frag : fragment object} + KEY_LOAD_TIMEOUT: 'keyLoadTimeOut', + // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType } + BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError', + // Identifier for a buffer append error - data: append error description + BUFFER_APPEND_ERROR: 'bufferAppendError', + // Identifier for a buffer appending error event - data: appending error description + BUFFER_APPENDING_ERROR: 'bufferAppendingError', + // Identifier for a buffer stalled error event + BUFFER_STALLED_ERROR: 'bufferStalledError', + // Identifier for a buffer full event + BUFFER_FULL_ERROR: 'bufferFullError', + // Identifier for a buffer seek over hole event + BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole', + // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area) + BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall', + // Identifier for an internal exception happening inside hls.js while handling an event + INTERNAL_EXCEPTION: 'internalException' +}; + +/***/ }), +/* 3 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return utf8ArrayToStr; }); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * ID3 parser + */ +var ID3 = function () { + function ID3() { + _classCallCheck(this, ID3); + } + + /** + * Returns true if an ID3 header can be found at offset in data + * @param {Uint8Array} data - The data to search in + * @param {number} offset - The offset at which to start searching + * @return {boolean} - True if an ID3 header is found + */ + ID3.isHeader = function isHeader(data, offset) { + /* + * http://id3.org/id3v2.3.0 + * [0] = 'I' + * [1] = 'D' + * [2] = '3' + * [3,4] = {Version} + * [5] = {Flags} + * [6-9] = {ID3 Size} + * + * An ID3v2 tag can be detected with the following pattern: + * $49 44 33 yy yy xx zz zz zz zz + * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80 + */ + if (offset + 10 <= data.length) { + //look for 'ID3' identifier + if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) { + //check version is within range + if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) { + //check size is within range + if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) { + return true; + } + } + } + } + + return false; + }; + + /** + * Returns true if an ID3 footer can be found at offset in data + * @param {Uint8Array} data - The data to search in + * @param {number} offset - The offset at which to start searching + * @return {boolean} - True if an ID3 footer is found + */ + + + ID3.isFooter = function isFooter(data, offset) { + /* + * The footer is a copy of the header, but with a different identifier + */ + if (offset + 10 <= data.length) { + //look for '3DI' identifier + if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) { + //check version is within range + if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) { + //check size is within range + if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) { + return true; + } + } + } + } + + return false; + }; + + /** + * Returns any adjacent ID3 tags found in data starting at offset, as one block of data + * @param {Uint8Array} data - The data to search in + * @param {number} offset - The offset at which to start searching + * @return {Uint8Array} - The block of data containing any ID3 tags found + */ + + + ID3.getID3Data = function getID3Data(data, offset) { + var front = offset; + var length = 0; + + while (ID3.isHeader(data, offset)) { + //ID3 header is 10 bytes + length += 10; + + var size = ID3._readSize(data, offset + 6); + length += size; + + if (ID3.isFooter(data, offset + 10)) { + //ID3 footer is 10 bytes + length += 10; + } + + offset += length; + } + + if (length > 0) { + return data.subarray(front, front + length); + } + + return undefined; + }; + + ID3._readSize = function _readSize(data, offset) { + var size = 0; + size = (data[offset] & 0x7f) << 21; + size |= (data[offset + 1] & 0x7f) << 14; + size |= (data[offset + 2] & 0x7f) << 7; + size |= data[offset + 3] & 0x7f; + return size; + }; + + /** + * Searches for the Elementary Stream timestamp found in the ID3 data chunk + * @param {Uint8Array} data - Block of data containing one or more ID3 tags + * @return {number} - The timestamp + */ + + + ID3.getTimeStamp = function getTimeStamp(data) { + var frames = ID3.getID3Frames(data); + for (var i = 0; i < frames.length; i++) { + var frame = frames[i]; + if (ID3.isTimeStampFrame(frame)) { + return ID3._readTimeStamp(frame); + } + } + + return undefined; + }; + + /** + * Returns true if the ID3 frame is an Elementary Stream timestamp frame + * @param {ID3 frame} frame + */ + + + ID3.isTimeStampFrame = function isTimeStampFrame(frame) { + return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp'; + }; + + ID3._getFrameData = function _getFrameData(data) { + /* + Frame ID $xx xx xx xx (four characters) + Size $xx xx xx xx + Flags $xx xx + */ + var type = String.fromCharCode(data[0], data[1], data[2], data[3]); + var size = ID3._readSize(data, 4); + + //skip frame id, size, and flags + var offset = 10; + + return { type: type, size: size, data: data.subarray(offset, offset + size) }; + }; + + /** + * Returns an array of ID3 frames found in all the ID3 tags in the id3Data + * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags + * @return {ID3 frame[]} - Array of ID3 frame objects + */ + + + ID3.getID3Frames = function getID3Frames(id3Data) { + var offset = 0; + var frames = []; + + while (ID3.isHeader(id3Data, offset)) { + var size = ID3._readSize(id3Data, offset + 6); + //skip past ID3 header + offset += 10; + var end = offset + size; + //loop through frames in the ID3 tag + while (offset + 8 < end) { + var frameData = ID3._getFrameData(id3Data.subarray(offset)); + var frame = ID3._decodeFrame(frameData); + if (frame) { + frames.push(frame); + } + //skip frame header and frame data + offset += frameData.size + 10; + } + + if (ID3.isFooter(id3Data, offset)) { + offset += 10; + } + } + + return frames; + }; + + ID3._decodeFrame = function _decodeFrame(frame) { + if (frame.type === 'PRIV') { + return ID3._decodePrivFrame(frame); + } else if (frame.type[0] === 'T') { + return ID3._decodeTextFrame(frame); + } else if (frame.type[0] === 'W') { + return ID3._decodeURLFrame(frame); + } + + return undefined; + }; + + ID3._readTimeStamp = function _readTimeStamp(timeStampFrame) { + if (timeStampFrame.data.byteLength === 8) { + var data = new Uint8Array(timeStampFrame.data); + // timestamp is 33 bit expressed as a big-endian eight-octet number, + // with the upper 31 bits set to zero. + var pts33Bit = data[3] & 0x1; + var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7]; + timestamp /= 45; + + if (pts33Bit) { + timestamp += 47721858.84; // 2^32 / 90 + } + + return Math.round(timestamp); + } + + return undefined; + }; + + ID3._decodePrivFrame = function _decodePrivFrame(frame) { + /* + Format: \0 + */ + if (frame.size < 2) { + return undefined; + } + + var owner = ID3._utf8ArrayToStr(frame.data); + var privateData = new Uint8Array(frame.data.subarray(owner.length + 1)); + + return { key: frame.type, info: owner, data: privateData.buffer }; + }; + + ID3._decodeTextFrame = function _decodeTextFrame(frame) { + if (frame.size < 2) { + return undefined; + } + + if (frame.type === 'TXXX') { + /* + Format: + [0] = {Text Encoding} + [1-?] = {Description}\0{Value} + */ + var index = 1; + var description = ID3._utf8ArrayToStr(frame.data.subarray(index)); + + index += description.length + 1; + var value = ID3._utf8ArrayToStr(frame.data.subarray(index)); + + return { key: frame.type, info: description, data: value }; + } else { + /* + Format: + [0] = {Text Encoding} + [1-?] = {Value} + */ + var text = ID3._utf8ArrayToStr(frame.data.subarray(1)); + return { key: frame.type, data: text }; + } + }; + + ID3._decodeURLFrame = function _decodeURLFrame(frame) { + if (frame.type === 'WXXX') { + /* + Format: + [0] = {Text Encoding} + [1-?] = {Description}\0{URL} + */ + if (frame.size < 2) { + return undefined; + } + + var index = 1; + var description = ID3._utf8ArrayToStr(frame.data.subarray(index)); + + index += description.length + 1; + var value = ID3._utf8ArrayToStr(frame.data.subarray(index)); + + return { key: frame.type, info: description, data: value }; + } else { + /* + Format: + [0-?] = {URL} + */ + var url = ID3._utf8ArrayToStr(frame.data); + return { key: frame.type, data: url }; + } + }; + + // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197 + // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt + /* utf.js - UTF-8 <=> UTF-16 convertion + * + * Copyright (C) 1999 Masanao Izumo + * Version: 1.0 + * LastModified: Dec 25 1999 + * This library is free. You can redistribute it and/or modify it. + */ + + + ID3._utf8ArrayToStr = function _utf8ArrayToStr(array) { + + var len = array.length; + var c = void 0; + var char2 = void 0; + var char3 = void 0; + var out = ''; + var i = 0; + while (i < len) { + c = array[i++]; + // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it + if (c === 0x00 || c === 0x03) { + continue; + } + switch (c >> 4) { + case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7: + // 0xxxxxxx + out += String.fromCharCode(c); + break; + case 12:case 13: + // 110x xxxx 10xx xxxx + char2 = array[i++]; + out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F); + break; + case 14: + // 1110 xxxx 10xx xxxx 10xx xxxx + char2 = array[i++]; + char3 = array[i++]; + out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0); + break; + default: + } + } + return out; + }; + + return ID3; +}(); + +var utf8ArrayToStr = ID3._utf8ArrayToStr; + +/* harmony default export */ __webpack_exports__["a"] = (ID3); + + + +/***/ }), +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; + +// CONCATENATED MODULE: ./src/crypt/aes-crypto.js +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var AESCrypto = function () { + function AESCrypto(subtle, iv) { + _classCallCheck(this, AESCrypto); + + this.subtle = subtle; + this.aesIV = iv; + } + + AESCrypto.prototype.decrypt = function decrypt(data, key) { + return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data); + }; + + return AESCrypto; +}(); + +/* harmony default export */ var aes_crypto = (AESCrypto); +// CONCATENATED MODULE: ./src/crypt/fast-aes-key.js +function fast_aes_key__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var FastAESKey = function () { + function FastAESKey(subtle, key) { + fast_aes_key__classCallCheck(this, FastAESKey); + + this.subtle = subtle; + this.key = key; + } + + FastAESKey.prototype.expandKey = function expandKey() { + return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']); + }; + + return FastAESKey; +}(); + +/* harmony default export */ var fast_aes_key = (FastAESKey); +// CONCATENATED MODULE: ./src/crypt/aes-decryptor.js +function aes_decryptor__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var AESDecryptor = function () { + function AESDecryptor() { + aes_decryptor__classCallCheck(this, AESDecryptor); + + // Static after running initTable + this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; + this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)]; + this.sBox = new Uint32Array(256); + this.invSBox = new Uint32Array(256); + + // Changes during runtime + this.key = new Uint32Array(0); + + this.initTable(); + } + + // Using view.getUint32() also swaps the byte order. + + + AESDecryptor.prototype.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) { + var view = new DataView(arrayBuffer); + var newArray = new Uint32Array(4); + for (var i = 0; i < 4; i++) { + newArray[i] = view.getUint32(i * 4); + } + return newArray; + }; + + AESDecryptor.prototype.initTable = function initTable() { + var sBox = this.sBox; + var invSBox = this.invSBox; + var subMix = this.subMix; + var subMix0 = subMix[0]; + var subMix1 = subMix[1]; + var subMix2 = subMix[2]; + var subMix3 = subMix[3]; + var invSubMix = this.invSubMix; + var invSubMix0 = invSubMix[0]; + var invSubMix1 = invSubMix[1]; + var invSubMix2 = invSubMix[2]; + var invSubMix3 = invSubMix[3]; + + var d = new Uint32Array(256); + var x = 0; + var xi = 0; + var i = 0; + for (i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = i << 1 ^ 0x11b; + } + } + + for (i = 0; i < 256; i++) { + var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4; + sx = sx >>> 8 ^ sx & 0xff ^ 0x63; + sBox[x] = sx; + invSBox[sx] = x; + + // Compute multiplication + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + + // Compute sub/invSub bytes, mix columns tables + var t = d[sx] * 0x101 ^ sx * 0x1010100; + subMix0[x] = t << 24 | t >>> 8; + subMix1[x] = t << 16 | t >>> 16; + subMix2[x] = t << 8 | t >>> 24; + subMix3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100; + invSubMix0[sx] = t << 24 | t >>> 8; + invSubMix1[sx] = t << 16 | t >>> 16; + invSubMix2[sx] = t << 8 | t >>> 24; + invSubMix3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + }; + + AESDecryptor.prototype.expandKey = function expandKey(keyBuffer) { + // convert keyBuffer to Uint32Array + var key = this.uint8ArrayToUint32Array_(keyBuffer); + var sameKey = true; + var offset = 0; + + while (offset < key.length && sameKey) { + sameKey = key[offset] === this.key[offset]; + offset++; + } + + if (sameKey) { + return; + } + + this.key = key; + var keySize = this.keySize = key.length; + + if (keySize !== 4 && keySize !== 6 && keySize !== 8) { + throw new Error('Invalid aes key size=' + keySize); + } + + var ksRows = this.ksRows = (keySize + 6 + 1) * 4; + var ksRow = void 0; + var invKsRow = void 0; + + var keySchedule = this.keySchedule = new Uint32Array(ksRows); + var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows); + var sbox = this.sBox; + var rcon = this.rcon; + + var invSubMix = this.invSubMix; + var invSubMix0 = invSubMix[0]; + var invSubMix1 = invSubMix[1]; + var invSubMix2 = invSubMix[2]; + var invSubMix3 = invSubMix[3]; + + var prev = void 0; + var t = void 0; + + for (ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + prev = keySchedule[ksRow] = key[ksRow]; + continue; + } + t = prev; + + if (ksRow % keySize === 0) { + // Rot word + t = t << 8 | t >>> 24; + + // Sub word + t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; + + // Mix Rcon + t ^= rcon[ksRow / keySize | 0] << 24; + } else if (keySize > 6 && ksRow % keySize === 4) { + // Sub word + t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; + } + + keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0; + } + + for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { + ksRow = ksRows - invKsRow; + if (invKsRow & 3) { + t = keySchedule[ksRow]; + } else { + t = keySchedule[ksRow - 4]; + } + + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]]; + } + + invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0; + } + }; + + // Adding this as a method greatly improves performance. + + + AESDecryptor.prototype.networkToHostOrderSwap = function networkToHostOrderSwap(word) { + return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24; + }; + + AESDecryptor.prototype.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) { + var nRounds = this.keySize + 6; + var invKeySchedule = this.invKeySchedule; + var invSBOX = this.invSBox; + + var invSubMix = this.invSubMix; + var invSubMix0 = invSubMix[0]; + var invSubMix1 = invSubMix[1]; + var invSubMix2 = invSubMix[2]; + var invSubMix3 = invSubMix[3]; + + var initVector = this.uint8ArrayToUint32Array_(aesIV); + var initVector0 = initVector[0]; + var initVector1 = initVector[1]; + var initVector2 = initVector[2]; + var initVector3 = initVector[3]; + + var inputInt32 = new Int32Array(inputArrayBuffer); + var outputInt32 = new Int32Array(inputInt32.length); + + var t0 = void 0, + t1 = void 0, + t2 = void 0, + t3 = void 0; + var s0 = void 0, + s1 = void 0, + s2 = void 0, + s3 = void 0; + var inputWords0 = void 0, + inputWords1 = void 0, + inputWords2 = void 0, + inputWords3 = void 0; + + var ksRow, i; + var swapWord = this.networkToHostOrderSwap; + + while (offset < inputInt32.length) { + inputWords0 = swapWord(inputInt32[offset]); + inputWords1 = swapWord(inputInt32[offset + 1]); + inputWords2 = swapWord(inputInt32[offset + 2]); + inputWords3 = swapWord(inputInt32[offset + 3]); + + s0 = inputWords0 ^ invKeySchedule[0]; + s1 = inputWords3 ^ invKeySchedule[1]; + s2 = inputWords2 ^ invKeySchedule[2]; + s3 = inputWords1 ^ invKeySchedule[3]; + + ksRow = 4; + + // Iterate through the rounds of decryption + for (i = 1; i < nRounds; i++) { + t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow]; + t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1]; + t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2]; + t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + + ksRow = ksRow + 4; + } + + // Shift rows, sub bytes, add round key + t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow]; + t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1]; + t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2]; + t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; + ksRow = ksRow + 3; + + // Write + outputInt32[offset] = swapWord(t0 ^ initVector0); + outputInt32[offset + 1] = swapWord(t3 ^ initVector1); + outputInt32[offset + 2] = swapWord(t2 ^ initVector2); + outputInt32[offset + 3] = swapWord(t1 ^ initVector3); + + // reset initVector to last 4 unsigned int + initVector0 = inputWords0; + initVector1 = inputWords1; + initVector2 = inputWords2; + initVector3 = inputWords3; + + offset = offset + 4; + } + + return outputInt32.buffer; + }; + + AESDecryptor.prototype.destroy = function destroy() { + this.key = undefined; + this.keySize = undefined; + this.ksRows = undefined; + + this.sBox = undefined; + this.invSBox = undefined; + this.subMix = undefined; + this.invSubMix = undefined; + this.keySchedule = undefined; + this.invKeySchedule = undefined; + + this.rcon = undefined; + }; + + return AESDecryptor; +}(); + +/* harmony default export */ var aes_decryptor = (AESDecryptor); +// EXTERNAL MODULE: ./src/errors.js +var errors = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/utils/logger.js +var logger = __webpack_require__(0); + +// CONCATENATED MODULE: ./src/crypt/decrypter.js +function decrypter__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + + + + +/*globals self: false */ + +var decrypter_Decrypter = function () { + function Decrypter(observer, config) { + decrypter__classCallCheck(this, Decrypter); + + this.observer = observer; + this.config = config; + this.logEnabled = true; + try { + var browserCrypto = crypto ? crypto : self.crypto; + this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle; + } catch (e) {} + this.disableWebCrypto = !this.subtle; + } + + Decrypter.prototype.isSync = function isSync() { + return this.disableWebCrypto && this.config.enableSoftwareAES; + }; + + Decrypter.prototype.decrypt = function decrypt(data, key, iv, callback) { + var _this = this; + + if (this.disableWebCrypto && this.config.enableSoftwareAES) { + if (this.logEnabled) { + logger["b" /* logger */].log('JS AES decrypt'); + this.logEnabled = false; + } + var decryptor = this.decryptor; + if (!decryptor) { + this.decryptor = decryptor = new aes_decryptor(); + } + decryptor.expandKey(key); + callback(decryptor.decrypt(data, 0, iv)); + } else { + if (this.logEnabled) { + logger["b" /* logger */].log('WebCrypto AES decrypt'); + this.logEnabled = false; + } + var subtle = this.subtle; + if (this.key !== key) { + this.key = key; + this.fastAesKey = new fast_aes_key(subtle, key); + } + + this.fastAesKey.expandKey().then(function (aesKey) { + // decrypt using web crypto + var crypto = new aes_crypto(subtle, iv); + crypto.decrypt(data, aesKey).catch(function (err) { + _this.onWebCryptoError(err, data, key, iv, callback); + }).then(function (result) { + callback(result); + }); + }).catch(function (err) { + _this.onWebCryptoError(err, data, key, iv, callback); + }); + } + }; + + Decrypter.prototype.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) { + if (this.config.enableSoftwareAES) { + logger["b" /* logger */].log('WebCrypto Error, disable WebCrypto API'); + this.disableWebCrypto = true; + this.logEnabled = true; + this.decrypt(data, key, iv, callback); + } else { + logger["b" /* logger */].error('decrypting error : ' + err.message); + this.observer.trigger(Event.ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_DECRYPT_ERROR, fatal: true, reason: err.message }); + } + }; + + Decrypter.prototype.destroy = function destroy() { + var decryptor = this.decryptor; + if (decryptor) { + decryptor.destroy(); + this.decryptor = undefined; + } + }; + + return Decrypter; +}(); + +/* harmony default export */ var decrypter = __webpack_exports__["a"] = (decrypter_Decrypter); + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +// see https://tools.ietf.org/html/rfc1808 + +/* jshint ignore:start */ +(function(root) { +/* jshint ignore:end */ + + var URL_REGEX = /^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/; + var FIRST_SEGMENT_REGEX = /^([^\/;?#]*)(.*)$/; + var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g; + var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g; + + var URLToolkit = { // jshint ignore:line + // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or // + // E.g + // With opts.alwaysNormalize = false (default, spec compliant) + // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g + // With opts.alwaysNormalize = true (default, not spec compliant) + // http://a.com/b/cd + /e/f/../g => http://a.com/e/g + buildAbsoluteURL: function(baseURL, relativeURL, opts) { + opts = opts || {}; + // remove any remaining space and CRLF + baseURL = baseURL.trim(); + relativeURL = relativeURL.trim(); + if (!relativeURL) { + // 2a) If the embedded URL is entirely empty, it inherits the + // entire base URL (i.e., is set equal to the base URL) + // and we are done. + if (!opts.alwaysNormalize) { + return baseURL; + } + var basePartsForNormalise = this.parseURL(baseURL); + if (!baseParts) { + throw new Error('Error trying to parse base URL.'); + } + basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path); + return URLToolkit.buildURLFromParts(basePartsForNormalise); + } + var relativeParts = this.parseURL(relativeURL); + if (!relativeParts) { + throw new Error('Error trying to parse relative URL.'); + } + if (relativeParts.scheme) { + // 2b) If the embedded URL starts with a scheme name, it is + // interpreted as an absolute URL and we are done. + if (!opts.alwaysNormalize) { + return relativeURL; + } + relativeParts.path = URLToolkit.normalizePath(relativeParts.path); + return URLToolkit.buildURLFromParts(relativeParts); + } + var baseParts = this.parseURL(baseURL); + if (!baseParts) { + throw new Error('Error trying to parse base URL.'); + } + if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') { + // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc + // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a' + var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path); + baseParts.netLoc = pathParts[1]; + baseParts.path = pathParts[2]; + } + if (baseParts.netLoc && !baseParts.path) { + baseParts.path = '/'; + } + var builtParts = { + // 2c) Otherwise, the embedded URL inherits the scheme of + // the base URL. + scheme: baseParts.scheme, + netLoc: relativeParts.netLoc, + path: null, + params: relativeParts.params, + query: relativeParts.query, + fragment: relativeParts.fragment + }; + if (!relativeParts.netLoc) { + // 3) If the embedded URL's is non-empty, we skip to + // Step 7. Otherwise, the embedded URL inherits the + // (if any) of the base URL. + builtParts.netLoc = baseParts.netLoc; + // 4) If the embedded URL path is preceded by a slash "/", the + // path is not relative and we skip to Step 7. + if (relativeParts.path[0] !== '/') { + if (!relativeParts.path) { + // 5) If the embedded URL path is empty (and not preceded by a + // slash), then the embedded URL inherits the base URL path + builtParts.path = baseParts.path; + // 5a) if the embedded URL's is non-empty, we skip to + // step 7; otherwise, it inherits the of the base + // URL (if any) and + if (!relativeParts.params) { + builtParts.params = baseParts.params; + // 5b) if the embedded URL's is non-empty, we skip to + // step 7; otherwise, it inherits the of the base + // URL (if any) and we skip to step 7. + if (!relativeParts.query) { + builtParts.query = baseParts.query; + } + } + } else { + // 6) The last segment of the base URL's path (anything + // following the rightmost slash "/", or the entire path if no + // slash is present) is removed and the embedded URL's path is + // appended in its place. + var baseURLPath = baseParts.path; + var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path; + builtParts.path = URLToolkit.normalizePath(newPath); + } + } + } + if (builtParts.path === null) { + builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path; + } + return URLToolkit.buildURLFromParts(builtParts); + }, + parseURL: function(url) { + var parts = URL_REGEX.exec(url); + if (!parts) { + return null; + } + return { + scheme: parts[1] || '', + netLoc: parts[2] || '', + path: parts[3] || '', + params: parts[4] || '', + query: parts[5] || '', + fragment: parts[6] || '' + }; + }, + normalizePath: function(path) { + // The following operations are + // then applied, in order, to the new path: + // 6a) All occurrences of "./", where "." is a complete path + // segment, are removed. + // 6b) If the path ends with "." as a complete path segment, + // that "." is removed. + path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); + // 6c) All occurrences of "/../", where is a + // complete path segment not equal to "..", are removed. + // Removal of these path segments is performed iteratively, + // removing the leftmost matching pattern on each iteration, + // until no matching pattern remains. + // 6d) If the path ends with "/..", where is a + // complete path segment not equal to "..", that + // "/.." is removed. + while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line + return path.split('').reverse().join(''); + }, + buildURLFromParts: function(parts) { + return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment; + } + }; + +/* jshint ignore:start */ + if(true) + module.exports = URLToolkit; + else if(typeof define === 'function' && define.amd) + define([], function() { return URLToolkit; }); + else if(typeof exports === 'object') + exports["URLToolkit"] = URLToolkit; + else + root["URLToolkit"] = URLToolkit; +})(this); +/* jshint ignore:end */ + + +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; + +// EXTERNAL MODULE: ./src/events.js +var events = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/errors.js +var errors = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules +var crypt_decrypter = __webpack_require__(4); + +// EXTERNAL MODULE: ./src/utils/logger.js +var logger = __webpack_require__(0); + +// CONCATENATED MODULE: ./src/demux/adts.js +/** + * ADTS parser helper + */ + + + +function getAudioConfig(observer, data, offset, audioCodec) { + var adtsObjectType, + // :int + adtsSampleingIndex, + // :int + adtsExtensionSampleingIndex, + // :int + adtsChanelConfig, + // :int + config, + userAgent = navigator.userAgent.toLowerCase(), + manifestCodec = audioCodec, + adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; + // byte 2 + adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1; + adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2; + if (adtsSampleingIndex > adtsSampleingRates.length - 1) { + observer.trigger(Event.ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex }); + return; + } + adtsChanelConfig = (data[offset + 2] & 0x01) << 2; + // byte 3 + adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6; + logger["b" /* logger */].log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig); + // firefox: freq less than 24kHz = AAC SBR (HE-AAC) + if (/firefox/i.test(userAgent)) { + if (adtsSampleingIndex >= 6) { + adtsObjectType = 5; + config = new Array(4); + // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies + // there is a factor 2 between frame sample rate and output sample rate + // multiply frequency by 2 (see table below, equivalent to substract 3) + adtsExtensionSampleingIndex = adtsSampleingIndex - 3; + } else { + adtsObjectType = 2; + config = new Array(2); + adtsExtensionSampleingIndex = adtsSampleingIndex; + } + // Android : always use AAC + } else if (userAgent.indexOf('android') !== -1) { + adtsObjectType = 2; + config = new Array(2); + adtsExtensionSampleingIndex = adtsSampleingIndex; + } else { + /* for other browsers (Chrome/Vivaldi/Opera ...) + always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...) + */ + adtsObjectType = 5; + config = new Array(4); + // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz) + if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) { + // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies + // there is a factor 2 between frame sample rate and output sample rate + // multiply frequency by 2 (see table below, equivalent to substract 3) + adtsExtensionSampleingIndex = adtsSampleingIndex - 3; + } else { + // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio) + // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo. + if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) { + adtsObjectType = 2; + config = new Array(2); + } + adtsExtensionSampleingIndex = adtsSampleingIndex; + } + } + /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config + ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig() + Audio Profile / Audio Object Type + 0: Null + 1: AAC Main + 2: AAC LC (Low Complexity) + 3: AAC SSR (Scalable Sample Rate) + 4: AAC LTP (Long Term Prediction) + 5: SBR (Spectral Band Replication) + 6: AAC Scalable + sampling freq + 0: 96000 Hz + 1: 88200 Hz + 2: 64000 Hz + 3: 48000 Hz + 4: 44100 Hz + 5: 32000 Hz + 6: 24000 Hz + 7: 22050 Hz + 8: 16000 Hz + 9: 12000 Hz + 10: 11025 Hz + 11: 8000 Hz + 12: 7350 Hz + 13: Reserved + 14: Reserved + 15: frequency is written explictly + Channel Configurations + These are the channel configurations: + 0: Defined in AOT Specifc Config + 1: 1 channel: front-center + 2: 2 channels: front-left, front-right + */ + // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1 + config[0] = adtsObjectType << 3; + // samplingFrequencyIndex + config[0] |= (adtsSampleingIndex & 0x0E) >> 1; + config[1] |= (adtsSampleingIndex & 0x01) << 7; + // channelConfiguration + config[1] |= adtsChanelConfig << 3; + if (adtsObjectType === 5) { + // adtsExtensionSampleingIndex + config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1; + config[2] = (adtsExtensionSampleingIndex & 0x01) << 7; + // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ??? + // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc + config[2] |= 2 << 2; + config[3] = 0; + } + return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec }; +} + +function isHeaderPattern(data, offset) { + return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0; +} + +function getHeaderLength(data, offset) { + return !!(data[offset + 1] & 0x01) ? 7 : 9; +} + +function getFullFrameLength(data, offset) { + return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5; +} + +function isHeader(data, offset) { + // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1 + // Layer bits (position 14 and 15) in header should be always 0 for ADTS + // More info https://wiki.multimedia.cx/index.php?title=ADTS + if (offset + 1 < data.length && isHeaderPattern(data, offset)) { + return true; + } + return false; +} + +function adts_probe(data, offset) { + // same as isHeader but we also check that ADTS frame follows last ADTS frame + // or end of data is reached + if (offset + 1 < data.length && isHeaderPattern(data, offset)) { + // ADTS header Length + var headerLength = getHeaderLength(data, offset); + // ADTS frame Length + var frameLength = headerLength; + if (offset + 5 < data.length) { + frameLength = getFullFrameLength(data, offset); + } + var newOffset = offset + frameLength; + if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) { + return true; + } + } + return false; +} + +function initTrackConfig(track, observer, data, offset, audioCodec) { + if (!track.samplerate) { + var config = getAudioConfig(observer, data, offset, audioCodec); + track.config = config.config; + track.samplerate = config.samplerate; + track.channelCount = config.channelCount; + track.codec = config.codec; + track.manifestCodec = config.manifestCodec; + logger["b" /* logger */].log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount); + } +} + +function getFrameDuration(samplerate) { + return 1024 * 90000 / samplerate; +} + +function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) { + var headerLength, frameLength, stamp; + var length = data.length; + + // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header + headerLength = getHeaderLength(data, offset); + // retrieve frame size + frameLength = getFullFrameLength(data, offset); + frameLength -= headerLength; + + if (frameLength > 0 && offset + headerLength + frameLength <= length) { + stamp = pts + frameIndex * frameDuration; + //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`); + return { headerLength: headerLength, frameLength: frameLength, stamp: stamp }; + } + + return undefined; +} + +function appendFrame(track, data, offset, pts, frameIndex) { + var frameDuration = getFrameDuration(track.samplerate); + var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration); + if (header) { + var stamp = header.stamp; + var headerLength = header.headerLength; + var frameLength = header.frameLength; + + //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`); + var aacSample = { + unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), + pts: stamp, + dts: stamp + }; + + track.samples.push(aacSample); + track.len += frameLength; + + return { sample: aacSample, length: frameLength + headerLength }; + } + + return undefined; +} +// EXTERNAL MODULE: ./src/demux/id3.js +var id3 = __webpack_require__(3); + +// CONCATENATED MODULE: ./src/demux/aacdemuxer.js +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * AAC demuxer + */ + + + + +var aacdemuxer_AACDemuxer = function () { + function AACDemuxer(observer, remuxer, config) { + _classCallCheck(this, AACDemuxer); + + this.observer = observer; + this.config = config; + this.remuxer = remuxer; + } + + AACDemuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { + this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 }; + }; + + AACDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {}; + + AACDemuxer.probe = function probe(data) { + if (!data) { + return false; + } + // Check for the ADTS sync word + // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1 + // Layer bits (position 14 and 15) in header should be always 0 for ADTS + // More info https://wiki.multimedia.cx/index.php?title=ADTS + var id3Data = id3["a" /* default */].getID3Data(data, 0) || []; + var offset = id3Data.length; + + for (var length = data.length; offset < length; offset++) { + if (adts_probe(data, offset)) { + logger["b" /* logger */].log('ADTS sync word found !'); + return true; + } + } + return false; + }; + + // feed incoming data to the front of the parsing pipeline + + + AACDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) { + var track = this._audioTrack; + var id3Data = id3["a" /* default */].getID3Data(data, 0) || []; + var timestamp = id3["a" /* default */].getTimeStamp(id3Data); + var pts = timestamp ? 90 * timestamp : timeOffset * 90000; + var frameIndex = 0; + var stamp = pts; + var length = data.length; + var offset = id3Data.length; + + var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }]; + + while (offset < length - 1) { + if (isHeader(data, offset) && offset + 5 < length) { + initTrackConfig(track, this.observer, data, offset, track.manifestCodec); + var frame = appendFrame(track, data, offset, pts, frameIndex); + if (frame) { + offset += frame.length; + stamp = frame.sample.pts; + frameIndex++; + } else { + logger["b" /* logger */].log('Unable to parse AAC frame'); + break; + } + } else if (id3["a" /* default */].isHeader(data, offset)) { + id3Data = id3["a" /* default */].getID3Data(data, offset); + id3Samples.push({ pts: stamp, dts: stamp, data: id3Data }); + offset += id3Data.length; + } else { + //nothing found, keep looking + offset++; + } + } + + this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset); + }; + + AACDemuxer.prototype.destroy = function destroy() {}; + + return AACDemuxer; +}(); + +/* harmony default export */ var aacdemuxer = (aacdemuxer_AACDemuxer); +// CONCATENATED MODULE: ./src/demux/mp4demuxer.js +function mp4demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * MP4 demuxer + */ + + + +var UINT32_MAX = Math.pow(2, 32) - 1; + +var mp4demuxer_MP4Demuxer = function () { + function MP4Demuxer(observer, remuxer) { + mp4demuxer__classCallCheck(this, MP4Demuxer); + + this.observer = observer; + this.remuxer = remuxer; + } + + MP4Demuxer.prototype.resetTimeStamp = function resetTimeStamp(initPTS) { + this.initPTS = initPTS; + }; + + MP4Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { + //jshint unused:false + if (initSegment && initSegment.byteLength) { + var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment); + + // default audio codec if nothing specified + // TODO : extract that from initsegment + if (audioCodec == null) { + audioCodec = 'mp4a.40.5'; + } + if (videoCodec == null) { + videoCodec = 'avc1.42e01e'; + } + var tracks = {}; + if (initData.audio && initData.video) { + tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null }; + } else { + if (initData.audio) { + tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null }; + } + if (initData.video) { + tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null }; + } + } + this.observer.trigger(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, { tracks: tracks }); + } else { + if (audioCodec) { + this.audioCodec = audioCodec; + } + if (videoCodec) { + this.videoCodec = videoCodec; + } + } + }; + + MP4Demuxer.probe = function probe(data) { + // ensure we find a moof box in the first 16 kB + return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0; + }; + + MP4Demuxer.bin2str = function bin2str(buffer) { + return String.fromCharCode.apply(null, buffer); + }; + + MP4Demuxer.readUint32 = function readUint32(buffer, offset) { + if (buffer.data) { + offset += buffer.start; + buffer = buffer.data; + } + + var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3]; + return val < 0 ? 4294967296 + val : val; + }; + + MP4Demuxer.writeUint32 = function writeUint32(buffer, offset, value) { + if (buffer.data) { + offset += buffer.start; + buffer = buffer.data; + } + buffer[offset] = value >> 24; + buffer[offset + 1] = value >> 16 & 0xff; + buffer[offset + 2] = value >> 8 & 0xff; + buffer[offset + 3] = value & 0xff; + }; + + // Find the data for a box specified by its path + + + MP4Demuxer.findBox = function findBox(data, path) { + var results = [], + i, + size, + type, + end, + subresults, + start, + endbox; + + if (data.data) { + start = data.start; + end = data.end; + data = data.data; + } else { + start = 0; + end = data.byteLength; + } + + if (!path.length) { + // short-circuit the search for empty paths + return null; + } + + for (i = start; i < end;) { + size = MP4Demuxer.readUint32(data, i); + type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8)); + endbox = size > 1 ? i + size : end; + + if (type === path[0]) { + + if (path.length === 1) { + // this is the end of the path and we've found the box we were + // looking for + results.push({ data: data, start: i + 8, end: endbox }); + } else { + // recursively search for the next box along the path + subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1)); + if (subresults.length) { + results = results.concat(subresults); + } + } + } + i = endbox; + } + + // we've finished searching all of data + return results; + }; + + /** + * Parses an MP4 initialization segment and extracts stream type and + * timescale values for any declared tracks. Timescale values indicate the + * number of clock ticks per second to assume for time-based values + * elsewhere in the MP4. + * + * To determine the start time of an MP4, you need two pieces of + * information: the timescale unit and the earliest base media decode + * time. Multiple timescales can be specified within an MP4 but the + * base media decode time is always expressed in the timescale from + * the media header box for the track: + * ``` + * moov > trak > mdia > mdhd.timescale + * moov > trak > mdia > hdlr + * ``` + * @param init {Uint8Array} the bytes of the init segment + * @return {object} a hash of track type to timescale values or null if + * the init segment is malformed. + */ + + + MP4Demuxer.parseInitSegment = function parseInitSegment(initSegment) { + var result = []; + var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']); + + traks.forEach(function (trak) { + var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0]; + if (tkhd) { + var version = tkhd.data[tkhd.start]; + var index = version === 0 ? 12 : 20; + var trackId = MP4Demuxer.readUint32(tkhd, index); + + var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0]; + if (mdhd) { + version = mdhd.data[mdhd.start]; + index = version === 0 ? 12 : 20; + var timescale = MP4Demuxer.readUint32(mdhd, index); + + var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0]; + if (hdlr) { + var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12)); + var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType]; + if (type) { + // extract codec info. TODO : parse codec details to be able to build MIME type + var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']); + if (codecBox.length) { + codecBox = codecBox[0]; + var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16)); + logger["b" /* logger */].log('MP4Demuxer:' + type + ':' + codecType + ' found'); + } + result[trackId] = { timescale: timescale, type: type }; + result[type] = { timescale: timescale, id: trackId }; + } + } + } + } + }); + return result; + }; + + /** + * Determine the base media decode start time, in seconds, for an MP4 + * fragment. If multiple fragments are specified, the earliest time is + * returned. + * + * The base media decode time can be parsed from track fragment + * metadata: + * ``` + * moof > traf > tfdt.baseMediaDecodeTime + * ``` + * It requires the timescale value from the mdhd to interpret. + * + * @param timescale {object} a hash of track ids to timescale values. + * @return {number} the earliest base media decode start time for the + * fragment, in seconds + */ + + + MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) { + var trafs, baseTimes, result; + + // we need info from two childrend of each track fragment box + trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']); + + // determine the start times for each track + baseTimes = [].concat.apply([], trafs.map(function (traf) { + return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) { + var id, scale, baseTime; + + // get the track id from the tfhd + id = MP4Demuxer.readUint32(tfhd, 4); + // assume a 90kHz clock if no timescale was specified + scale = initData[id].timescale || 90e3; + + // get the base media decode time from the tfdt + baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) { + var version, result; + + version = tfdt.data[tfdt.start]; + result = MP4Demuxer.readUint32(tfdt, 4); + if (version === 1) { + result *= Math.pow(2, 32); + + result += MP4Demuxer.readUint32(tfdt, 8); + } + return result; + })[0]; + // convert base time to seconds + return baseTime / scale; + }); + })); + + // return the minimum + result = Math.min.apply(null, baseTimes); + return isFinite(result) ? result : 0; + }; + + MP4Demuxer.offsetStartDTS = function offsetStartDTS(initData, fragment, timeOffset) { + MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) { + return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) { + // get the track id from the tfhd + var id = MP4Demuxer.readUint32(tfhd, 4); + // assume a 90kHz clock if no timescale was specified + var timescale = initData[id].timescale || 90e3; + + // get the base media decode time from the tfdt + MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) { + var version = tfdt.data[tfdt.start]; + var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4); + if (version === 0) { + MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale); + } else { + baseMediaDecodeTime *= Math.pow(2, 32); + baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8); + baseMediaDecodeTime -= timeOffset * timescale; + baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0); + var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)); + var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1)); + MP4Demuxer.writeUint32(tfdt, 4, upper); + MP4Demuxer.writeUint32(tfdt, 8, lower); + } + }); + }); + }); + }; + + // feed incoming data to the front of the parsing pipeline + + + MP4Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) { + var initData = this.initData; + if (!initData) { + this.resetInitSegment(data, this.audioCodec, this.videoCodec); + initData = this.initData; + } + var startDTS = void 0, + initPTS = this.initPTS; + if (initPTS === undefined) { + var _startDTS = MP4Demuxer.getStartDTS(initData, data); + this.initPTS = initPTS = _startDTS - timeOffset; + this.observer.trigger(events["a" /* default */].INIT_PTS_FOUND, { initPTS: initPTS }); + } + MP4Demuxer.offsetStartDTS(initData, data, initPTS); + startDTS = MP4Demuxer.getStartDTS(initData, data); + this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data); + }; + + MP4Demuxer.prototype.destroy = function destroy() {}; + + return MP4Demuxer; +}(); + +/* harmony default export */ var mp4demuxer = (mp4demuxer_MP4Demuxer); +// CONCATENATED MODULE: ./src/demux/mpegaudio.js +/** + * MPEG parser helper + */ + +var MpegAudio = { + + BitratesMap: [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160], + + SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000], + + appendFrame: function appendFrame(track, data, offset, pts, frameIndex) { + // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference + if (offset + 24 > data.length) { + return undefined; + } + + var header = this.parseHeader(data, offset); + if (header && offset + header.frameLength <= data.length) { + var frameDuration = 1152 * 90000 / header.sampleRate; + var stamp = pts + frameIndex * frameDuration; + var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp }; + + track.config = []; + track.channelCount = header.channelCount; + track.samplerate = header.sampleRate; + track.samples.push(sample); + track.len += header.frameLength; + + return { sample: sample, length: header.frameLength }; + } + + return undefined; + }, + + parseHeader: function parseHeader(data, offset) { + var headerB = data[offset + 1] >> 3 & 3; + var headerC = data[offset + 1] >> 1 & 3; + var headerE = data[offset + 2] >> 4 & 15; + var headerF = data[offset + 2] >> 2 & 3; + var headerG = !!(data[offset + 2] & 2); + if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) { + var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4; + var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000; + var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2; + var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF]; + var padding = headerG ? 1 : 0; + var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono) + var frameLength = headerC === 3 ? (headerB === 3 ? 12 : 6) * bitRate / sampleRate + padding << 2 : (headerB === 3 ? 144 : 72) * bitRate / sampleRate + padding | 0; + + return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength }; + } + + return undefined; + }, + + isHeaderPattern: function isHeaderPattern(data, offset) { + return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00; + }, + + isHeader: function isHeader(data, offset) { + // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1 + // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III) + // More info http://www.mp3-tech.org/programmer/frame_header.html + if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) { + return true; + } + return false; + }, + + probe: function probe(data, offset) { + // same as isHeader but we also check that MPEG frame follows last MPEG frame + // or end of data is reached + if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) { + // MPEG header Length + var headerLength = 4; + // MPEG frame Length + var header = this.parseHeader(data, offset); + var frameLength = headerLength; + if (header && header.frameLength) { + frameLength = header.frameLength; + } + var newOffset = offset + frameLength; + if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) { + return true; + } + } + return false; + } +}; + +/* harmony default export */ var mpegaudio = (MpegAudio); +// CONCATENATED MODULE: ./src/demux/exp-golomb.js +function exp_golomb__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264. +*/ + + + +var exp_golomb_ExpGolomb = function () { + function ExpGolomb(data) { + exp_golomb__classCallCheck(this, ExpGolomb); + + this.data = data; + // the number of bytes left to examine in this.data + this.bytesAvailable = data.byteLength; + // the current word being examined + this.word = 0; // :uint + // the number of bits left to examine in the current word + this.bitsAvailable = 0; // :uint + } + + // ():void + + + ExpGolomb.prototype.loadWord = function loadWord() { + var data = this.data, + bytesAvailable = this.bytesAvailable, + position = data.byteLength - bytesAvailable, + workingBytes = new Uint8Array(4), + availableBytes = Math.min(4, bytesAvailable); + if (availableBytes === 0) { + throw new Error('no bytes available'); + } + workingBytes.set(data.subarray(position, position + availableBytes)); + this.word = new DataView(workingBytes.buffer).getUint32(0); + // track the amount of this.data that has been processed + this.bitsAvailable = availableBytes * 8; + this.bytesAvailable -= availableBytes; + }; + + // (count:int):void + + + ExpGolomb.prototype.skipBits = function skipBits(count) { + var skipBytes; // :int + if (this.bitsAvailable > count) { + this.word <<= count; + this.bitsAvailable -= count; + } else { + count -= this.bitsAvailable; + skipBytes = count >> 3; + count -= skipBytes >> 3; + this.bytesAvailable -= skipBytes; + this.loadWord(); + this.word <<= count; + this.bitsAvailable -= count; + } + }; + + // (size:int):uint + + + ExpGolomb.prototype.readBits = function readBits(size) { + var bits = Math.min(this.bitsAvailable, size), + // :uint + valu = this.word >>> 32 - bits; // :uint + if (size > 32) { + logger["b" /* logger */].error('Cannot read more than 32 bits at a time'); + } + this.bitsAvailable -= bits; + if (this.bitsAvailable > 0) { + this.word <<= bits; + } else if (this.bytesAvailable > 0) { + this.loadWord(); + } + bits = size - bits; + if (bits > 0 && this.bitsAvailable) { + return valu << bits | this.readBits(bits); + } else { + return valu; + } + }; + + // ():uint + + + ExpGolomb.prototype.skipLZ = function skipLZ() { + var leadingZeroCount; // :uint + for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { + if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) { + // the first bit of working word is 1 + this.word <<= leadingZeroCount; + this.bitsAvailable -= leadingZeroCount; + return leadingZeroCount; + } + } + // we exhausted word and still have not found a 1 + this.loadWord(); + return leadingZeroCount + this.skipLZ(); + }; + + // ():void + + + ExpGolomb.prototype.skipUEG = function skipUEG() { + this.skipBits(1 + this.skipLZ()); + }; + + // ():void + + + ExpGolomb.prototype.skipEG = function skipEG() { + this.skipBits(1 + this.skipLZ()); + }; + + // ():uint + + + ExpGolomb.prototype.readUEG = function readUEG() { + var clz = this.skipLZ(); // :uint + return this.readBits(clz + 1) - 1; + }; + + // ():int + + + ExpGolomb.prototype.readEG = function readEG() { + var valu = this.readUEG(); // :int + if (0x01 & valu) { + // the number is odd if the low order bit is set + return 1 + valu >>> 1; // add 1 to make it even, and divide by 2 + } else { + return -1 * (valu >>> 1); // divide by two then make it negative + } + }; + + // Some convenience functions + // :Boolean + + + ExpGolomb.prototype.readBoolean = function readBoolean() { + return 1 === this.readBits(1); + }; + + // ():int + + + ExpGolomb.prototype.readUByte = function readUByte() { + return this.readBits(8); + }; + + // ():int + + + ExpGolomb.prototype.readUShort = function readUShort() { + return this.readBits(16); + }; + // ():int + + + ExpGolomb.prototype.readUInt = function readUInt() { + return this.readBits(32); + }; + + /** + * Advance the ExpGolomb decoder past a scaling list. The scaling + * list is optionally transmitted as part of a sequence parameter + * set and is not relevant to transmuxing. + * @param count {number} the number of entries in this scaling list + * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1 + */ + + + ExpGolomb.prototype.skipScalingList = function skipScalingList(count) { + var lastScale = 8, + nextScale = 8, + j, + deltaScale; + for (j = 0; j < count; j++) { + if (nextScale !== 0) { + deltaScale = this.readEG(); + nextScale = (lastScale + deltaScale + 256) % 256; + } + lastScale = nextScale === 0 ? lastScale : nextScale; + } + }; + + /** + * Read a sequence parameter set and return some interesting video + * properties. A sequence parameter set is the H264 metadata that + * describes the properties of upcoming video frames. + * @param data {Uint8Array} the bytes of a sequence parameter set + * @return {object} an object with configuration parsed from the + * sequence parameter set, including the dimensions of the + * associated video frames. + */ + + + ExpGolomb.prototype.readSPS = function readSPS() { + var frameCropLeftOffset = 0, + frameCropRightOffset = 0, + frameCropTopOffset = 0, + frameCropBottomOffset = 0, + profileIdc, + profileCompat, + levelIdc, + numRefFramesInPicOrderCntCycle, + picWidthInMbsMinus1, + picHeightInMapUnitsMinus1, + frameMbsOnlyFlag, + scalingListCount, + i, + readUByte = this.readUByte.bind(this), + readBits = this.readBits.bind(this), + readUEG = this.readUEG.bind(this), + readBoolean = this.readBoolean.bind(this), + skipBits = this.skipBits.bind(this), + skipEG = this.skipEG.bind(this), + skipUEG = this.skipUEG.bind(this), + skipScalingList = this.skipScalingList.bind(this); + + readUByte(); + profileIdc = readUByte(); // profile_idc + profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5) + skipBits(3); // reserved_zero_3bits u(3), + levelIdc = readUByte(); //level_idc u(8) + skipUEG(); // seq_parameter_set_id + // some profiles have more optional data we don't need + if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) { + var chromaFormatIdc = readUEG(); + if (chromaFormatIdc === 3) { + skipBits(1); // separate_colour_plane_flag + } + skipUEG(); // bit_depth_luma_minus8 + skipUEG(); // bit_depth_chroma_minus8 + skipBits(1); // qpprime_y_zero_transform_bypass_flag + if (readBoolean()) { + // seq_scaling_matrix_present_flag + scalingListCount = chromaFormatIdc !== 3 ? 8 : 12; + for (i = 0; i < scalingListCount; i++) { + if (readBoolean()) { + // seq_scaling_list_present_flag[ i ] + if (i < 6) { + skipScalingList(16); + } else { + skipScalingList(64); + } + } + } + } + } + skipUEG(); // log2_max_frame_num_minus4 + var picOrderCntType = readUEG(); + if (picOrderCntType === 0) { + readUEG(); //log2_max_pic_order_cnt_lsb_minus4 + } else if (picOrderCntType === 1) { + skipBits(1); // delta_pic_order_always_zero_flag + skipEG(); // offset_for_non_ref_pic + skipEG(); // offset_for_top_to_bottom_field + numRefFramesInPicOrderCntCycle = readUEG(); + for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) { + skipEG(); // offset_for_ref_frame[ i ] + } + } + skipUEG(); // max_num_ref_frames + skipBits(1); // gaps_in_frame_num_value_allowed_flag + picWidthInMbsMinus1 = readUEG(); + picHeightInMapUnitsMinus1 = readUEG(); + frameMbsOnlyFlag = readBits(1); + if (frameMbsOnlyFlag === 0) { + skipBits(1); // mb_adaptive_frame_field_flag + } + skipBits(1); // direct_8x8_inference_flag + if (readBoolean()) { + // frame_cropping_flag + frameCropLeftOffset = readUEG(); + frameCropRightOffset = readUEG(); + frameCropTopOffset = readUEG(); + frameCropBottomOffset = readUEG(); + } + var pixelRatio = [1, 1]; + if (readBoolean()) { + // vui_parameters_present_flag + if (readBoolean()) { + // aspect_ratio_info_present_flag + var aspectRatioIdc = readUByte(); + switch (aspectRatioIdc) { + case 1: + pixelRatio = [1, 1];break; + case 2: + pixelRatio = [12, 11];break; + case 3: + pixelRatio = [10, 11];break; + case 4: + pixelRatio = [16, 11];break; + case 5: + pixelRatio = [40, 33];break; + case 6: + pixelRatio = [24, 11];break; + case 7: + pixelRatio = [20, 11];break; + case 8: + pixelRatio = [32, 11];break; + case 9: + pixelRatio = [80, 33];break; + case 10: + pixelRatio = [18, 11];break; + case 11: + pixelRatio = [15, 11];break; + case 12: + pixelRatio = [64, 33];break; + case 13: + pixelRatio = [160, 99];break; + case 14: + pixelRatio = [4, 3];break; + case 15: + pixelRatio = [3, 2];break; + case 16: + pixelRatio = [2, 1];break; + case 255: + { + pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()]; + break; + } + } + } + } + return { + width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2), + height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset), + pixelRatio: pixelRatio + }; + }; + + ExpGolomb.prototype.readSliceType = function readSliceType() { + // skip NALu type + this.readUByte(); + // discard first_mb_in_slice + this.readUEG(); + // return slice_type + return this.readUEG(); + }; + + return ExpGolomb; +}(); + +/* harmony default export */ var exp_golomb = (exp_golomb_ExpGolomb); +// CONCATENATED MODULE: ./src/demux/sample-aes.js +function sample_aes__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * SAMPLE-AES decrypter +*/ + + + +var sample_aes_SampleAesDecrypter = function () { + function SampleAesDecrypter(observer, config, decryptdata, discardEPB) { + sample_aes__classCallCheck(this, SampleAesDecrypter); + + this.decryptdata = decryptdata; + this.discardEPB = discardEPB; + this.decrypter = new crypt_decrypter["a" /* default */](observer, config); + } + + SampleAesDecrypter.prototype.decryptBuffer = function decryptBuffer(encryptedData, callback) { + this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback); + }; + + // AAC - encrypt all full 16 bytes blocks starting from offset 16 + + + SampleAesDecrypter.prototype.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) { + var curUnit = samples[sampleIndex].unit; + var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16); + var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length); + + var localthis = this; + this.decryptBuffer(encryptedBuffer, function (decryptedData) { + decryptedData = new Uint8Array(decryptedData); + curUnit.set(decryptedData, 16); + + if (!sync) { + localthis.decryptAacSamples(samples, sampleIndex + 1, callback); + } + }); + }; + + SampleAesDecrypter.prototype.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) { + for (;; sampleIndex++) { + if (sampleIndex >= samples.length) { + callback(); + return; + } + + if (samples[sampleIndex].unit.length < 32) { + continue; + } + + var sync = this.decrypter.isSync(); + + this.decryptAacSample(samples, sampleIndex, callback, sync); + + if (!sync) { + return; + } + } + }; + + // AVC - encrypt one 16 bytes block out of ten, starting from offset 32 + + + SampleAesDecrypter.prototype.getAvcEncryptedData = function getAvcEncryptedData(decodedData) { + var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16; + var encryptedData = new Int8Array(encryptedDataLen); + var outputPos = 0; + for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) { + encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos); + } + return encryptedData; + }; + + SampleAesDecrypter.prototype.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) { + decryptedData = new Uint8Array(decryptedData); + var inputPos = 0; + for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) { + decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos); + } + return decodedData; + }; + + SampleAesDecrypter.prototype.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) { + var decodedData = this.discardEPB(curUnit.data); + var encryptedData = this.getAvcEncryptedData(decodedData); + var localthis = this; + + this.decryptBuffer(encryptedData.buffer, function (decryptedData) { + curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData); + + if (!sync) { + localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback); + } + }); + }; + + SampleAesDecrypter.prototype.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) { + for (;; sampleIndex++, unitIndex = 0) { + if (sampleIndex >= samples.length) { + callback(); + return; + } + + var curUnits = samples[sampleIndex].units; + for (;; unitIndex++) { + if (unitIndex >= curUnits.length) { + break; + } + + var curUnit = curUnits[unitIndex]; + if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) { + continue; + } + + var sync = this.decrypter.isSync(); + + this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync); + + if (!sync) { + return; + } + } + } + }; + + return SampleAesDecrypter; +}(); + +/* harmony default export */ var sample_aes = (sample_aes_SampleAesDecrypter); +// CONCATENATED MODULE: ./src/demux/tsdemuxer.js +function tsdemuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * highly optimized TS demuxer: + * parse PAT, PMT + * extract PES packet from audio and video PIDs + * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet + * trigger the remuxer upon parsing completion + * 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. + * it also controls the remuxing process : + * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state. +*/ + + + + + + +// import Hex from '../utils/hex'; + + + +// We are using fixed track IDs for driving the MP4 remuxer +// instead of following the TS PIDs. +// There is no reason not to do this and some browsers/SourceBuffer-demuxers +// may not like if there are TrackID "switches" +// See https://github.com/video-dev/hls.js/issues/1331 +// Here we are mapping our internal track types to constant MP4 track IDs +// With MSE currently one can only have one track of each, and we are muxing +// whatever video/audio rendition in them. +var RemuxerTrackIdConfig = { + video: 0, + audio: 1, + id3: 2, + text: 3 +}; + +var tsdemuxer_TSDemuxer = function () { + function TSDemuxer(observer, remuxer, config, typeSupported) { + tsdemuxer__classCallCheck(this, TSDemuxer); + + this.observer = observer; + this.config = config; + this.typeSupported = typeSupported; + this.remuxer = remuxer; + this.sampleAes = null; + } + + TSDemuxer.prototype.setDecryptData = function setDecryptData(decryptdata) { + if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') { + this.sampleAes = new sample_aes(this.observer, this.config, decryptdata, this.discardEPB); + } else { + this.sampleAes = null; + } + }; + + TSDemuxer.probe = function probe(data) { + var syncOffset = TSDemuxer._syncOffset(data); + if (syncOffset < 0) { + return false; + } else { + if (syncOffset) { + logger["b" /* logger */].warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?'); + } + return true; + } + }; + + TSDemuxer._syncOffset = function _syncOffset(data) { + // scan 1000 first bytes + var scanwindow = Math.min(1000, data.length - 3 * 188); + var i = 0; + while (i < scanwindow) { + // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47 + if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) { + return i; + } else { + i++; + } + } + return -1; + }; + + /** + * Creates a track model internal to demuxer used to drive remuxing input + * + * @param {string} type 'audio' | 'video' | 'id3' | 'text' + * @param {number} duration + * @return {object} TSDemuxer's internal track model + */ + + + TSDemuxer.createTrack = function createTrack(type, duration) { + return { + container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined, + type: type, + id: RemuxerTrackIdConfig[type], + pid: -1, + inputTimeScale: 90000, + sequenceNumber: 0, + samples: [], + len: 0, + dropped: type === 'video' ? 0 : undefined, + isAAC: type === 'audio' ? true : undefined, + duration: type === 'audio' ? duration : undefined + }; + }; + + /** + * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start) + * Resets all internal track instances of the demuxer. + * + * @override Implements generic demuxing/remuxing interface (see DemuxerInline) + * @param {object} initSegment + * @param {string} audioCodec + * @param {string} videoCodec + * @param {number} duration (in TS timescale = 90kHz) + */ + + + TSDemuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { + this.pmtParsed = false; + this._pmtId = -1; + + this._avcTrack = TSDemuxer.createTrack('video', duration); + this._audioTrack = TSDemuxer.createTrack('audio', duration); + this._id3Track = TSDemuxer.createTrack('id3', duration); + this._txtTrack = TSDemuxer.createTrack('text', duration); + + // flush any partial content + this.aacOverFlow = null; + this.aacLastPTS = null; + this.avcSample = null; + this.audioCodec = audioCodec; + this.videoCodec = videoCodec; + this._duration = duration; + }; + + /** + * + * @override + */ + + + TSDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {}; + + // feed incoming data to the front of the parsing pipeline + + + TSDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) { + var start, + len = data.length, + stt, + pid, + atf, + offset, + pes, + unknownPIDs = false; + this.contiguous = contiguous; + var pmtParsed = this.pmtParsed, + avcTrack = this._avcTrack, + audioTrack = this._audioTrack, + id3Track = this._id3Track, + avcId = avcTrack.pid, + audioId = audioTrack.pid, + id3Id = id3Track.pid, + pmtId = this._pmtId, + avcData = avcTrack.pesData, + audioData = audioTrack.pesData, + id3Data = id3Track.pesData, + parsePAT = this._parsePAT, + parsePMT = this._parsePMT, + parsePES = this._parsePES, + parseAVCPES = this._parseAVCPES.bind(this), + parseAACPES = this._parseAACPES.bind(this), + parseMPEGPES = this._parseMPEGPES.bind(this), + parseID3PES = this._parseID3PES.bind(this); + + var syncOffset = TSDemuxer._syncOffset(data); + + // don't parse last TS packet if incomplete + len -= (len + syncOffset) % 188; + + // loop through TS packets + for (start = syncOffset; start < len; start += 188) { + if (data[start] === 0x47) { + stt = !!(data[start + 1] & 0x40); + // pid is a 13-bit field starting at the last bit of TS[1] + pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2]; + atf = (data[start + 3] & 0x30) >> 4; + // if an adaption field is present, its length is specified by the fifth byte of the TS packet header. + if (atf > 1) { + offset = start + 5 + data[start + 4]; + // continue if there is only adaptation field + if (offset === start + 188) { + continue; + } + } else { + offset = start + 4; + } + switch (pid) { + case avcId: + if (stt) { + if (avcData && (pes = parsePES(avcData))) { + parseAVCPES(pes, false); + } + avcData = { data: [], size: 0 }; + } + if (avcData) { + avcData.data.push(data.subarray(offset, start + 188)); + avcData.size += start + 188 - offset; + } + break; + case audioId: + if (stt) { + if (audioData && (pes = parsePES(audioData))) { + if (audioTrack.isAAC) { + parseAACPES(pes); + } else { + parseMPEGPES(pes); + } + } + audioData = { data: [], size: 0 }; + } + if (audioData) { + audioData.data.push(data.subarray(offset, start + 188)); + audioData.size += start + 188 - offset; + } + break; + case id3Id: + if (stt) { + if (id3Data && (pes = parsePES(id3Data))) { + parseID3PES(pes); + } + id3Data = { data: [], size: 0 }; + } + if (id3Data) { + id3Data.data.push(data.subarray(offset, start + 188)); + id3Data.size += start + 188 - offset; + } + break; + case 0: + if (stt) { + offset += data[offset] + 1; + } + pmtId = this._pmtId = parsePAT(data, offset); + break; + case pmtId: + if (stt) { + offset += data[offset] + 1; + } + var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null); + + // only update track id if track PID found while parsing PMT + // this is to avoid resetting the PID to -1 in case + // track PID transiently disappears from the stream + // this could happen in case of transient missing audio samples for example + // NOTE this is only the PID of the track as found in TS, + // but we are not using this for MP4 track IDs. + avcId = parsedPIDs.avc; + if (avcId > 0) { + avcTrack.pid = avcId; + } + audioId = parsedPIDs.audio; + if (audioId > 0) { + audioTrack.pid = audioId; + audioTrack.isAAC = parsedPIDs.isAAC; + } + id3Id = parsedPIDs.id3; + if (id3Id > 0) { + id3Track.pid = id3Id; + } + if (unknownPIDs && !pmtParsed) { + logger["b" /* logger */].log('reparse from beginning'); + unknownPIDs = false; + // we set it to -188, the += 188 in the for loop will reset start to 0 + start = syncOffset - 188; + } + pmtParsed = this.pmtParsed = true; + break; + case 17: + case 0x1fff: + break; + default: + unknownPIDs = true; + break; + } + } else { + this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' }); + } + } + // try to parse last PES packets + if (avcData && (pes = parsePES(avcData))) { + parseAVCPES(pes, true); + avcTrack.pesData = null; + } else { + // either avcData null or PES truncated, keep it for next frag parsing + avcTrack.pesData = avcData; + } + + if (audioData && (pes = parsePES(audioData))) { + if (audioTrack.isAAC) { + parseAACPES(pes); + } else { + parseMPEGPES(pes); + } + audioTrack.pesData = null; + } else { + if (audioData && audioData.size) { + logger["b" /* logger */].log('last AAC PES packet truncated,might overlap between fragments'); + } + // either audioData null or PES truncated, keep it for next frag parsing + audioTrack.pesData = audioData; + } + + if (id3Data && (pes = parsePES(id3Data))) { + parseID3PES(pes); + id3Track.pesData = null; + } else { + // either id3Data null or PES truncated, keep it for next frag parsing + id3Track.pesData = id3Data; + } + + if (this.sampleAes == null) { + this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset); + } else { + this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset); + } + }; + + TSDemuxer.prototype.decryptAndRemux = function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) { + if (audioTrack.samples && audioTrack.isAAC) { + var localthis = this; + this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () { + localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset); + }); + } else { + this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset); + } + }; + + TSDemuxer.prototype.decryptAndRemuxAvc = function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) { + if (videoTrack.samples) { + var localthis = this; + this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () { + localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset); + }); + } else { + this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset); + } + }; + + TSDemuxer.prototype.destroy = function destroy() { + this._initPTS = this._initDTS = undefined; + this._duration = 0; + }; + + TSDemuxer.prototype._parsePAT = function _parsePAT(data, offset) { + // skip the PSI header and parse the first PMT entry + return (data[offset + 10] & 0x1F) << 8 | data[offset + 11]; + //logger.log('PMT PID:' + this._pmtId); + }; + + TSDemuxer.prototype._parsePMT = function _parsePMT(data, offset, mpegSupported, isSampleAes) { + var sectionLength, + tableEnd, + programInfoLength, + pid, + result = { audio: -1, avc: -1, id3: -1, isAAC: true }; + sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2]; + tableEnd = offset + 3 + sectionLength - 4; + // to determine where the table is, we have to figure out how + // long the program info descriptors are + programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; + // advance the offset to the first entry in the mapping table + offset += 12 + programInfoLength; + while (offset < tableEnd) { + pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2]; + switch (data[offset]) { + case 0xcf: + // SAMPLE-AES AAC + if (!isSampleAes) { + logger["b" /* logger */].log('unkown stream type:' + data[offset]); + break; + } + /* falls through */ + + // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio) + case 0x0f: + //logger.log('AAC PID:' + pid); + if (result.audio === -1) { + result.audio = pid; + } + break; + + // Packetized metadata (ID3) + case 0x15: + //logger.log('ID3 PID:' + pid); + if (result.id3 === -1) { + result.id3 = pid; + } + break; + + case 0xdb: + // SAMPLE-AES AVC + if (!isSampleAes) { + logger["b" /* logger */].log('unkown stream type:' + data[offset]); + break; + } + /* falls through */ + + // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video) + case 0x1b: + //logger.log('AVC PID:' + pid); + if (result.avc === -1) { + result.avc = pid; + } + break; + + // ISO/IEC 11172-3 (MPEG-1 audio) + // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio) + case 0x03: + case 0x04: + //logger.log('MPEG PID:' + pid); + if (!mpegSupported) { + logger["b" /* logger */].log('MPEG audio found, not supported in this browser for now'); + } else if (result.audio === -1) { + result.audio = pid; + result.isAAC = false; + } + break; + + case 0x24: + logger["b" /* logger */].warn('HEVC stream type found, not supported for now'); + break; + + default: + logger["b" /* logger */].log('unkown stream type:' + data[offset]); + break; + } + // move to the next table entry + // skip past the elementary stream descriptors, if present + offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5; + } + return result; + }; + + TSDemuxer.prototype._parsePES = function _parsePES(stream) { + var i = 0, + frag, + pesFlags, + pesPrefix, + pesLen, + pesHdrLen, + pesData, + pesPts, + pesDts, + payloadStartOffset, + data = stream.data; + // safety check + if (!stream || stream.size === 0) { + return null; + } + + // we might need up to 19 bytes to read PES header + // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes + // usually only one merge is needed (and this is rare ...) + while (data[0].length < 19 && data.length > 1) { + var newData = new Uint8Array(data[0].length + data[1].length); + newData.set(data[0]); + newData.set(data[1], data[0].length); + data[0] = newData; + data.splice(1, 1); + } + //retrieve PTS/DTS from first fragment + frag = data[0]; + pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2]; + if (pesPrefix === 1) { + pesLen = (frag[4] << 8) + frag[5]; + // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated + // minus 6 : PES header size + if (pesLen && pesLen > stream.size - 6) { + return null; + } + pesFlags = frag[7]; + if (pesFlags & 0xC0) { + /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html + as PTS / DTS is 33 bit we cannot use bitwise operator in JS, + as Bitwise operators treat their operands as a sequence of 32 bits */ + pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29 + (frag[10] & 0xFF) * 4194304 + // 1 << 22 + (frag[11] & 0xFE) * 16384 + // 1 << 14 + (frag[12] & 0xFF) * 128 + // 1 << 7 + (frag[13] & 0xFE) / 2; + // check if greater than 2^32 -1 + if (pesPts > 4294967295) { + // decrement 2^33 + pesPts -= 8589934592; + } + if (pesFlags & 0x40) { + pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29 + (frag[15] & 0xFF) * 4194304 + // 1 << 22 + (frag[16] & 0xFE) * 16384 + // 1 << 14 + (frag[17] & 0xFF) * 128 + // 1 << 7 + (frag[18] & 0xFE) / 2; + // check if greater than 2^32 -1 + if (pesDts > 4294967295) { + // decrement 2^33 + pesDts -= 8589934592; + } + if (pesPts - pesDts > 60 * 90000) { + logger["b" /* logger */].warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them'); + pesPts = pesDts; + } + } else { + pesDts = pesPts; + } + } + pesHdrLen = frag[8]; + // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension + payloadStartOffset = pesHdrLen + 9; + + stream.size -= payloadStartOffset; + //reassemble PES packet + pesData = new Uint8Array(stream.size); + for (var j = 0, dataLen = data.length; j < dataLen; j++) { + frag = data[j]; + var len = frag.byteLength; + if (payloadStartOffset) { + if (payloadStartOffset > len) { + // trim full frag if PES header bigger than frag + payloadStartOffset -= len; + continue; + } else { + // trim partial frag if PES header smaller than frag + frag = frag.subarray(payloadStartOffset); + len -= payloadStartOffset; + payloadStartOffset = 0; + } + } + pesData.set(frag, i); + i += len; + } + if (pesLen) { + // payload size : remove PES header + PES extension + pesLen -= pesHdrLen + 3; + } + return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen }; + } else { + return null; + } + }; + + TSDemuxer.prototype.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) { + if (avcSample.units.length && avcSample.frame) { + var samples = avcTrack.samples; + var nbSamples = samples.length; + // only push AVC sample if starting with a keyframe is not mandatory OR + // if keyframe already found in this fragment OR + // keyframe found in last fragment (track.sps) AND + // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous + if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) { + avcSample.id = nbSamples; + samples.push(avcSample); + } else { + // dropped samples, track it + avcTrack.dropped++; + } + } + if (avcSample.debug.length) { + logger["b" /* logger */].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug); + } + }; + + TSDemuxer.prototype._parseAVCPES = function _parseAVCPES(pes, last) { + var _this = this; + + //logger.log('parse new PES'); + var track = this._avcTrack, + units = this._parseAVCNALu(pes.data), + debug = false, + expGolombDecoder, + avcSample = this.avcSample, + push, + spsfound = false, + i, + pushAccesUnit = this.pushAccesUnit.bind(this), + createAVCSample = function createAVCSample(key, pts, dts, debug) { + return { key: key, pts: pts, dts: dts, units: [], debug: debug }; + }; + //free pes.data to save up some memory + pes.data = null; + + // if new NAL units found and last sample still there, let's push ... + // this helps parsing streams with missing AUD (only do this if AUD never found) + if (avcSample && units.length && !track.audFound) { + pushAccesUnit(avcSample, track); + avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, ''); + } + + units.forEach(function (unit) { + switch (unit.type) { + //NDR + case 1: + push = true; + if (!avcSample) { + avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, ''); + } + if (debug) { + avcSample.debug += 'NDR '; + } + avcSample.frame = true; + var data = unit.data; + // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...) + if (spsfound && data.length > 4) { + // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR + var sliceType = new exp_golomb(data).readSliceType(); + // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice + // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples. + // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice. + // I slice: A slice that is not an SI slice that is decoded using intra prediction only. + //if (sliceType === 2 || sliceType === 7) { + if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) { + avcSample.key = true; + } + } + break; + //IDR + case 5: + push = true; + // handle PES not starting with AUD + if (!avcSample) { + avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, ''); + } + if (debug) { + avcSample.debug += 'IDR '; + } + avcSample.key = true; + avcSample.frame = true; + break; + //SEI + case 6: + push = true; + if (debug && avcSample) { + avcSample.debug += 'SEI '; + } + expGolombDecoder = new exp_golomb(_this.discardEPB(unit.data)); + + // skip frameType + expGolombDecoder.readUByte(); + + var payloadType = 0; + var payloadSize = 0; + var endOfCaptions = false; + var b = 0; + + while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) { + payloadType = 0; + do { + b = expGolombDecoder.readUByte(); + payloadType += b; + } while (b === 0xFF); + + // Parse payload size. + payloadSize = 0; + do { + b = expGolombDecoder.readUByte(); + payloadSize += b; + } while (b === 0xFF); + + // TODO: there can be more than one payload in an SEI packet... + // TODO: need to read type and size in a while loop to get them all + if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) { + + endOfCaptions = true; + + var countryCode = expGolombDecoder.readUByte(); + + if (countryCode === 181) { + var providerCode = expGolombDecoder.readUShort(); + + if (providerCode === 49) { + var userStructure = expGolombDecoder.readUInt(); + + if (userStructure === 0x47413934) { + var userDataType = expGolombDecoder.readUByte(); + + // Raw CEA-608 bytes wrapped in CEA-708 packet + if (userDataType === 3) { + var firstByte = expGolombDecoder.readUByte(); + var secondByte = expGolombDecoder.readUByte(); + + var totalCCs = 31 & firstByte; + var byteArray = [firstByte, secondByte]; + + for (i = 0; i < totalCCs; i++) { + // 3 bytes per CC + byteArray.push(expGolombDecoder.readUByte()); + byteArray.push(expGolombDecoder.readUByte()); + byteArray.push(expGolombDecoder.readUByte()); + } + + _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray }); + } + } + } + } + } else if (payloadSize < expGolombDecoder.bytesAvailable) { + for (i = 0; i < payloadSize; i++) { + expGolombDecoder.readUByte(); + } + } + } + break; + //SPS + case 7: + push = true; + spsfound = true; + if (debug && avcSample) { + avcSample.debug += 'SPS '; + } + if (!track.sps) { + expGolombDecoder = new exp_golomb(unit.data); + var config = expGolombDecoder.readSPS(); + track.width = config.width; + track.height = config.height; + track.pixelRatio = config.pixelRatio; + track.sps = [unit.data]; + track.duration = _this._duration; + var codecarray = unit.data.subarray(1, 4); + var codecstring = 'avc1.'; + for (i = 0; i < 3; i++) { + var h = codecarray[i].toString(16); + if (h.length < 2) { + h = '0' + h; + } + codecstring += h; + } + track.codec = codecstring; + } + break; + //PPS + case 8: + push = true; + if (debug && avcSample) { + avcSample.debug += 'PPS '; + } + if (!track.pps) { + track.pps = [unit.data]; + } + break; + // AUD + case 9: + push = false; + track.audFound = true; + if (avcSample) { + pushAccesUnit(avcSample, track); + } + avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : ''); + break; + // Filler Data + case 12: + push = false; + break; + default: + push = false; + if (avcSample) { + avcSample.debug += 'unknown NAL ' + unit.type + ' '; + } + break; + } + if (avcSample && push) { + var _units = avcSample.units; + _units.push(unit); + } + }); + // if last PES packet, push samples + if (last && avcSample) { + pushAccesUnit(avcSample, track); + this.avcSample = null; + } + }; + + TSDemuxer.prototype._insertSampleInOrder = function _insertSampleInOrder(arr, data) { + var len = arr.length; + if (len > 0) { + if (data.pts >= arr[len - 1].pts) { + arr.push(data); + } else { + for (var pos = len - 1; pos >= 0; pos--) { + if (data.pts < arr[pos].pts) { + arr.splice(pos, 0, data); + break; + } + } + } + } else { + arr.push(data); + } + }; + + TSDemuxer.prototype._getLastNalUnit = function _getLastNalUnit() { + var avcSample = this.avcSample, + lastUnit = void 0; + // try to fallback to previous sample if current one is empty + if (!avcSample || avcSample.units.length === 0) { + var track = this._avcTrack, + samples = track.samples; + avcSample = samples[samples.length - 1]; + } + if (avcSample) { + var units = avcSample.units; + lastUnit = units[units.length - 1]; + } + return lastUnit; + }; + + TSDemuxer.prototype._parseAVCNALu = function _parseAVCNALu(array) { + var i = 0, + len = array.byteLength, + value, + overflow, + track = this._avcTrack, + state = track.naluState || 0, + lastState = state; + var units = [], + unit, + unitType, + lastUnitStart = -1, + lastUnitType; + //logger.log('PES:' + Hex.hexDump(array)); + + if (state === -1) { + // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet + lastUnitStart = 0; + // NALu type is value read from offset 0 + lastUnitType = array[0] & 0x1f; + state = 0; + i = 1; + } + + while (i < len) { + value = array[i++]; + // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case + if (!state) { + state = value ? 0 : 1; + continue; + } + if (state === 1) { + state = value ? 0 : 2; + continue; + } + // here we have state either equal to 2 or 3 + if (!value) { + state = 3; + } else if (value === 1) { + if (lastUnitStart >= 0) { + unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType }; + //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength); + units.push(unit); + } else { + // lastUnitStart is undefined => this is the first start code found in this PES packet + // first check if start code delimiter is overlapping between 2 PES packets, + // ie it started in last packet (lastState not zero) + // and ended at the beginning of this PES packet (i <= 4 - lastState) + var lastUnit = this._getLastNalUnit(); + if (lastUnit) { + if (lastState && i <= 4 - lastState) { + // start delimiter overlapping between PES packets + // strip start delimiter bytes from the end of last NAL unit + // check if lastUnit had a state different from zero + if (lastUnit.state) { + // strip last bytes + lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState); + } + } + // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit. + overflow = i - state - 1; + if (overflow > 0) { + //logger.log('first NALU found with overflow:' + overflow); + var tmp = new Uint8Array(lastUnit.data.byteLength + overflow); + tmp.set(lastUnit.data, 0); + tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength); + lastUnit.data = tmp; + } + } + } + // check if we can read unit type + if (i < len) { + unitType = array[i] & 0x1f; + //logger.log('find NALU @ offset:' + i + ',type:' + unitType); + lastUnitStart = i; + lastUnitType = unitType; + state = 0; + } else { + // not enough byte to read unit type. let's read it on next PES parsing + state = -1; + } + } else { + state = 0; + } + } + if (lastUnitStart >= 0 && state >= 0) { + unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state }; + units.push(unit); + //logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state); + } + // no NALu found + if (units.length === 0) { + // append pes.data to previous NAL unit + var _lastUnit = this._getLastNalUnit(); + if (_lastUnit) { + var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength); + _tmp.set(_lastUnit.data, 0); + _tmp.set(array, _lastUnit.data.byteLength); + _lastUnit.data = _tmp; + } + } + track.naluState = state; + return units; + }; + + /** + * remove Emulation Prevention bytes from a RBSP + */ + + + TSDemuxer.prototype.discardEPB = function discardEPB(data) { + var length = data.byteLength, + EPBPositions = [], + i = 1, + newLength, + newData; + + // Find all `Emulation Prevention Bytes` + while (i < length - 2) { + if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) { + EPBPositions.push(i + 2); + i += 2; + } else { + i++; + } + } + + // If no Emulation Prevention Bytes were found just return the original + // array + if (EPBPositions.length === 0) { + return data; + } + + // Create a new array to hold the NAL unit data + newLength = length - EPBPositions.length; + newData = new Uint8Array(newLength); + var sourceIndex = 0; + + for (i = 0; i < newLength; sourceIndex++, i++) { + if (sourceIndex === EPBPositions[0]) { + // Skip this byte + sourceIndex++; + // Remove this position index + EPBPositions.shift(); + } + newData[i] = data[sourceIndex]; + } + return newData; + }; + + TSDemuxer.prototype._parseAACPES = function _parseAACPES(pes) { + var track = this._audioTrack, + data = pes.data, + pts = pes.pts, + startOffset = 0, + aacOverFlow = this.aacOverFlow, + aacLastPTS = this.aacLastPTS, + frameDuration, + frameIndex, + offset, + stamp, + len; + if (aacOverFlow) { + var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength); + tmp.set(aacOverFlow, 0); + tmp.set(data, aacOverFlow.byteLength); + //logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`); + data = tmp; + } + // look for ADTS header (0xFFFx) + for (offset = startOffset, len = data.length; offset < len - 1; offset++) { + if (isHeader(data, offset)) { + break; + } + } + // if ADTS header does not start straight from the beginning of the PES payload, raise an error + if (offset) { + var reason, fatal; + if (offset < len - 1) { + reason = 'AAC PES did not start with ADTS header,offset:' + offset; + fatal = false; + } else { + reason = 'no ADTS header found in AAC PES'; + fatal = true; + } + logger["b" /* logger */].warn('parsing error:' + reason); + this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: fatal, reason: reason }); + if (fatal) { + return; + } + } + + initTrackConfig(track, this.observer, data, offset, this.audioCodec); + frameIndex = 0; + frameDuration = getFrameDuration(track.samplerate); + + // if last AAC frame is overflowing, we should ensure timestamps are contiguous: + // first sample PTS should be equal to last sample PTS + frameDuration + if (aacOverFlow && aacLastPTS) { + var newPTS = aacLastPTS + frameDuration; + if (Math.abs(newPTS - pts) > 1) { + logger["b" /* logger */].log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90)); + pts = newPTS; + } + } + + //scan for aac samples + while (offset < len) { + if (isHeader(data, offset) && offset + 5 < len) { + var frame = appendFrame(track, data, offset, pts, frameIndex); + if (frame) { + //logger.log(`${Math.round(frame.sample.pts)} : AAC`); + offset += frame.length; + stamp = frame.sample.pts; + frameIndex++; + } else { + //logger.log('Unable to parse AAC frame'); + break; + } + } else { + //nothing found, keep looking + offset++; + } + } + + if (offset < len) { + aacOverFlow = data.subarray(offset, len); + //logger.log(`AAC: overflow detected:${len-offset}`); + } else { + aacOverFlow = null; + } + this.aacOverFlow = aacOverFlow; + this.aacLastPTS = stamp; + }; + + TSDemuxer.prototype._parseMPEGPES = function _parseMPEGPES(pes) { + var data = pes.data; + var length = data.length; + var frameIndex = 0; + var offset = 0; + var pts = pes.pts; + + while (offset < length) { + if (mpegaudio.isHeader(data, offset)) { + var frame = mpegaudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex); + if (frame) { + offset += frame.length; + frameIndex++; + } else { + //logger.log('Unable to parse Mpeg audio frame'); + break; + } + } else { + //nothing found, keep looking + offset++; + } + } + }; + + TSDemuxer.prototype._parseID3PES = function _parseID3PES(pes) { + this._id3Track.samples.push(pes); + }; + + return TSDemuxer; +}(); + +/* harmony default export */ var tsdemuxer = (tsdemuxer_TSDemuxer); +// CONCATENATED MODULE: ./src/demux/mp3demuxer.js +function mp3demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * MP3 demuxer + */ + + + + +var mp3demuxer_MP3Demuxer = function () { + function MP3Demuxer(observer, remuxer, config) { + mp3demuxer__classCallCheck(this, MP3Demuxer); + + this.observer = observer; + this.config = config; + this.remuxer = remuxer; + } + + MP3Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) { + this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 }; + }; + + MP3Demuxer.prototype.resetTimeStamp = function resetTimeStamp() {}; + + MP3Demuxer.probe = function probe(data) { + // check if data contains ID3 timestamp and MPEG sync word + var offset, length; + var id3Data = id3["a" /* default */].getID3Data(data, 0); + if (id3Data && id3["a" /* default */].getTimeStamp(id3Data) !== undefined) { + // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1 + // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III) + // More info http://www.mp3-tech.org/programmer/frame_header.html + for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) { + if (mpegaudio.probe(data, offset)) { + logger["b" /* logger */].log('MPEG Audio sync word found !'); + return true; + } + } + } + return false; + }; + + // feed incoming data to the front of the parsing pipeline + + + MP3Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) { + var id3Data = id3["a" /* default */].getID3Data(data, 0); + var pts = 90 * id3["a" /* default */].getTimeStamp(id3Data); + var offset = id3Data.length; + var length = data.length; + var frameIndex = 0, + stamp = 0; + var track = this._audioTrack; + + var id3Samples = [{ pts: pts, dts: pts, data: id3Data }]; + + while (offset < length) { + if (mpegaudio.isHeader(data, offset)) { + var frame = mpegaudio.appendFrame(track, data, offset, pts, frameIndex); + if (frame) { + offset += frame.length; + stamp = frame.sample.pts; + frameIndex++; + } else { + //logger.log('Unable to parse Mpeg audio frame'); + break; + } + } else if (id3["a" /* default */].isHeader(data, offset)) { + id3Data = id3["a" /* default */].getID3Data(data, offset); + id3Samples.push({ pts: stamp, dts: stamp, data: id3Data }); + offset += id3Data.length; + } else { + //nothing found, keep looking + offset++; + } + } + + this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset); + }; + + MP3Demuxer.prototype.destroy = function destroy() {}; + + return MP3Demuxer; +}(); + +/* harmony default export */ var mp3demuxer = (mp3demuxer_MP3Demuxer); +// CONCATENATED MODULE: ./src/helper/aac.js +function aac__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * AAC helper + */ + +var AAC = function () { + function AAC() { + aac__classCallCheck(this, AAC); + } + + AAC.getSilentFrame = function getSilentFrame(codec, channelCount) { + switch (codec) { + case 'mp4a.40.2': + if (channelCount === 1) { + return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]); + } else if (channelCount === 2) { + return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]); + } else if (channelCount === 3) { + return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]); + } else if (channelCount === 4) { + return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]); + } else if (channelCount === 5) { + return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]); + } else if (channelCount === 6) { + 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]); + } + break; + // handle HE-AAC below (mp4a.40.5 / mp4a.40.29) + default: + if (channelCount === 1) { + // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac + return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); + } else if (channelCount === 2) { + // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac + return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); + } else if (channelCount === 3) { + // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac + return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]); + } + break; + } + return null; + }; + + return AAC; +}(); + +/* harmony default export */ var aac = (AAC); +// CONCATENATED MODULE: ./src/remux/mp4-generator.js +function mp4_generator__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generate MP4 Box +*/ + +//import Hex from '../utils/hex'; + +var mp4_generator_UINT32_MAX = Math.pow(2, 32) - 1; + +var MP4 = function () { + function MP4() { + mp4_generator__classCallCheck(this, MP4); + } + + MP4.init = function init() { + MP4.types = { + avc1: [], // codingname + avcC: [], + btrt: [], + dinf: [], + dref: [], + esds: [], + ftyp: [], + hdlr: [], + mdat: [], + mdhd: [], + mdia: [], + mfhd: [], + minf: [], + moof: [], + moov: [], + mp4a: [], + '.mp3': [], + mvex: [], + mvhd: [], + pasp: [], + sdtp: [], + stbl: [], + stco: [], + stsc: [], + stsd: [], + stsz: [], + stts: [], + tfdt: [], + tfhd: [], + traf: [], + trak: [], + trun: [], + trex: [], + tkhd: [], + vmhd: [], + smhd: [] + }; + + var i; + for (i in MP4.types) { + if (MP4.types.hasOwnProperty(i)) { + MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)]; + } + } + + var videoHdlr = new Uint8Array([0x00, // version 0 + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, 0x00, 0x00, // pre_defined + 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide' + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, 0x00, // reserved + 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler' + ]); + + var audioHdlr = new Uint8Array([0x00, // version 0 + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, 0x00, 0x00, // pre_defined + 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun' + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, 0x00, // reserved + 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler' + ]); + + MP4.HDLR_TYPES = { + 'video': videoHdlr, + 'audio': audioHdlr + }; + + var dref = new Uint8Array([0x00, // version 0 + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, 0x00, 0x01, // entry_count + 0x00, 0x00, 0x00, 0x0c, // entry_size + 0x75, 0x72, 0x6c, 0x20, // 'url' type + 0x00, // version 0 + 0x00, 0x00, 0x01 // entry_flags + ]); + + var stco = new Uint8Array([0x00, // version + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, 0x00, 0x00 // entry_count + ]); + + MP4.STTS = MP4.STSC = MP4.STCO = stco; + + MP4.STSZ = new Uint8Array([0x00, // version + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, 0x00, 0x00, // sample_size + 0x00, 0x00, 0x00, 0x00]); + MP4.VMHD = new Uint8Array([0x00, // version + 0x00, 0x00, 0x01, // flags + 0x00, 0x00, // graphicsmode + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor + ]); + MP4.SMHD = new Uint8Array([0x00, // version + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, // balance + 0x00, 0x00 // reserved + ]); + + MP4.STSD = new Uint8Array([0x00, // version 0 + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, 0x00, 0x01]); // entry_count + + var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom + var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1 + var minorVersion = new Uint8Array([0, 0, 0, 1]); + + MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand); + MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref)); + }; + + MP4.box = function box(type) { + var payload = Array.prototype.slice.call(arguments, 1), + size = 8, + i = payload.length, + len = i, + result; + // calculate the total size we need to allocate + while (i--) { + size += payload[i].byteLength; + } + result = new Uint8Array(size); + result[0] = size >> 24 & 0xff; + result[1] = size >> 16 & 0xff; + result[2] = size >> 8 & 0xff; + result[3] = size & 0xff; + result.set(type, 4); + // copy the payload into the result + for (i = 0, size = 8; i < len; i++) { + // copy payload[i] array @ offset size + result.set(payload[i], size); + size += payload[i].byteLength; + } + return result; + }; + + MP4.hdlr = function hdlr(type) { + return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]); + }; + + MP4.mdat = function mdat(data) { + return MP4.box(MP4.types.mdat, data); + }; + + MP4.mdhd = function mdhd(timescale, duration) { + duration *= timescale; + var upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1)); + var lowerWordDuration = Math.floor(duration % (mp4_generator_UINT32_MAX + 1)); + return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1 + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time + timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale + upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x55, 0xc4, // 'und' language (undetermined) + 0x00, 0x00])); + }; + + MP4.mdia = function mdia(track) { + return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track)); + }; + + MP4.mfhd = function mfhd(sequenceNumber) { + return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags + sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF]) // sequence_number + ); + }; + + MP4.minf = function minf(track) { + if (track.type === 'audio') { + return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track)); + } else { + return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track)); + } + }; + + MP4.moof = function moof(sn, baseMediaDecodeTime, track) { + return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime)); + }; + /** + * @param tracks... (optional) {array} the tracks associated with this movie + */ + + + MP4.moov = function moov(tracks) { + var i = tracks.length, + boxes = []; + + while (i--) { + boxes[i] = MP4.trak(tracks[i]); + } + + return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks))); + }; + + MP4.mvex = function mvex(tracks) { + var i = tracks.length, + boxes = []; + + while (i--) { + boxes[i] = MP4.trex(tracks[i]); + } + return MP4.box.apply(null, [MP4.types.mvex].concat(boxes)); + }; + + MP4.mvhd = function mvhd(timescale, duration) { + duration *= timescale; + var upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1)); + var lowerWordDuration = Math.floor(duration % (mp4_generator_UINT32_MAX + 1)); + var bytes = new Uint8Array([0x01, // version 1 + 0x00, 0x00, 0x00, // flags + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time + timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale + upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x01, 0x00, 0x00, // 1.0 rate + 0x01, 0x00, // 1.0 volume + 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined + 0xff, 0xff, 0xff, 0xff // next_track_ID + ]); + return MP4.box(MP4.types.mvhd, bytes); + }; + + MP4.sdtp = function sdtp(track) { + var samples = track.samples || [], + bytes = new Uint8Array(4 + samples.length), + flags, + i; + // leave the full box header (4 bytes) all zero + // write the sample table + for (i = 0; i < samples.length; i++) { + flags = samples[i].flags; + bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy; + } + + return MP4.box(MP4.types.sdtp, bytes); + }; + + MP4.stbl = function stbl(track) { + 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)); + }; + + MP4.avc1 = function avc1(track) { + var sps = [], + pps = [], + i, + data, + len; + // assemble the SPSs + + for (i = 0; i < track.sps.length; i++) { + data = track.sps[i]; + len = data.byteLength; + sps.push(len >>> 8 & 0xFF); + sps.push(len & 0xFF); + sps = sps.concat(Array.prototype.slice.call(data)); // SPS + } + + // assemble the PPSs + for (i = 0; i < track.pps.length; i++) { + data = track.pps[i]; + len = data.byteLength; + pps.push(len >>> 8 & 0xFF); + pps.push(len & 0xFF); + pps = pps.concat(Array.prototype.slice.call(data)); + } + + var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version + sps[3], // profile + sps[4], // profile compat + sps[5], // level + 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes + 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets + ].concat(sps).concat([track.pps.length // numOfPictureParameterSets + ]).concat(pps))), + // "PPS" + width = track.width, + height = track.height, + hSpacing = track.pixelRatio[0], + vSpacing = track.pixelRatio[1]; + //console.log('avcc:' + Hex.hexDump(avcc)); + return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, // reserved + 0x00, 0x01, // data_reference_index + 0x00, 0x00, // pre_defined + 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined + width >> 8 & 0xFF, width & 0xff, // width + height >> 8 & 0xFF, height & 0xff, // height + 0x00, 0x48, 0x00, 0x00, // horizresolution + 0x00, 0x48, 0x00, 0x00, // vertresolution + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x01, // frame_count + 0x12, 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js + 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 + 0x00, 0x18, // depth = 24 + 0x11, 0x11]), // pre_defined = -1 + avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB + 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate + 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate + MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing + hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing + vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF]))); + }; + + MP4.esds = function esds(track) { + var configlen = track.config.length; + return new Uint8Array([0x00, // version 0 + 0x00, 0x00, 0x00, // flags + + 0x03, // descriptor_type + 0x17 + configlen, // length + 0x00, 0x01, //es_id + 0x00, // stream_priority + + 0x04, // descriptor_type + 0x0f + configlen, // length + 0x40, //codec : mpeg4_audio + 0x15, // stream_type + 0x00, 0x00, 0x00, // buffer_size + 0x00, 0x00, 0x00, 0x00, // maxBitrate + 0x00, 0x00, 0x00, 0x00, // avgBitrate + + 0x05 // descriptor_type + ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor + }; + + MP4.mp4a = function mp4a(track) { + var samplerate = track.samplerate; + return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, // reserved + 0x00, 0x01, // data_reference_index + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, track.channelCount, // channelcount + 0x00, 0x10, // sampleSize:16bits + 0x00, 0x00, 0x00, 0x00, // reserved2 + samplerate >> 8 & 0xFF, samplerate & 0xff, // + 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track))); + }; + + MP4.mp3 = function mp3(track) { + var samplerate = track.samplerate; + return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved + 0x00, 0x00, 0x00, // reserved + 0x00, 0x01, // data_reference_index + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, track.channelCount, // channelcount + 0x00, 0x10, // sampleSize:16bits + 0x00, 0x00, 0x00, 0x00, // reserved2 + samplerate >> 8 & 0xFF, samplerate & 0xff, // + 0x00, 0x00])); + }; + + MP4.stsd = function stsd(track) { + if (track.type === 'audio') { + if (!track.isAAC && track.codec === 'mp3') { + return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track)); + } + return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track)); + } else { + return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track)); + } + }; + + MP4.tkhd = function tkhd(track) { + var id = track.id, + duration = track.duration * track.timescale, + width = track.width, + height = track.height, + upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1)), + lowerWordDuration = Math.floor(duration % (mp4_generator_UINT32_MAX + 1)); + return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1 + 0x00, 0x00, 0x07, // flags + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time + id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID + 0x00, 0x00, 0x00, 0x00, // reserved + upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x00, // layer + 0x00, 0x00, // alternate_group + 0x00, 0x00, // non-audio track volume + 0x00, 0x00, // reserved + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix + width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width + height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height + ])); + }; + + MP4.traf = function traf(track, baseMediaDecodeTime) { + var sampleDependencyTable = MP4.sdtp(track), + id = track.id, + upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (mp4_generator_UINT32_MAX + 1)), + lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (mp4_generator_UINT32_MAX + 1)); + return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0 + 0x00, 0x00, 0x00, // flags + id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF]) // track_ID + ), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1 + 0x00, 0x00, 0x00, // flags + upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0XFF, upperWordBaseMediaDecodeTime >> 8 & 0XFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0XFF, lowerWordBaseMediaDecodeTime >> 8 & 0XFF, lowerWordBaseMediaDecodeTime & 0xFF])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd + 20 + // tfdt + 8 + // traf header + 16 + // mfhd + 8 + // moof header + 8), // mdat header + sampleDependencyTable); + }; + + /** + * Generate a track box. + * @param track {object} a track definition + * @return {Uint8Array} the track box + */ + + + MP4.trak = function trak(track) { + track.duration = track.duration || 0xffffffff; + return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track)); + }; + + MP4.trex = function trex(track) { + var id = track.id; + return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0 + 0x00, 0x00, 0x00, // flags + id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID + 0x00, 0x00, 0x00, 0x01, // default_sample_description_index + 0x00, 0x00, 0x00, 0x00, // default_sample_duration + 0x00, 0x00, 0x00, 0x00, // default_sample_size + 0x00, 0x01, 0x00, 0x01 // default_sample_flags + ])); + }; + + MP4.trun = function trun(track, offset) { + var samples = track.samples || [], + len = samples.length, + arraylen = 12 + 16 * len, + array = new Uint8Array(arraylen), + i, + sample, + duration, + size, + flags, + cts; + offset += 8 + arraylen; + array.set([0x00, // version 0 + 0x00, 0x0f, 0x01, // flags + len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count + offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset + ], 0); + for (i = 0; i < len; i++) { + sample = samples[i]; + duration = sample.duration; + size = sample.size; + flags = sample.flags; + cts = sample.cts; + array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration + size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size + 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 + cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset + ], 12 + 16 * i); + } + return MP4.box(MP4.types.trun, array); + }; + + MP4.initSegment = function initSegment(tracks) { + if (!MP4.types) { + MP4.init(); + } + var movie = MP4.moov(tracks), + result; + result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength); + result.set(MP4.FTYP); + result.set(movie, MP4.FTYP.byteLength); + return result; + }; + + return MP4; +}(); + +/* harmony default export */ var mp4_generator = (MP4); +// CONCATENATED MODULE: ./src/remux/mp4-remuxer.js +function mp4_remuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** +* fMP4 remuxer +*/ + + + + + + + +// 10 seconds +var MAX_SILENT_FRAME_DURATION = 10 * 1000; + +var mp4_remuxer_MP4Remuxer = function () { + function MP4Remuxer(observer, config, typeSupported, vendor) { + mp4_remuxer__classCallCheck(this, MP4Remuxer); + + this.observer = observer; + this.config = config; + this.typeSupported = typeSupported; + var userAgent = navigator.userAgent; + this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS'); + this.ISGenerated = false; + } + + MP4Remuxer.prototype.destroy = function destroy() {}; + + MP4Remuxer.prototype.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) { + this._initPTS = this._initDTS = defaultTimeStamp; + }; + + MP4Remuxer.prototype.resetInitSegment = function resetInitSegment() { + this.ISGenerated = false; + }; + + MP4Remuxer.prototype.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) { + // generate Init Segment if needed + if (!this.ISGenerated) { + this.generateIS(audioTrack, videoTrack, timeOffset); + } + + if (this.ISGenerated) { + var nbAudioSamples = audioTrack.samples.length; + var nbVideoSamples = videoTrack.samples.length; + var audioTimeOffset = timeOffset; + var videoTimeOffset = timeOffset; + if (nbAudioSamples && nbVideoSamples) { + // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS) + // if first audio DTS is not aligned with first video DTS then we need to take that into account + // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small + // drift between audio and video streams + var audiovideoDeltaDts = (audioTrack.samples[0].dts - videoTrack.samples[0].dts) / videoTrack.inputTimeScale; + audioTimeOffset += Math.max(0, audiovideoDeltaDts); + videoTimeOffset += Math.max(0, -audiovideoDeltaDts); + } + // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is + // calculated in remuxAudio. + //logger.log('nb AAC samples:' + audioTrack.samples.length); + if (nbAudioSamples) { + // if initSegment was generated without video samples, regenerate it again + if (!audioTrack.timescale) { + logger["b" /* logger */].warn('regenerate InitSegment as audio detected'); + this.generateIS(audioTrack, videoTrack, timeOffset); + } + var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset); + //logger.log('nb AVC samples:' + videoTrack.samples.length); + if (nbVideoSamples) { + var audioTrackLength = void 0; + if (audioData) { + audioTrackLength = audioData.endPTS - audioData.startPTS; + } + // if initSegment was generated without video samples, regenerate it again + if (!videoTrack.timescale) { + logger["b" /* logger */].warn('regenerate InitSegment as video detected'); + this.generateIS(audioTrack, videoTrack, timeOffset); + } + this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset); + } + } else { + var videoData = void 0; + //logger.log('nb AVC samples:' + videoTrack.samples.length); + if (nbVideoSamples) { + videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, accurateTimeOffset); + } + if (videoData && audioTrack.codec) { + this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData); + } + } + } + //logger.log('nb ID3 samples:' + audioTrack.samples.length); + if (id3Track.samples.length) { + this.remuxID3(id3Track, timeOffset); + } + //logger.log('nb ID3 samples:' + audioTrack.samples.length); + if (textTrack.samples.length) { + this.remuxText(textTrack, timeOffset); + } + //notify end of parsing + this.observer.trigger(events["a" /* default */].FRAG_PARSED); + }; + + MP4Remuxer.prototype.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) { + var observer = this.observer, + audioSamples = audioTrack.samples, + videoSamples = videoTrack.samples, + typeSupported = this.typeSupported, + container = 'audio/mp4', + tracks = {}, + data = { tracks: tracks }, + computePTSDTS = this._initPTS === undefined, + initPTS, + initDTS; + + if (computePTSDTS) { + initPTS = initDTS = Infinity; + } + if (audioTrack.config && audioSamples.length) { + // let's use audio sampling rate as MP4 time scale. + // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC) + // using audio sampling rate here helps having an integer MP4 frame duration + // this avoids potential rounding issue and AV sync issue + audioTrack.timescale = audioTrack.samplerate; + logger["b" /* logger */].log('audio sampling rate : ' + audioTrack.samplerate); + if (!audioTrack.isAAC) { + if (typeSupported.mpeg) { + // Chrome and Safari + container = 'audio/mpeg'; + audioTrack.codec = ''; + } else if (typeSupported.mp3) { + // Firefox + audioTrack.codec = 'mp3'; + } + } + tracks.audio = { + container: container, + codec: audioTrack.codec, + initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : mp4_generator.initSegment([audioTrack]), + metadata: { + channelCount: audioTrack.channelCount + } + }; + if (computePTSDTS) { + // remember first PTS of this demuxing context. for audio, PTS = DTS + initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset; + } + } + + if (videoTrack.sps && videoTrack.pps && videoSamples.length) { + // let's use input time scale as MP4 video timescale + // we use input time scale straight away to avoid rounding issues on frame duration / cts computation + var inputTimeScale = videoTrack.inputTimeScale; + videoTrack.timescale = inputTimeScale; + tracks.video = { + container: 'video/mp4', + codec: videoTrack.codec, + initSegment: mp4_generator.initSegment([videoTrack]), + metadata: { + width: videoTrack.width, + height: videoTrack.height + } + }; + if (computePTSDTS) { + initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset); + initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset); + this.observer.trigger(events["a" /* default */].INIT_PTS_FOUND, { initPTS: initPTS }); + } + } + + if (Object.keys(tracks).length) { + observer.trigger(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, data); + this.ISGenerated = true; + if (computePTSDTS) { + this._initPTS = initPTS; + this._initDTS = initDTS; + } + } else { + observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' }); + } + }; + + MP4Remuxer.prototype.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) { + var offset = 8, + timeScale = track.timescale, + mp4SampleDuration, + mdat, + moof, + firstPTS, + firstDTS, + nextDTS, + lastPTS, + lastDTS, + inputSamples = track.samples, + outputSamples = [], + nbSamples = inputSamples.length, + ptsNormalize = this._PTSNormalize, + initDTS = this._initDTS; + + // for (let i = 0; i < track.samples.length; i++) { + // let avcSample = track.samples[i]; + // let units = avcSample.units; + // let unitsString = ''; + // for (let j = 0; j < units.length ; j++) { + // unitsString += units[j].type + ','; + // if (units[j].data.length < 500) { + // unitsString += Hex.hexDump(units[j].data); + // } + // } + // logger.log(avcSample.pts + '/' + avcSample.dts + ',' + unitsString + avcSample.units.length); + // } + + // if parsed fragment is contiguous with last one, let's use last DTS value as reference + var nextAvcDts = this.nextAvcDts; + + var isSafari = this.isSafari; + + // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive + if (isSafari) { + // also consider consecutive fragments as being contiguous (even if a level switch occurs), + // for sake of clarity: + // consecutive fragments are frags with + // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR + // - less than 200 ms PTS gaps (timeScale/5) + contiguous |= inputSamples.length && nextAvcDts && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initDTS) < timeScale / 5); + } + + if (!contiguous) { + // if not contiguous, let's use target timeOffset + nextAvcDts = timeOffset * timeScale; + } + + // PTS is coded on 33bits, and can loop from -2^32 to 2^32 + // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value + inputSamples.forEach(function (sample) { + sample.pts = ptsNormalize(sample.pts - initDTS, nextAvcDts); + sample.dts = ptsNormalize(sample.dts - initDTS, nextAvcDts); + }); + + // sort video samples by DTS then PTS then demux id order + inputSamples.sort(function (a, b) { + var deltadts = a.dts - b.dts; + var deltapts = a.pts - b.pts; + return deltadts ? deltadts : deltapts ? deltapts : a.id - b.id; + }); + + // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale) + var PTSDTSshift = inputSamples.reduce(function (prev, curr) { + return Math.max(Math.min(prev, curr.pts - curr.dts), -18000); + }, 0); + if (PTSDTSshift < 0) { + logger["b" /* logger */].warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue'); + for (var i = 0; i < inputSamples.length; i++) { + inputSamples[i].dts += PTSDTSshift; + } + } + + // compute first DTS and last DTS, normalize them against reference value + var sample = inputSamples[0]; + firstDTS = Math.max(sample.dts, 0); + firstPTS = Math.max(sample.pts, 0); + + // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole) + var delta = Math.round((firstDTS - nextAvcDts) / 90); + // if fragment are contiguous, detect hole/overlapping between fragments + if (contiguous) { + if (delta) { + if (delta > 1) { + logger["b" /* logger */].log('AVC:' + delta + ' ms hole between fragments detected,filling it'); + } else if (delta < -1) { + logger["b" /* logger */].log('AVC:' + -delta + ' ms overlapping between fragments detected'); + } + // remove hole/gap : set DTS to next expected DTS + firstDTS = nextAvcDts; + inputSamples[0].dts = firstDTS; + // offset PTS as well, ensure that PTS is smaller or equal than new DTS + firstPTS = Math.max(firstPTS - delta, nextAvcDts); + inputSamples[0].pts = firstPTS; + logger["b" /* logger */].log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms'); + } + } + nextDTS = firstDTS; + + // compute lastPTS/lastDTS + sample = inputSamples[inputSamples.length - 1]; + lastDTS = Math.max(sample.dts, 0); + lastPTS = Math.max(sample.pts, 0, lastDTS); + + // on Safari let's signal the same sample duration for all samples + // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS + // set this constant duration as being the avg delta between consecutive DTS. + if (isSafari) { + mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1)); + } + + var nbNalu = 0, + naluLen = 0; + for (var _i = 0; _i < nbSamples; _i++) { + // compute total/avc sample length and nb of NAL units + var _sample = inputSamples[_i], + units = _sample.units, + nbUnits = units.length, + sampleLen = 0; + for (var j = 0; j < nbUnits; j++) { + sampleLen += units[j].data.length; + } + naluLen += sampleLen; + nbNalu += nbUnits; + _sample.length = sampleLen; + + // normalize PTS/DTS + if (isSafari) { + // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples + _sample.dts = firstDTS + _i * mp4SampleDuration; + } else { + // ensure sample monotonic DTS + _sample.dts = Math.max(_sample.dts, firstDTS); + } + // ensure that computed value is greater or equal than sample DTS + _sample.pts = Math.max(_sample.pts, _sample.dts); + } + + /* concatenate the video data and construct the mdat in place + (need 8 more bytes to fill length and mpdat type) */ + var mdatSize = naluLen + 4 * nbNalu + 8; + try { + mdat = new Uint8Array(mdatSize); + } catch (err) { + this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MUX_ERROR, details: errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating video mdat ' + mdatSize }); + return; + } + var view = new DataView(mdat.buffer); + view.setUint32(0, mdatSize); + mdat.set(mp4_generator.types.mdat, 4); + + for (var _i2 = 0; _i2 < nbSamples; _i2++) { + var avcSample = inputSamples[_i2], + avcSampleUnits = avcSample.units, + mp4SampleLength = 0, + compositionTimeOffset = void 0; + // convert NALU bitstream to MP4 format (prepend NALU with size field) + for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) { + var unit = avcSampleUnits[_j], + unitData = unit.data, + unitDataLen = unit.data.byteLength; + view.setUint32(offset, unitDataLen); + offset += 4; + mdat.set(unitData, offset); + offset += unitDataLen; + mp4SampleLength += 4 + unitDataLen; + } + + if (!isSafari) { + // expected sample duration is the Decoding Timestamp diff of consecutive samples + if (_i2 < nbSamples - 1) { + mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts; + } else { + var config = this.config, + lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts; + if (config.stretchShortVideoTrack) { + // In some cases, a segment's audio track duration may exceed the video track duration. + // Since we've already remuxed audio, and we know how long the audio track is, we look to + // see if the delta to the next segment is longer than the minimum of maxBufferHole and + // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate + // the duration of the last frame to minimize any potential gap between segments. + var maxBufferHole = config.maxBufferHole, + maxSeekHole = config.maxSeekHole, + gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * timeScale), + deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts; + if (deltaToFrameEnd > gapTolerance) { + // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video + // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway. + mp4SampleDuration = deltaToFrameEnd - lastFrameDuration; + if (mp4SampleDuration < 0) { + mp4SampleDuration = lastFrameDuration; + } + logger["b" /* logger */].log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.'); + } else { + mp4SampleDuration = lastFrameDuration; + } + } else { + mp4SampleDuration = lastFrameDuration; + } + } + compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts); + } else { + compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration)); + } + + //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}'); + outputSamples.push({ + size: mp4SampleLength, + // constant duration + duration: mp4SampleDuration, + cts: compositionTimeOffset, + flags: { + isLeading: 0, + isDependedOn: 0, + hasRedundancy: 0, + degradPrio: 0, + dependsOn: avcSample.key ? 2 : 1, + isNonSync: avcSample.key ? 0 : 1 + } + }); + } + // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale) + this.nextAvcDts = lastDTS + mp4SampleDuration; + var dropped = track.dropped; + track.len = 0; + track.nbNalu = 0; + track.dropped = 0; + if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var flags = outputSamples[0].flags; + // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue + // https://code.google.com/p/chromium/issues/detail?id=229412 + flags.dependsOn = 2; + flags.isNonSync = 0; + } + track.samples = outputSamples; + moof = mp4_generator.moof(track.sequenceNumber++, firstDTS, track); + track.samples = []; + + var data = { + data1: moof, + data2: mdat, + startPTS: firstPTS / timeScale, + endPTS: (lastPTS + mp4SampleDuration) / timeScale, + startDTS: firstDTS / timeScale, + endDTS: this.nextAvcDts / timeScale, + type: 'video', + nb: outputSamples.length, + dropped: dropped + }; + this.observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, data); + return data; + }; + + MP4Remuxer.prototype.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) { + var inputTimeScale = track.inputTimeScale, + mp4timeScale = track.timescale, + scaleFactor = inputTimeScale / mp4timeScale, + mp4SampleDuration = track.isAAC ? 1024 : 1152, + inputSampleDuration = mp4SampleDuration * scaleFactor, + ptsNormalize = this._PTSNormalize, + initDTS = this._initDTS, + rawMPEG = !track.isAAC && this.typeSupported.mpeg; + + var offset, + mp4Sample, + fillFrame, + mdat, + moof, + firstPTS, + lastPTS, + inputSamples = track.samples, + outputSamples = [], + nextAudioPts = this.nextAudioPts; + + // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs), + // for sake of clarity: + // consecutive fragments are frags with + // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR + // - less than 20 audio frames distance + // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1) + // this helps ensuring audio continuity + // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame + contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initDTS) < 20 * inputSampleDuration); + + if (!contiguous) { + // if fragments are not contiguous, let's use timeOffset to compute next Audio PTS + nextAudioPts = timeOffset * inputTimeScale; + } + + // compute normalized PTS + inputSamples.forEach(function (sample) { + sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, nextAudioPts); + }); + + // sort based on normalized PTS (this is to avoid sorting issues in case timestamp + // reloop in the middle of our samples array) + inputSamples.sort(function (a, b) { + return a.pts - b.pts; + }); + + // If the audio track is missing samples, the frames seem to get "left-shifted" within the + // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment. + // In an effort to prevent this from happening, we inject frames here where there are gaps. + // When possible, we inject a silent frame; when that's not possible, we duplicate the last + // frame. + + // only inject/drop audio frames in case time offset is accurate + if (accurateTimeOffset && track.isAAC) { + var maxAudioFramesDrift = this.config.maxAudioFramesDrift; + for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) { + // First, let's see how far off this frame is from where we expect it to be + var sample = inputSamples[i], + delta; + var pts = sample.pts; + delta = pts - nextPts; + + //console.log(Math.round(pts) + '/' + Math.round(nextPts) + '/' + Math.round(delta)); + var duration = Math.abs(1000 * delta / inputTimeScale); + + // If we're overlapping by more than a duration, drop this sample + if (delta <= -maxAudioFramesDrift * inputSampleDuration) { + logger["b" /* logger */].warn('Dropping 1 audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(duration) + ' ms overlap.'); + inputSamples.splice(i, 1); + track.len -= sample.unit.length; + // Don't touch nextPtsNorm or i + } + + // Insert missing frames if: + // 1: We're more than maxAudioFramesDrift frame away + // 2: Not more than MAX_SILENT_FRAME_DURATION away + // 3: currentTime (aka nextPtsNorm) is not 0 + else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) { + var missing = Math.round(delta / inputSampleDuration); + logger["b" /* logger */].warn('Injecting ' + missing + ' audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(1000 * delta / inputTimeScale) + ' ms gap.'); + for (var j = 0; j < missing; j++) { + var newStamp = Math.max(nextPts, 0); + fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); + if (!fillFrame) { + logger["b" /* logger */].log('Unable to get silent frame for given audio codec; duplicating last frame instead.'); + fillFrame = sample.unit.subarray(); + } + inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp }); + track.len += fillFrame.length; + nextPts += inputSampleDuration; + i++; + } + + // Adjust sample to next expected pts + sample.pts = sample.dts = nextPts; + nextPts += inputSampleDuration; + i++; + } else { + // Otherwise, just adjust pts + if (Math.abs(delta) > 0.1 * inputSampleDuration) { + //logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`); + } + sample.pts = sample.dts = nextPts; + nextPts += inputSampleDuration; + i++; + } + } + } + + for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) { + var audioSample = inputSamples[_j2]; + var unit = audioSample.unit; + var _pts = audioSample.pts; + //logger.log(`Audio/PTS:${Math.round(pts/90)}`); + // if not first sample + if (lastPTS !== undefined) { + mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor); + } else { + var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale), + numMissingFrames = 0; + // if fragment are contiguous, detect hole/overlapping between fragments + // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1) + if (contiguous && track.isAAC) { + // log delta + if (_delta) { + if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) { + numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration); + logger["b" /* logger */].log(_delta + ' ms hole between AAC samples detected,filling it'); + if (numMissingFrames > 0) { + fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); + if (!fillFrame) { + fillFrame = unit.subarray(); + } + track.len += numMissingFrames * fillFrame.length; + } + // if we have frame overlap, overlapping for more than half a frame duraion + } else if (_delta < -12) { + // drop overlapping audio frames... browser will deal with it + logger["b" /* logger */].log('drop overlapping AAC sample, expected/parsed/delta:' + (nextAudioPts / inputTimeScale).toFixed(3) + 's/' + (_pts / inputTimeScale).toFixed(3) + 's/' + -_delta + 'ms'); + track.len -= unit.byteLength; + continue; + } + // set PTS/DTS to expected PTS/DTS + _pts = nextAudioPts; + } + } + // remember first PTS of our audioSamples, ensure value is positive + firstPTS = Math.max(0, _pts); + if (track.len > 0) { + /* concatenate the audio data and construct the mdat in place + (need 8 more bytes to fill length and mdat type) */ + var mdatSize = rawMPEG ? track.len : track.len + 8; + offset = rawMPEG ? 0 : 8; + try { + mdat = new Uint8Array(mdatSize); + } catch (err) { + this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MUX_ERROR, details: errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating audio mdat ' + mdatSize }); + return; + } + if (!rawMPEG) { + var view = new DataView(mdat.buffer); + view.setUint32(0, mdatSize); + mdat.set(mp4_generator.types.mdat, 4); + } + } else { + // no audio samples + return; + } + for (var _i3 = 0; _i3 < numMissingFrames; _i3++) { + fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); + if (!fillFrame) { + logger["b" /* logger */].log('Unable to get silent frame for given audio codec; duplicating this frame instead.'); + fillFrame = unit.subarray(); + } + mdat.set(fillFrame, offset); + offset += fillFrame.byteLength; + mp4Sample = { + size: fillFrame.byteLength, + cts: 0, + duration: 1024, + flags: { + isLeading: 0, + isDependedOn: 0, + hasRedundancy: 0, + degradPrio: 0, + dependsOn: 1 + } + }; + outputSamples.push(mp4Sample); + } + } + mdat.set(unit, offset); + var unitLen = unit.byteLength; + offset += unitLen; + //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}'); + mp4Sample = { + size: unitLen, + cts: 0, + duration: 0, + flags: { + isLeading: 0, + isDependedOn: 0, + hasRedundancy: 0, + degradPrio: 0, + dependsOn: 1 + } + }; + outputSamples.push(mp4Sample); + lastPTS = _pts; + } + var lastSampleDuration = 0; + var nbSamples = outputSamples.length; + //set last sample duration as being identical to previous sample + if (nbSamples >= 2) { + lastSampleDuration = outputSamples[nbSamples - 2].duration; + mp4Sample.duration = lastSampleDuration; + } + if (nbSamples) { + // next audio sample PTS should be equal to last sample PTS + duration + this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration; + //logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0)); + track.len = 0; + track.samples = outputSamples; + if (rawMPEG) { + moof = new Uint8Array(); + } else { + moof = mp4_generator.moof(track.sequenceNumber++, firstPTS / scaleFactor, track); + } + track.samples = []; + var start = firstPTS / inputTimeScale; + var end = nextAudioPts / inputTimeScale; + var audioData = { + data1: moof, + data2: mdat, + startPTS: start, + endPTS: end, + startDTS: start, + endDTS: end, + type: 'audio', + nb: nbSamples + }; + this.observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, audioData); + return audioData; + } + return null; + }; + + MP4Remuxer.prototype.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) { + var inputTimeScale = track.inputTimeScale, + mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale, + scaleFactor = inputTimeScale / mp4timeScale, + nextAudioPts = this.nextAudioPts, + + + // sync with video's timestamp + startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS, + endDTS = videoData.endDTS * inputTimeScale + this._initDTS, + + // one sample's duration value + sampleDuration = 1024, + frameDuration = scaleFactor * sampleDuration, + + + // samples count of this segment's duration + nbSamples = Math.ceil((endDTS - startDTS) / frameDuration), + + + // silent frame + silentFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount); + + logger["b" /* logger */].warn('remux empty Audio'); + // Can't remux if we can't generate a silent frame... + if (!silentFrame) { + logger["b" /* logger */].trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!'); + return; + } + + var samples = []; + for (var i = 0; i < nbSamples; i++) { + var stamp = startDTS + i * frameDuration; + samples.push({ unit: silentFrame, pts: stamp, dts: stamp }); + track.len += silentFrame.length; + } + track.samples = samples; + + this.remuxAudio(track, timeOffset, contiguous); + }; + + MP4Remuxer.prototype.remuxID3 = function remuxID3(track, timeOffset) { + var length = track.samples.length, + sample; + var inputTimeScale = track.inputTimeScale; + var initPTS = this._initPTS; + var initDTS = this._initDTS; + // consume samples + if (length) { + for (var index = 0; index < length; index++) { + sample = track.samples[index]; + // setting id3 pts, dts to relative time + // using this._initPTS and this._initDTS to calculate relative time + sample.pts = (sample.pts - initPTS) / inputTimeScale; + sample.dts = (sample.dts - initDTS) / inputTimeScale; + } + this.observer.trigger(events["a" /* default */].FRAG_PARSING_METADATA, { + samples: track.samples + }); + } + + track.samples = []; + timeOffset = timeOffset; + }; + + MP4Remuxer.prototype.remuxText = function remuxText(track, timeOffset) { + track.samples.sort(function (a, b) { + return a.pts - b.pts; + }); + + var length = track.samples.length, + sample; + var inputTimeScale = track.inputTimeScale; + var initPTS = this._initPTS; + // consume samples + if (length) { + for (var index = 0; index < length; index++) { + sample = track.samples[index]; + // setting text pts, dts to relative time + // using this._initPTS and this._initDTS to calculate relative time + sample.pts = (sample.pts - initPTS) / inputTimeScale; + } + this.observer.trigger(events["a" /* default */].FRAG_PARSING_USERDATA, { + samples: track.samples + }); + } + + track.samples = []; + timeOffset = timeOffset; + }; + + MP4Remuxer.prototype._PTSNormalize = function _PTSNormalize(value, reference) { + var offset; + if (reference === undefined) { + return value; + } + if (reference < value) { + // - 2^33 + offset = -8589934592; + } else { + // + 2^33 + offset = 8589934592; + } + /* PTS is 33bit (from 0 to 2^33 -1) + if diff between value and reference is bigger than half of the amplitude (2^32) then it means that + PTS looping occured. fill the gap */ + while (Math.abs(value - reference) > 4294967296) { + value += offset; + } + return value; + }; + + return MP4Remuxer; +}(); + +/* harmony default export */ var mp4_remuxer = (mp4_remuxer_MP4Remuxer); +// CONCATENATED MODULE: ./src/remux/passthrough-remuxer.js +function passthrough_remuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * passthrough remuxer +*/ + + +var passthrough_remuxer_PassThroughRemuxer = function () { + function PassThroughRemuxer(observer) { + passthrough_remuxer__classCallCheck(this, PassThroughRemuxer); + + this.observer = observer; + } + + PassThroughRemuxer.prototype.destroy = function destroy() {}; + + PassThroughRemuxer.prototype.resetTimeStamp = function resetTimeStamp() {}; + + PassThroughRemuxer.prototype.resetInitSegment = function resetInitSegment() {}; + + PassThroughRemuxer.prototype.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) { + var observer = this.observer; + var streamType = ''; + if (audioTrack) { + streamType += 'audio'; + } + if (videoTrack) { + streamType += 'video'; + } + observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, { + data1: rawData, + startPTS: timeOffset, + startDTS: timeOffset, + type: streamType, + nb: 1, + dropped: 0 + }); + //notify end of parsing + observer.trigger(events["a" /* default */].FRAG_PARSED); + }; + + return PassThroughRemuxer; +}(); + +/* harmony default export */ var passthrough_remuxer = (passthrough_remuxer_PassThroughRemuxer); +// CONCATENATED MODULE: ./src/demux/demuxer-inline.js +function demuxer_inline__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/* inline demuxer. + * probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...) + */ + + + + + + + + + + + +var demuxer_inline_DemuxerInline = function () { + function DemuxerInline(observer, typeSupported, config, vendor) { + demuxer_inline__classCallCheck(this, DemuxerInline); + + this.observer = observer; + this.typeSupported = typeSupported; + this.config = config; + this.vendor = vendor; + } + + DemuxerInline.prototype.destroy = function destroy() { + var demuxer = this.demuxer; + if (demuxer) { + demuxer.destroy(); + } + }; + + DemuxerInline.prototype.push = function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) { + if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') { + var decrypter = this.decrypter; + if (decrypter == null) { + decrypter = this.decrypter = new crypt_decrypter["a" /* default */](this.observer, this.config); + } + var localthis = this; + // performance.now() not available on WebWorker, at least on Safari Desktop + var startTime; + try { + startTime = performance.now(); + } catch (error) { + startTime = Date.now(); + } + decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) { + var endTime; + try { + endTime = performance.now(); + } catch (error) { + endTime = Date.now(); + } + localthis.observer.trigger(events["a" /* default */].FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } }); + localthis.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS); + }); + } else { + this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS); + } + }; + + DemuxerInline.prototype.pushDecrypted = function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) { + var demuxer = this.demuxer; + if (!demuxer || + // in case of continuity change, we might switch from content type (AAC container to TS container for example) + // so let's check that current demuxer is still valid + discontinuity && !this.probe(data)) { + var observer = this.observer; + var typeSupported = this.typeSupported; + var config = this.config; + // probing order is TS/AAC/MP3/MP4 + var muxConfig = [{ demux: tsdemuxer, remux: mp4_remuxer }, { demux: aacdemuxer, remux: mp4_remuxer }, { demux: mp3demuxer, remux: mp4_remuxer }, { demux: mp4demuxer, remux: passthrough_remuxer }]; + + // probe for content type + for (var i = 0, len = muxConfig.length; i < len; i++) { + var mux = muxConfig[i]; + var probe = mux.demux.probe; + if (probe(data)) { + var _remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor); + demuxer = new mux.demux(observer, _remuxer, config, typeSupported); + this.probe = probe; + break; + } + } + if (!demuxer) { + observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' }); + return; + } + this.demuxer = demuxer; + } + var remuxer = this.remuxer; + + if (discontinuity || trackSwitch) { + demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration); + remuxer.resetInitSegment(); + } + if (discontinuity) { + demuxer.resetTimeStamp(defaultInitPTS); + remuxer.resetTimeStamp(defaultInitPTS); + } + if (typeof demuxer.setDecryptData === 'function') { + demuxer.setDecryptData(decryptdata); + } + demuxer.append(data, timeOffset, contiguous, accurateTimeOffset); + }; + + return DemuxerInline; +}(); + +/* harmony default export */ var demuxer_inline = __webpack_exports__["a"] = (demuxer_inline_DemuxerInline); + +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +var cues_namespaceObject = {}; +__webpack_require__.d(cues_namespaceObject, "newCue", function() { return newCue; }); + +// EXTERNAL MODULE: ./node_modules/url-toolkit/src/url-toolkit.js +var url_toolkit = __webpack_require__(6); +var url_toolkit_default = /*#__PURE__*/__webpack_require__.n(url_toolkit); + +// EXTERNAL MODULE: ./src/events.js +var events = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/errors.js +var errors = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/utils/logger.js +var logger = __webpack_require__(0); + +// CONCATENATED MODULE: ./src/event-handler.js +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/* +* +* All objects in the event handling chain should inherit from this class +* +*/ + + + + + +var event_handler_EventHandler = function () { + function EventHandler(hls) { + _classCallCheck(this, EventHandler); + + this.hls = hls; + this.onEvent = this.onEvent.bind(this); + + for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + events[_key - 1] = arguments[_key]; + } + + this.handledEvents = events; + this.useGenericHandler = true; + + this.registerListeners(); + } + + EventHandler.prototype.destroy = function destroy() { + this.unregisterListeners(); + }; + + EventHandler.prototype.isEventHandler = function isEventHandler() { + return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function'; + }; + + EventHandler.prototype.registerListeners = function registerListeners() { + if (this.isEventHandler()) { + this.handledEvents.forEach(function (event) { + if (event === 'hlsEventGeneric') { + throw new Error('Forbidden event name: ' + event); + } + this.hls.on(event, this.onEvent); + }, this); + } + }; + + EventHandler.prototype.unregisterListeners = function unregisterListeners() { + if (this.isEventHandler()) { + this.handledEvents.forEach(function (event) { + this.hls.off(event, this.onEvent); + }, this); + } + }; + + /** + * arguments: event (string), data (any) + */ + + + EventHandler.prototype.onEvent = function onEvent(event, data) { + this.onEventGeneric(event, data); + }; + + EventHandler.prototype.onEventGeneric = function onEventGeneric(event, data) { + var eventToFunction = function eventToFunction(event, data) { + var funcName = 'on' + event.replace('hls', ''); + if (typeof this[funcName] !== 'function') { + throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')'); + } + return this[funcName].bind(this, data); + }; + try { + eventToFunction.call(this, event, data).call(); + } catch (err) { + logger["b" /* logger */].error('internal error happened while processing ' + event + ':' + err.message); + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: false, event: event, err: err }); + } + }; + + return EventHandler; +}(); + +/* harmony default export */ var event_handler = (event_handler_EventHandler); +// CONCATENATED MODULE: ./src/utils/attr-list.js +function attr_list__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; +var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; + +// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js + +var AttrList = function () { + function AttrList(attrs) { + attr_list__classCallCheck(this, AttrList); + + if (typeof attrs === 'string') { + attrs = AttrList.parseAttrList(attrs); + } + for (var attr in attrs) { + if (attrs.hasOwnProperty(attr)) { + this[attr] = attrs[attr]; + } + } + } + + AttrList.prototype.decimalInteger = function decimalInteger(attrName) { + var intValue = parseInt(this[attrName], 10); + if (intValue > Number.MAX_SAFE_INTEGER) { + return Infinity; + } + return intValue; + }; + + AttrList.prototype.hexadecimalInteger = function hexadecimalInteger(attrName) { + if (this[attrName]) { + var stringValue = (this[attrName] || '0x').slice(2); + stringValue = (stringValue.length & 1 ? '0' : '') + stringValue; + + var value = new Uint8Array(stringValue.length / 2); + for (var i = 0; i < stringValue.length / 2; i++) { + value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16); + } + return value; + } else { + return null; + } + }; + + AttrList.prototype.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) { + var intValue = parseInt(this[attrName], 16); + if (intValue > Number.MAX_SAFE_INTEGER) { + return Infinity; + } + return intValue; + }; + + AttrList.prototype.decimalFloatingPoint = function decimalFloatingPoint(attrName) { + return parseFloat(this[attrName]); + }; + + AttrList.prototype.enumeratedString = function enumeratedString(attrName) { + return this[attrName]; + }; + + AttrList.prototype.decimalResolution = function decimalResolution(attrName) { + var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]); + if (res === null) { + return undefined; + } + return { + width: parseInt(res[1], 10), + height: parseInt(res[2], 10) + }; + }; + + AttrList.parseAttrList = function parseAttrList(input) { + var match, + attrs = {}; + ATTR_LIST_REGEX.lastIndex = 0; + while ((match = ATTR_LIST_REGEX.exec(input)) !== null) { + var value = match[2], + quote = '"'; + + if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) { + value = value.slice(1, -1); + } + attrs[match[1]] = value; + } + return attrs; + }; + + return AttrList; +}(); + +/* harmony default export */ var attr_list = (AttrList); +// CONCATENATED MODULE: ./src/utils/codecs.js +// from http://mp4ra.org/codecs.html +var sampleEntryCodesISO = { + audio: { + 'a3ds': true, + 'ac-3': true, + 'ac-4': true, + 'alac': true, + 'alaw': true, + 'dra1': true, + 'dts+': true, + 'dts-': true, + 'dtsc': true, + 'dtse': true, + 'dtsh': true, + 'ec-3': true, + 'enca': true, + 'g719': true, + 'g726': true, + 'm4ae': true, + 'mha1': true, + 'mha2': true, + 'mhm1': true, + 'mhm2': true, + 'mlpa': true, + 'mp4a': true, + 'raw ': true, + 'Opus': true, + 'samr': true, + 'sawb': true, + 'sawp': true, + 'sevc': true, + 'sqcp': true, + 'ssmv': true, + 'twos': true, + 'ulaw': true + }, + video: { + 'avc1': true, + 'avc2': true, + 'avc3': true, + 'avc4': true, + 'avcp': true, + 'drac': true, + 'dvav': true, + 'dvhe': true, + 'encv': true, + 'hev1': true, + 'hvc1': true, + 'mjp2': true, + 'mp4v': true, + 'mvc1': true, + 'mvc2': true, + 'mvc3': true, + 'mvc4': true, + 'resv': true, + 'rv60': true, + 's263': true, + 'svc1': true, + 'svc2': true, + 'vc-1': true, + 'vp08': true, + 'vp09': true + } +}; + +function isCodecType(codec, type) { + var typeCodes = sampleEntryCodesISO[type]; + return !!typeCodes && typeCodes[codec.slice(0, 4)] === true; +} + +function isCodecSupportedInMp4(codec, type) { + return MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs="' + codec + '"'); +} + + +// CONCATENATED MODULE: ./src/loader/playlist-loader.js +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; }; }(); + +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; } + +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; } + +function playlist_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Playlist Loader +*/ + + + + + + + + + +// https://regex101.com is your friend +var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g; +var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g; + +var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:,), group 1 => duration, group 2 => title +/|(?!#)(\S+)/.source, // segment URI, group 3 => the URI (note newline is not eaten) +/|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y) +/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec +/|#.*/.source // All other non-segment oriented tags will match with all groups empty +].join(''), 'g'); + +var LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/; + +var playlist_loader_LevelKey = function () { + function LevelKey() { + playlist_loader__classCallCheck(this, LevelKey); + + this.method = null; + this.key = null; + this.iv = null; + this._uri = null; + } + + _createClass(LevelKey, [{ + key: 'uri', + get: function get() { + if (!this._uri && this.reluri) { + this._uri = url_toolkit_default.a.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true }); + } + return this._uri; + } + }]); + + return LevelKey; +}(); + +var playlist_loader_Fragment = function () { + function Fragment() { + playlist_loader__classCallCheck(this, Fragment); + + this._url = null; + this._byteRange = null; + this._decryptdata = null; + this.tagList = []; + } + + /** + * Utility method for parseLevelPlaylist to create an initialization vector for a given segment + * @returns {Uint8Array} + */ + Fragment.prototype.createInitializationVector = function createInitializationVector(segmentNumber) { + var uint8View = new Uint8Array(16); + + for (var i = 12; i < 16; i++) { + uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff; + } + + return uint8View; + }; + + /** + * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data + * @param levelkey - a playlist's encryption info + * @param segmentNumber - the fragment's segment number + * @returns {*} - an object to be applied as a fragment's decryptdata + */ + + + Fragment.prototype.fragmentDecryptdataFromLevelkey = function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) { + var decryptdata = levelkey; + + if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) { + decryptdata = new playlist_loader_LevelKey(); + decryptdata.method = levelkey.method; + decryptdata.baseuri = levelkey.baseuri; + decryptdata.reluri = levelkey.reluri; + decryptdata.iv = this.createInitializationVector(segmentNumber); + } + + return decryptdata; + }; + + Fragment.prototype.cloneObj = function cloneObj(obj) { + return JSON.parse(JSON.stringify(obj)); + }; + + _createClass(Fragment, [{ + key: 'url', + get: function get() { + if (!this._url && this.relurl) { + this._url = url_toolkit_default.a.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true }); + } + return this._url; + }, + set: function set(value) { + this._url = value; + } + }, { + key: 'programDateTime', + get: function get() { + if (!this._programDateTime && this.rawProgramDateTime) { + this._programDateTime = new Date(Date.parse(this.rawProgramDateTime)); + } + return this._programDateTime; + } + }, { + key: 'byteRange', + get: function get() { + if (!this._byteRange) { + var byteRange = this._byteRange = []; + if (this.rawByteRange) { + var params = this.rawByteRange.split('@', 2); + if (params.length === 1) { + var lastByteRangeEndOffset = this.lastByteRangeEndOffset; + byteRange[0] = lastByteRangeEndOffset ? lastByteRangeEndOffset : 0; + } else { + byteRange[0] = parseInt(params[1]); + } + byteRange[1] = parseInt(params[0]) + byteRange[0]; + } + } + return this._byteRange; + } + }, { + key: 'byteRangeStartOffset', + get: function get() { + return this.byteRange[0]; + } + }, { + key: 'byteRangeEndOffset', + get: function get() { + return this.byteRange[1]; + } + }, { + key: 'decryptdata', + get: function get() { + if (!this._decryptdata) { + this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn); + } + return this._decryptdata; + } + }]); + + return Fragment; +}(); + +function findGroup(groups, mediaGroupId) { + if (!groups) { + return null; + } + + var matchingGroup = null; + + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + if (group.id === mediaGroupId) { + matchingGroup = group; + } + } + + return matchingGroup; +} + +var playlist_loader_PlaylistLoader = function (_EventHandler) { + _inherits(PlaylistLoader, _EventHandler); + + function PlaylistLoader(hls) { + playlist_loader__classCallCheck(this, PlaylistLoader); + + var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].LEVEL_LOADING, events["a" /* default */].AUDIO_TRACK_LOADING, events["a" /* default */].SUBTITLE_TRACK_LOADING)); + + _this.loaders = {}; + return _this; + } + + PlaylistLoader.prototype.destroy = function destroy() { + for (var loaderName in this.loaders) { + var loader = this.loaders[loaderName]; + if (loader) { + loader.destroy(); + } + } + this.loaders = {}; + event_handler.prototype.destroy.call(this); + }; + + PlaylistLoader.prototype.onManifestLoading = function onManifestLoading(data) { + this.load(data.url, { type: 'manifest' }); + }; + + PlaylistLoader.prototype.onLevelLoading = function onLevelLoading(data) { + this.load(data.url, { type: 'level', level: data.level, id: data.id }); + }; + + PlaylistLoader.prototype.onAudioTrackLoading = function onAudioTrackLoading(data) { + this.load(data.url, { type: 'audioTrack', id: data.id }); + }; + + PlaylistLoader.prototype.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) { + this.load(data.url, { type: 'subtitleTrack', id: data.id }); + }; + + PlaylistLoader.prototype.load = function load(url, context) { + var loader = this.loaders[context.type]; + if (loader) { + var loaderContext = loader.context; + if (loaderContext && loaderContext.url === url) { + logger["b" /* logger */].trace('playlist request ongoing'); + return; + } else { + logger["b" /* logger */].warn('abort previous loader for type:' + context.type); + loader.abort(); + } + } + var config = this.hls.config, + retry = void 0, + timeout = void 0, + retryDelay = void 0, + maxRetryDelay = void 0; + if (context.type === 'manifest') { + retry = config.manifestLoadingMaxRetry; + timeout = config.manifestLoadingTimeOut; + retryDelay = config.manifestLoadingRetryDelay; + maxRetryDelay = config.manifestLoadingMaxRetryTimeout; + } else { + retry = config.levelLoadingMaxRetry; + timeout = config.levelLoadingTimeOut; + retryDelay = config.levelLoadingRetryDelay; + maxRetryDelay = config.levelLoadingMaxRetryTimeout; + logger["b" /* logger */].log('loading playlist for ' + context.type + ' ' + (context.level || context.id)); + } + loader = this.loaders[context.type] = context.loader = typeof config.pLoader !== 'undefined' ? new config.pLoader(config) : new config.loader(config); + context.url = url; + context.responseType = ''; + + var loaderConfig = void 0, + loaderCallbacks = void 0; + loaderConfig = { timeout: timeout, maxRetry: retry, retryDelay: retryDelay, maxRetryDelay: maxRetryDelay }; + loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) }; + loader.load(context, loaderConfig, loaderCallbacks); + }; + + PlaylistLoader.prototype.resolve = function resolve(url, baseUrl) { + return url_toolkit_default.a.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true }); + }; + + PlaylistLoader.prototype.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) { + var levels = [], + result = void 0; + MASTER_PLAYLIST_REGEX.lastIndex = 0; + + function setCodecs(codecs, level) { + ['video', 'audio'].forEach(function (type) { + var filtered = codecs.filter(function (codec) { + return isCodecType(codec, type); + }); + if (filtered.length) { + var preferred = filtered.filter(function (codec) { + return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0; + }); + level[type + 'Codec'] = preferred.length > 0 ? preferred[0] : filtered[0]; + + // remove from list + codecs = codecs.filter(function (codec) { + return filtered.indexOf(codec) === -1; + }); + } + }); + + level.unknownCodecs = codecs; + } + + while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) { + var level = {}; + + var attrs = level.attrs = new attr_list(result[1]); + level.url = this.resolve(result[2], baseurl); + + var resolution = attrs.decimalResolution('RESOLUTION'); + if (resolution) { + level.width = resolution.width; + level.height = resolution.height; + } + level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'); + level.name = attrs.NAME; + + setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level); + + if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) { + level.videoCodec = this.avc1toavcoti(level.videoCodec); + } + + levels.push(level); + } + return levels; + }; + + PlaylistLoader.prototype.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type) { + var audioGroups = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; + + var result = void 0; + var medias = []; + var id = 0; + MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0; + while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) { + var media = {}; + var attrs = new attr_list(result[1]); + if (attrs.TYPE === type) { + media.groupId = attrs['GROUP-ID']; + media.name = attrs.NAME; + media.type = type; + media.default = attrs.DEFAULT === 'YES'; + media.autoselect = attrs.AUTOSELECT === 'YES'; + media.forced = attrs.FORCED === 'YES'; + if (attrs.URI) { + media.url = this.resolve(attrs.URI, baseurl); + } + media.lang = attrs.LANGUAGE; + if (!media.name) { + media.name = media.lang; + } + if (audioGroups.length) { + var groupCodec = findGroup(audioGroups, media.groupId); + media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec; + } + media.id = id++; + medias.push(media); + } + } + return medias; + }; + + PlaylistLoader.prototype.avc1toavcoti = function avc1toavcoti(codec) { + var result, + avcdata = codec.split('.'); + if (avcdata.length > 2) { + result = avcdata.shift() + '.'; + result += parseInt(avcdata.shift()).toString(16); + result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4); + } else { + result = codec; + } + return result; + }; + + PlaylistLoader.prototype.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type) { + var currentSN = 0, + totalduration = 0, + level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 }, + levelkey = new playlist_loader_LevelKey(), + cc = 0, + prevFrag = null, + frag = new playlist_loader_Fragment(), + result, + i; + + LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0; + + while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) { + var duration = result[1]; + if (duration) { + // INF + frag.duration = parseFloat(duration); + // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 + var title = (' ' + result[2]).slice(1); + frag.title = title ? title : null; + frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]); + } else if (result[3]) { + // url + if (!isNaN(frag.duration)) { + var sn = currentSN++; + frag.type = type; + frag.start = totalduration; + frag.levelkey = levelkey; + frag.sn = sn; + frag.level = id; + frag.cc = cc; + frag.baseurl = baseurl; + // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 + frag.relurl = (' ' + result[3]).slice(1); + + level.fragments.push(frag); + prevFrag = frag; + totalduration += frag.duration; + + frag = new playlist_loader_Fragment(); + } + } else if (result[4]) { + // X-BYTERANGE + frag.rawByteRange = (' ' + result[4]).slice(1); + if (prevFrag) { + var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset; + if (lastByteRangeEndOffset) { + frag.lastByteRangeEndOffset = lastByteRangeEndOffset; + } + } + } else if (result[5]) { + // PROGRAM-DATE-TIME + // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 + frag.rawProgramDateTime = (' ' + result[5]).slice(1); + frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]); + if (level.programDateTime === undefined) { + level.programDateTime = new Date(new Date(Date.parse(result[5])) - 1000 * totalduration); + } + } else { + result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW); + for (i = 1; i < result.length; i++) { + if (result[i] !== undefined) { + break; + } + } + + // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 + var value1 = (' ' + result[i + 1]).slice(1); + var value2 = (' ' + result[i + 2]).slice(1); + + switch (result[i]) { + case '#': + frag.tagList.push(value2 ? [value1, value2] : [value1]); + break; + case 'PLAYLIST-TYPE': + level.type = value1.toUpperCase(); + break; + case 'MEDIA-SEQUENCE': + currentSN = level.startSN = parseInt(value1); + break; + case 'TARGETDURATION': + level.targetduration = parseFloat(value1); + break; + case 'VERSION': + level.version = parseInt(value1); + break; + case 'EXTM3U': + break; + case 'ENDLIST': + level.live = false; + break; + case 'DIS': + cc++; + frag.tagList.push(['DIS']); + break; + case 'DISCONTINUITY-SEQ': + cc = parseInt(value1); + break; + case 'KEY': + // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4 + var decryptparams = value1; + var keyAttrs = new attr_list(decryptparams); + var decryptmethod = keyAttrs.enumeratedString('METHOD'), + decrypturi = keyAttrs.URI, + decryptiv = keyAttrs.hexadecimalInteger('IV'); + if (decryptmethod) { + levelkey = new playlist_loader_LevelKey(); + if (decrypturi && ['AES-128', 'SAMPLE-AES'].indexOf(decryptmethod) >= 0) { + levelkey.method = decryptmethod; + // URI to get the key + levelkey.baseuri = baseurl; + levelkey.reluri = decrypturi; + levelkey.key = null; + // Initialization Vector (IV) + levelkey.iv = decryptiv; + } + } + break; + case 'START': + var startParams = value1; + var startAttrs = new attr_list(startParams); + var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); + //TIME-OFFSET can be 0 + if (!isNaN(startTimeOffset)) { + level.startTimeOffset = startTimeOffset; + } + break; + case 'MAP': + var mapAttrs = new attr_list(value1); + frag.relurl = mapAttrs.URI; + frag.rawByteRange = mapAttrs.BYTERANGE; + frag.baseurl = baseurl; + frag.level = id; + frag.type = type; + frag.sn = 'initSegment'; + level.initSegment = frag; + frag = new playlist_loader_Fragment(); + break; + default: + logger["b" /* logger */].warn('line parsed but not handled: ' + result); + break; + } + } + } + frag = prevFrag; + //logger.log('found ' + level.fragments.length + ' fragments'); + if (frag && !frag.relurl) { + level.fragments.pop(); + totalduration -= frag.duration; + } + level.totalduration = totalduration; + level.averagetargetduration = totalduration / level.fragments.length; + level.endSN = currentSN - 1; + level.startCC = level.fragments[0] ? level.fragments[0].cc : 0; + level.endCC = cc; + return level; + }; + + PlaylistLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) { + var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + + var string = response.data, + url = response.url, + type = context.type, + id = context.id, + level = context.level, + hls = this.hls; + + this.loaders[type] = undefined; + // responseURL not supported on some browsers (it is used to detect URL redirection) + // data-uri mode also not supported (but no need to detect redirection) + if (url === undefined || url.indexOf('data:') === 0) { + // fallback to initial URL + url = context.url; + } + stats.tload = performance.now(); + //stats.mtime = new Date(target.getResponseHeader('Last-Modified')); + if (string.indexOf('#EXTM3U') === 0) { + if (string.indexOf('#EXTINF:') > 0) { + var isLevel = type !== 'audioTrack' && type !== 'subtitleTrack', + levelId = !isNaN(level) ? level : !isNaN(id) ? id : 0, + levelDetails = this.parseLevelPlaylist(string, url, levelId, type === 'audioTrack' ? 'audio' : type === 'subtitleTrack' ? 'subtitle' : 'main'); + levelDetails.tload = stats.tload; + if (type === 'manifest') { + // first request, stream manifest (no master playlist), fire manifest loaded event with level details + hls.trigger(events["a" /* default */].MANIFEST_LOADED, { levels: [{ url: url, details: levelDetails }], audioTracks: [], url: url, stats: stats, networkDetails: networkDetails }); + } + stats.tparsed = performance.now(); + if (levelDetails.targetduration) { + if (isLevel) { + hls.trigger(events["a" /* default */].LEVEL_LOADED, { details: levelDetails, level: level || 0, id: id || 0, stats: stats, networkDetails: networkDetails }); + } else { + if (type === 'audioTrack') { + hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADED, { details: levelDetails, id: id, stats: stats, networkDetails: networkDetails }); + } else if (type === 'subtitleTrack') { + hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADED, { details: levelDetails, id: id, stats: stats, networkDetails: networkDetails }); + } + } + } else { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'invalid targetduration', networkDetails: networkDetails }); + } + } else { + var levels = this.parseMasterPlaylist(string, url); + // multi level playlist, parse level info + if (levels.length) { + var audioGroups = levels.map(function (l) { + return { id: l.attrs.AUDIO, codec: l.audioCodec }; + }); + var audioTracks = this.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups); + var subtitles = this.parseMasterPlaylistMedia(string, url, 'SUBTITLES'); + if (audioTracks.length) { + // check if we have found an audio track embedded in main playlist (audio track without URI attribute) + var embeddedAudioFound = false; + audioTracks.forEach(function (audioTrack) { + if (!audioTrack.url) { + embeddedAudioFound = true; + } + }); + // if no embedded audio track defined, but audio codec signaled in quality level, we need to signal this main audio track + // this could happen with playlists with alt audio rendition in which quality levels (main) contains both audio+video. but with mixed audio track not signaled + if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) { + logger["b" /* logger */].log('audio codec signaled in quality level, but no embedded audio track signaled, create one'); + audioTracks.unshift({ type: 'main', name: 'main' }); + } + } + hls.trigger(events["a" /* default */].MANIFEST_LOADED, { levels: levels, audioTracks: audioTracks, subtitles: subtitles, url: url, stats: stats, networkDetails: networkDetails }); + } else { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest', networkDetails: networkDetails }); + } + } + } else { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter', networkDetails: networkDetails }); + } + }; + + PlaylistLoader.prototype.loaderror = function loaderror(response, context) { + var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + var details, + fatal, + loader = context.loader; + switch (context.type) { + case 'manifest': + details = errors["a" /* ErrorDetails */].MANIFEST_LOAD_ERROR; + fatal = true; + break; + case 'level': + details = errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR; + fatal = false; + break; + case 'audioTrack': + details = errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR; + fatal = false; + break; + } + if (loader) { + loader.abort(); + this.loaders[context.type] = undefined; + } + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, response: response, context: context, networkDetails: networkDetails }); + }; + + PlaylistLoader.prototype.loadtimeout = function loadtimeout(stats, context) { + var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + var details, + fatal, + loader = context.loader; + switch (context.type) { + case 'manifest': + details = errors["a" /* ErrorDetails */].MANIFEST_LOAD_TIMEOUT; + fatal = true; + break; + case 'level': + details = errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT; + fatal = false; + break; + case 'audioTrack': + details = errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT; + fatal = false; + break; + } + if (loader) { + loader.abort(); + this.loaders[context.type] = undefined; + } + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, context: context, networkDetails: networkDetails }); + }; + + return PlaylistLoader; +}(event_handler); + +/* harmony default export */ var playlist_loader = (playlist_loader_PlaylistLoader); +// CONCATENATED MODULE: ./src/loader/fragment-loader.js +function fragment_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function fragment_loader__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; } + +function fragment_loader__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; } + +/* + * Fragment Loader +*/ + + + + + + +var fragment_loader_FragmentLoader = function (_EventHandler) { + fragment_loader__inherits(FragmentLoader, _EventHandler); + + function FragmentLoader(hls) { + fragment_loader__classCallCheck(this, FragmentLoader); + + var _this = fragment_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING)); + + _this.loaders = {}; + return _this; + } + + FragmentLoader.prototype.destroy = function destroy() { + var loaders = this.loaders; + for (var loaderName in loaders) { + var loader = loaders[loaderName]; + if (loader) { + loader.destroy(); + } + } + this.loaders = {}; + event_handler.prototype.destroy.call(this); + }; + + FragmentLoader.prototype.onFragLoading = function onFragLoading(data) { + var frag = data.frag, + type = frag.type, + loader = this.loaders[type], + config = this.hls.config; + + frag.loaded = 0; + if (loader) { + logger["b" /* logger */].warn('abort previous fragment loader for type:' + type); + loader.abort(); + } + loader = this.loaders[type] = frag.loader = typeof config.fLoader !== 'undefined' ? new config.fLoader(config) : new config.loader(config); + + var loaderContext = void 0, + loaderConfig = void 0, + loaderCallbacks = void 0; + loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false }; + var start = frag.byteRangeStartOffset, + end = frag.byteRangeEndOffset; + if (!isNaN(start) && !isNaN(end)) { + loaderContext.rangeStart = start; + loaderContext.rangeEnd = end; + } + loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: 0, maxRetryDelay: config.fragLoadingMaxRetryTimeout }; + loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this), onProgress: this.loadprogress.bind(this) }; + loader.load(loaderContext, loaderConfig, loaderCallbacks); + }; + + FragmentLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) { + var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + + var payload = response.data, + frag = context.frag; + // detach fragment loader on load success + frag.loader = undefined; + this.loaders[frag.type] = undefined; + this.hls.trigger(events["a" /* default */].FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails }); + }; + + FragmentLoader.prototype.loaderror = function loaderror(response, context) { + var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + var loader = context.loader; + if (loader) { + loader.abort(); + } + this.loaders[context.type] = undefined; + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails }); + }; + + FragmentLoader.prototype.loadtimeout = function loadtimeout(stats, context) { + var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + var loader = context.loader; + if (loader) { + loader.abort(); + } + this.loaders[context.type] = undefined; + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails }); + }; + + // data will be used for progressive parsing + + + FragmentLoader.prototype.loadprogress = function loadprogress(stats, context, data) { + var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + // jshint ignore:line + var frag = context.frag; + frag.loaded = stats.loaded; + this.hls.trigger(events["a" /* default */].FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails }); + }; + + return FragmentLoader; +}(event_handler); + +/* harmony default export */ var fragment_loader = (fragment_loader_FragmentLoader); +// CONCATENATED MODULE: ./src/loader/key-loader.js +function key_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function key_loader__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; } + +function key_loader__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; } + +/* + * Decrypt key Loader +*/ + + + + + + +var key_loader_KeyLoader = function (_EventHandler) { + key_loader__inherits(KeyLoader, _EventHandler); + + function KeyLoader(hls) { + key_loader__classCallCheck(this, KeyLoader); + + var _this = key_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].KEY_LOADING)); + + _this.loaders = {}; + _this.decryptkey = null; + _this.decrypturl = null; + return _this; + } + + KeyLoader.prototype.destroy = function destroy() { + for (var loaderName in this.loaders) { + var loader = this.loaders[loaderName]; + if (loader) { + loader.destroy(); + } + } + this.loaders = {}; + event_handler.prototype.destroy.call(this); + }; + + KeyLoader.prototype.onKeyLoading = function onKeyLoading(data) { + var frag = data.frag, + type = frag.type, + loader = this.loaders[type], + decryptdata = frag.decryptdata, + uri = decryptdata.uri; + // if uri is different from previous one or if decrypt key not retrieved yet + if (uri !== this.decrypturl || this.decryptkey === null) { + var config = this.hls.config; + + if (loader) { + logger["b" /* logger */].warn('abort previous key loader for type:' + type); + loader.abort(); + } + frag.loader = this.loaders[type] = new config.loader(config); + this.decrypturl = uri; + this.decryptkey = null; + + var loaderContext = void 0, + loaderConfig = void 0, + loaderCallbacks = void 0; + loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' }; + loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: config.fragLoadingMaxRetry, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout }; + loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) }; + frag.loader.load(loaderContext, loaderConfig, loaderCallbacks); + } else if (this.decryptkey) { + // we already loaded this key, return it + decryptdata.key = this.decryptkey; + this.hls.trigger(events["a" /* default */].KEY_LOADED, { frag: frag }); + } + }; + + KeyLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) { + var frag = context.frag; + this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); + // detach fragment loader on load success + frag.loader = undefined; + this.loaders[frag.type] = undefined; + this.hls.trigger(events["a" /* default */].KEY_LOADED, { frag: frag }); + }; + + KeyLoader.prototype.loaderror = function loaderror(response, context) { + var frag = context.frag, + loader = frag.loader; + if (loader) { + loader.abort(); + } + this.loaders[context.type] = undefined; + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response }); + }; + + KeyLoader.prototype.loadtimeout = function loadtimeout(stats, context) { + var frag = context.frag, + loader = frag.loader; + if (loader) { + loader.abort(); + } + this.loaders[context.type] = undefined; + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT, fatal: false, frag: frag }); + }; + + return KeyLoader; +}(event_handler); + +/* harmony default export */ var key_loader = (key_loader_KeyLoader); +// CONCATENATED MODULE: ./src/utils/binary-search.js +var BinarySearch = { + /** + * Searches for an item in an array which matches a certain condition. + * This requires the condition to only match one item in the array, + * and for the array to be ordered. + * + * @param {Array} list The array to search. + * @param {Function} comparisonFunction + * Called and provided a candidate item as the first argument. + * Should return: + * > -1 if the item should be located at a lower index than the provided item. + * > 1 if the item should be located at a higher index than the provided item. + * > 0 if the item is the item you're looking for. + * + * @return {*} The object if it is found or null otherwise. + */ + search: function search(list, comparisonFunction) { + var minIndex = 0; + var maxIndex = list.length - 1; + var currentIndex = null; + var currentElement = null; + + while (minIndex <= maxIndex) { + currentIndex = (minIndex + maxIndex) / 2 | 0; + currentElement = list[currentIndex]; + + var comparisonResult = comparisonFunction(currentElement); + if (comparisonResult > 0) { + minIndex = currentIndex + 1; + } else if (comparisonResult < 0) { + maxIndex = currentIndex - 1; + } else { + return currentElement; + } + } + + return null; + } +}; + +/* harmony default export */ var binary_search = (BinarySearch); +// CONCATENATED MODULE: ./src/helper/buffer-helper.js +/** + * Buffer Helper utils, providing methods dealing buffer length retrieval +*/ + +var BufferHelper = { + isBuffered: function isBuffered(media, position) { + if (media) { + var buffered = media.buffered; + for (var i = 0; i < buffered.length; i++) { + if (position >= buffered.start(i) && position <= buffered.end(i)) { + return true; + } + } + } + return false; + }, + + bufferInfo: function bufferInfo(media, pos, maxHoleDuration) { + if (media) { + var vbuffered = media.buffered, + buffered = [], + i; + for (i = 0; i < vbuffered.length; i++) { + buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) }); + } + return this.bufferedInfo(buffered, pos, maxHoleDuration); + } else { + return { len: 0, start: pos, end: pos, nextStart: undefined }; + } + }, + + bufferedInfo: function bufferedInfo(buffered, pos, maxHoleDuration) { + var buffered2 = [], + + // bufferStart and bufferEnd are buffer boundaries around current video position + bufferLen, + bufferStart, + bufferEnd, + bufferStartNext, + i; + // sort on buffer.start/smaller end (IE does not always return sorted buffered range) + buffered.sort(function (a, b) { + var diff = a.start - b.start; + if (diff) { + return diff; + } else { + return b.end - a.end; + } + }); + // there might be some small holes between buffer time range + // consider that holes smaller than maxHoleDuration are irrelevant and build another + // buffer time range representations that discards those holes + for (i = 0; i < buffered.length; i++) { + var buf2len = buffered2.length; + if (buf2len) { + var buf2end = buffered2[buf2len - 1].end; + // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative) + if (buffered[i].start - buf2end < maxHoleDuration) { + // merge overlapping time ranges + // update lastRange.end only if smaller than item.end + // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end) + // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15]) + if (buffered[i].end > buf2end) { + buffered2[buf2len - 1].end = buffered[i].end; + } + } else { + // big hole + buffered2.push(buffered[i]); + } + } else { + // first value + buffered2.push(buffered[i]); + } + } + for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) { + var start = buffered2[i].start, + end = buffered2[i].end; + //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i)); + if (pos + maxHoleDuration >= start && pos < end) { + // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length + bufferStart = start; + bufferEnd = end; + bufferLen = bufferEnd - pos; + } else if (pos + maxHoleDuration < start) { + bufferStartNext = start; + break; + } + } + return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext }; + } +}; + +/* harmony default export */ var buffer_helper = (BufferHelper); +// EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 12 modules +var demuxer_inline = __webpack_require__(7); + +// EXTERNAL MODULE: ./node_modules/events/events.js +var events_events = __webpack_require__(5); +var events_default = /*#__PURE__*/__webpack_require__.n(events_events); + +// EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js +var webworkify_webpack = __webpack_require__(9); +var webworkify_webpack_default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack); + +// CONCATENATED MODULE: ./src/helper/mediasource-helper.js +/** + * MediaSource helper + */ + +function getMediaSource() { + if (typeof window !== 'undefined') { + return window.MediaSource || window.WebKitMediaSource; + } +} +// CONCATENATED MODULE: ./src/demux/demuxer.js +function demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + + + + + +var demuxer_MediaSource = getMediaSource(); + +var demuxer_Demuxer = function () { + function Demuxer(hls, id) { + demuxer__classCallCheck(this, Demuxer); + + this.hls = hls; + this.id = id; + // observer setup + var observer = this.observer = new events_default.a(); + var config = hls.config; + observer.trigger = function trigger(event) { + for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + data[_key - 1] = arguments[_key]; + } + + observer.emit.apply(observer, [event, event].concat(data)); + }; + + observer.off = function off(event) { + for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + data[_key2 - 1] = arguments[_key2]; + } + + observer.removeListener.apply(observer, [event].concat(data)); + }; + + var forwardMessage = function (ev, data) { + data = data || {}; + data.frag = this.frag; + data.id = this.id; + hls.trigger(ev, data); + }.bind(this); + + // forward events to main thread + observer.on(events["a" /* default */].FRAG_DECRYPTED, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSING_DATA, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSED, forwardMessage); + observer.on(events["a" /* default */].ERROR, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSING_METADATA, forwardMessage); + observer.on(events["a" /* default */].FRAG_PARSING_USERDATA, forwardMessage); + observer.on(events["a" /* default */].INIT_PTS_FOUND, forwardMessage); + + var typeSupported = { + mp4: demuxer_MediaSource.isTypeSupported('video/mp4'), + mpeg: demuxer_MediaSource.isTypeSupported('audio/mpeg'), + mp3: demuxer_MediaSource.isTypeSupported('audio/mp4; codecs="mp3"') + }; + // navigator.vendor is not always available in Web Worker + // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator + var vendor = navigator.vendor; + if (config.enableWorker && typeof Worker !== 'undefined') { + logger["b" /* logger */].log('demuxing in webworker'); + var w = void 0; + try { + w = this.w = webworkify_webpack_default()(/*require.resolve*/(10)); + this.onwmsg = this.onWorkerMessage.bind(this); + w.addEventListener('message', this.onwmsg); + w.onerror = function (event) { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } }); + }; + w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) }); + } catch (err) { + logger["b" /* logger */].error('error while initializing DemuxerWorker, fallback on DemuxerInline'); + if (w) { + // revoke the Object URL that was used to create demuxer worker, so as not to leak it + URL.revokeObjectURL(w.objectURL); + } + this.demuxer = new demuxer_inline["a" /* default */](observer, typeSupported, config, vendor); + this.w = undefined; + } + } else { + this.demuxer = new demuxer_inline["a" /* default */](observer, typeSupported, config, vendor); + } + } + + Demuxer.prototype.destroy = function destroy() { + var w = this.w; + if (w) { + w.removeEventListener('message', this.onwmsg); + w.terminate(); + this.w = null; + } else { + var demuxer = this.demuxer; + if (demuxer) { + demuxer.destroy(); + this.demuxer = null; + } + } + var observer = this.observer; + if (observer) { + observer.removeAllListeners(); + this.observer = null; + } + }; + + Demuxer.prototype.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) { + var w = this.w; + var timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start; + var decryptdata = frag.decryptdata; + var lastFrag = this.frag; + var discontinuity = !(lastFrag && frag.cc === lastFrag.cc); + var trackSwitch = !(lastFrag && frag.level === lastFrag.level); + var nextSN = lastFrag && frag.sn === lastFrag.sn + 1; + var contiguous = !trackSwitch && nextSN; + if (discontinuity) { + logger["b" /* logger */].log(this.id + ':discontinuity detected'); + } + if (trackSwitch) { + logger["b" /* logger */].log(this.id + ':switch detected'); + } + this.frag = frag; + if (w) { + // post fragment payload as transferable objects for ArrayBuffer (no copy) + w.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, initSegment: initSegment, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, discontinuity: discontinuity, trackSwitch: trackSwitch, contiguous: contiguous, duration: duration, accurateTimeOffset: accurateTimeOffset, defaultInitPTS: defaultInitPTS }, data instanceof ArrayBuffer ? [data] : []); + } else { + var demuxer = this.demuxer; + if (demuxer) { + demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS); + } + } + }; + + Demuxer.prototype.onWorkerMessage = function onWorkerMessage(ev) { + var data = ev.data, + hls = this.hls; + //console.log('onWorkerMessage:' + data.event); + switch (data.event) { + case 'init': + // revoke the Object URL that was used to create demuxer worker, so as not to leak it + URL.revokeObjectURL(this.w.objectURL); + break; + // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects + case events["a" /* default */].FRAG_PARSING_DATA: + data.data.data1 = new Uint8Array(data.data1); + if (data.data2) { + data.data.data2 = new Uint8Array(data.data2); + } + /* falls through */ + default: + data.data = data.data || {}; + data.data.frag = this.frag; + data.data.id = this.id; + hls.trigger(data.event, data.data); + break; + } + }; + + return Demuxer; +}(); + +/* harmony default export */ var demux_demuxer = (demuxer_Demuxer); +// CONCATENATED MODULE: ./src/helper/level-helper.js +/** + * Level Helper class, providing methods dealing with playlist sliding and drift +*/ + + + +function updatePTS(fragments, fromIdx, toIdx) { + var fragFrom = fragments[fromIdx], + fragTo = fragments[toIdx], + fragToPTS = fragTo.startPTS; + // if we know startPTS[toIdx] + if (!isNaN(fragToPTS)) { + // update fragment duration. + // it helps to fix drifts between playlist reported duration and fragment real duration + if (toIdx > fromIdx) { + fragFrom.duration = fragToPTS - fragFrom.start; + if (fragFrom.duration < 0) { + logger["b" /* logger */].warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!'); + } + } else { + fragTo.duration = fragFrom.start - fragToPTS; + if (fragTo.duration < 0) { + logger["b" /* logger */].warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!'); + } + } + } else { + // we dont know startPTS[toIdx] + if (toIdx > fromIdx) { + fragTo.start = fragFrom.start + fragFrom.duration; + } else { + fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0); + } + } +} + +function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) { + // update frag PTS/DTS + var maxStartPTS = startPTS; + if (!isNaN(frag.startPTS)) { + // delta PTS between audio and video + var deltaPTS = Math.abs(frag.startPTS - startPTS); + if (isNaN(frag.deltaPTS)) { + frag.deltaPTS = deltaPTS; + } else { + frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS); + } + maxStartPTS = Math.max(startPTS, frag.startPTS); + startPTS = Math.min(startPTS, frag.startPTS); + endPTS = Math.max(endPTS, frag.endPTS); + startDTS = Math.min(startDTS, frag.startDTS); + endDTS = Math.max(endDTS, frag.endDTS); + } + + var drift = startPTS - frag.start; + frag.start = frag.startPTS = startPTS; + frag.maxStartPTS = maxStartPTS; + frag.endPTS = endPTS; + frag.startDTS = startDTS; + frag.endDTS = endDTS; + frag.duration = endPTS - startPTS; + + var sn = frag.sn; + // exit if sn out of range + if (!details || sn < details.startSN || sn > details.endSN) { + return 0; + } + var fragIdx, fragments, i; + fragIdx = sn - details.startSN; + fragments = details.fragments; + // update frag reference in fragments array + // rationale is that fragments array might not contain this frag object. + // this will happpen if playlist has been refreshed between frag loading and call to updateFragPTSDTS() + // if we don't update frag, we won't be able to propagate PTS info on the playlist + // resulting in invalid sliding computation + fragments[fragIdx] = frag; + // adjust fragment PTS/duration from seqnum-1 to frag 0 + for (i = fragIdx; i > 0; i--) { + updatePTS(fragments, i, i - 1); + } + + // adjust fragment PTS/duration from seqnum to last frag + for (i = fragIdx; i < fragments.length - 1; i++) { + updatePTS(fragments, i, i + 1); + } + details.PTSKnown = true; + //logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`); + + return drift; +} + +function mergeDetails(oldDetails, newDetails) { + var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN, + end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN, + delta = newDetails.startSN - oldDetails.startSN, + oldfragments = oldDetails.fragments, + newfragments = newDetails.fragments, + ccOffset = 0, + PTSFrag; + + // check if old/new playlists have fragments in common + if (end < start) { + newDetails.PTSKnown = false; + return; + } + // loop through overlapping SN and update startPTS , cc, and duration if any found + for (var i = start; i <= end; i++) { + var oldFrag = oldfragments[delta + i], + newFrag = newfragments[i]; + if (newFrag && oldFrag) { + ccOffset = oldFrag.cc - newFrag.cc; + if (!isNaN(oldFrag.startPTS)) { + newFrag.start = newFrag.startPTS = oldFrag.startPTS; + newFrag.endPTS = oldFrag.endPTS; + newFrag.duration = oldFrag.duration; + newFrag.backtracked = oldFrag.backtracked; + newFrag.dropped = oldFrag.dropped; + PTSFrag = newFrag; + } + } + } + + if (ccOffset) { + logger["b" /* logger */].log('discontinuity sliding from playlist, take drift into account'); + for (i = 0; i < newfragments.length; i++) { + newfragments[i].cc += ccOffset; + } + } + + // if at least one fragment contains PTS info, recompute PTS information for all fragments + if (PTSFrag) { + updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS); + } else { + // ensure that delta is within oldfragments range + // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61]) + // in that case we also need to adjust start offset of all fragments + if (delta >= 0 && delta < oldfragments.length) { + // adjust start by sliding offset + var sliding = oldfragments[delta].start; + for (i = 0; i < newfragments.length; i++) { + newfragments[i].start += sliding; + } + } + } + // if we are here, it means we have fragments overlapping between + // old and new level. reliable PTS info is thus relying on old level + newDetails.PTSKnown = oldDetails.PTSKnown; +} +// CONCATENATED MODULE: ./src/utils/timeRanges.js +/** + * TimeRanges to string helper + */ + +var TimeRanges = { + toString: function toString(r) { + var log = '', + len = r.length; + for (var i = 0; i < len; i++) { + log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']'; + } + return log; + } +}; + +/* harmony default export */ var timeRanges = (TimeRanges); +// CONCATENATED MODULE: ./src/utils/discontinuities.js + + + +function findFirstFragWithCC(fragments, cc) { + var firstFrag = null; + + for (var i = 0; i < fragments.length; i += 1) { + var currentFrag = fragments[i]; + if (currentFrag && currentFrag.cc === cc) { + firstFrag = currentFrag; + break; + } + } + + return firstFrag; +} + +function findFragWithCC(fragments, CC) { + return binary_search.search(fragments, function (candidate) { + if (candidate.cc < CC) { + return 1; + } else if (candidate.cc > CC) { + return -1; + } else { + return 0; + } + }); +} + +function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) { + var shouldAlign = false; + if (lastLevel && lastLevel.details && details) { + if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) { + shouldAlign = true; + } + } + return shouldAlign; +} + +// Find the first frag in the previous level which matches the CC of the first frag of the new level +function findDiscontinuousReferenceFrag(prevDetails, curDetails) { + var prevFrags = prevDetails.fragments; + var curFrags = curDetails.fragments; + + if (!curFrags.length || !prevFrags.length) { + logger["b" /* logger */].log('No fragments to align'); + return; + } + + var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc); + + if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) { + logger["b" /* logger */].log('No frag in previous level to align on'); + return; + } + + return prevStartFrag; +} + +function adjustPts(sliding, details) { + details.fragments.forEach(function (frag) { + if (frag) { + var start = frag.start + sliding; + frag.start = frag.startPTS = start; + frag.endPTS = start + frag.duration; + } + }); + details.PTSKnown = true; +} + +// If a change in CC is detected, the PTS can no longer be relied upon +// Attempt to align the level by using the last level - find the last frag matching the current CC and use it's PTS +// as a reference +function alignDiscontinuities(lastFrag, lastLevel, details) { + if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) { + var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details); + if (referenceFrag) { + logger["b" /* logger */].log('Adjusting PTS using last level due to CC increase within current level'); + adjustPts(referenceFrag.start, details); + } + } + // try to align using programDateTime attribute (if available) + if (details.PTSKnown === false && lastLevel && lastLevel.details) { + // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM + // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM + // then we can deduce that playlist B sliding is 1000+8 = 1008s + var lastPDT = lastLevel.details.programDateTime; + var newPDT = details.programDateTime; + // date diff is in ms. frag.start is in seconds + var sliding = (newPDT - lastPDT) / 1000 + lastLevel.details.fragments[0].start; + if (!isNaN(sliding)) { + logger["b" /* logger */].log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3)); + adjustPts(sliding, details); + } + } +} +// CONCATENATED MODULE: ./src/controller/stream-controller.js +var stream_controller__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; }; }(); + +function stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function stream_controller__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; } + +function stream_controller__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; } + +/* + * Stream Controller +*/ + + + + + + + + + + + +var State = { + STOPPED: 'STOPPED', + IDLE: 'IDLE', + KEY_LOADING: 'KEY_LOADING', + FRAG_LOADING: 'FRAG_LOADING', + FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY', + WAITING_LEVEL: 'WAITING_LEVEL', + PARSING: 'PARSING', + PARSED: 'PARSED', + BUFFER_FLUSHING: 'BUFFER_FLUSHING', + ENDED: 'ENDED', + ERROR: 'ERROR' +}; + +var stream_controller_StreamController = function (_EventHandler) { + stream_controller__inherits(StreamController, _EventHandler); + + function StreamController(hls) { + stream_controller__classCallCheck(this, StreamController); + + var _this = stream_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, events["a" /* default */].FRAG_PARSING_DATA, events["a" /* default */].FRAG_PARSED, events["a" /* default */].ERROR, events["a" /* default */].AUDIO_TRACK_SWITCHING, events["a" /* default */].AUDIO_TRACK_SWITCHED, events["a" /* default */].BUFFER_CREATED, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].BUFFER_FLUSHED)); + + _this.config = hls.config; + _this.audioCodecSwap = false; + _this.ticks = 0; + _this._state = State.STOPPED; + _this.ontick = _this.tick.bind(_this); + return _this; + } + + StreamController.prototype.destroy = function destroy() { + this.stopLoad(); + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + event_handler.prototype.destroy.call(this); + this.state = State.STOPPED; + }; + + StreamController.prototype.startLoad = function startLoad(startPosition) { + if (this.levels) { + var lastCurrentTime = this.lastCurrentTime, + hls = this.hls; + this.stopLoad(); + if (!this.timer) { + this.timer = setInterval(this.ontick, 100); + } + this.level = -1; + this.fragLoadError = 0; + if (!this.startFragRequested) { + // determine load level + var startLevel = hls.startLevel; + if (startLevel === -1) { + // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level + startLevel = 0; + this.bitrateTest = true; + } + // set new level to playlist loader : this will trigger start level load + // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded + this.level = hls.nextLoadLevel = startLevel; + this.loadedmetadata = false; + } + // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime + if (lastCurrentTime > 0 && startPosition === -1) { + logger["b" /* logger */].log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3)); + startPosition = lastCurrentTime; + } + this.state = State.IDLE; + this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition; + this.tick(); + } else { + this.forceStartLoad = true; + this.state = State.STOPPED; + } + }; + + StreamController.prototype.stopLoad = function stopLoad() { + var frag = this.fragCurrent; + if (frag) { + if (frag.loader) { + frag.loader.abort(); + } + this.fragCurrent = null; + } + this.fragPrevious = null; + if (this.demuxer) { + this.demuxer.destroy(); + this.demuxer = null; + } + this.state = State.STOPPED; + this.forceStartLoad = false; + }; + + StreamController.prototype.tick = function tick() { + this.ticks++; + if (this.ticks === 1) { + this.doTick(); + if (this.ticks > 1) { + setTimeout(this.tick, 1); + } + this.ticks = 0; + } + }; + + StreamController.prototype.doTick = function doTick() { + switch (this.state) { + case State.ERROR: + //don't do anything in error state to avoid breaking further ... + break; + case State.BUFFER_FLUSHING: + // in buffer flushing state, reset fragLoadError counter + this.fragLoadError = 0; + break; + case State.IDLE: + this._doTickIdle(); + break; + case State.WAITING_LEVEL: + var level = this.levels[this.level]; + // check if playlist is already loaded + if (level && level.details) { + this.state = State.IDLE; + } + break; + case State.FRAG_LOADING_WAITING_RETRY: + var now = performance.now(); + var retryDate = this.retryDate; + // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading + if (!retryDate || now >= retryDate || this.media && this.media.seeking) { + logger["b" /* logger */].log('mediaController: retryDate reached, switch back to IDLE state'); + this.state = State.IDLE; + } + break; + case State.ERROR: + case State.STOPPED: + case State.FRAG_LOADING: + case State.PARSING: + case State.PARSED: + case State.ENDED: + break; + default: + break; + } + // check buffer + this._checkBuffer(); + // check/update current fragment + this._checkFragmentChanged(); + }; + + // Ironically the "idle" state is the on we do the most logic in it seems .... + // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently + // played segment, or on pause/play/seek instead of naively checking every 100ms? + + + StreamController.prototype._doTickIdle = function _doTickIdle() { + var hls = this.hls, + config = hls.config, + media = this.media; + + // if start level not parsed yet OR + // if video not attached AND start fragment already requested OR start frag prefetch disable + // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment + if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) { + return; + } + + // if we have not yet loaded any fragment, start loading from start position + var pos = void 0; + if (this.loadedmetadata) { + pos = media.currentTime; + } else { + pos = this.nextLoadPosition; + } + // determine next load level + var level = hls.nextLoadLevel, + levelInfo = this.levels[level]; + + if (!levelInfo) { + return; + } + + var levelBitrate = levelInfo.bitrate, + maxBufLen = void 0; + + // 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 + if (levelBitrate) { + maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength); + } else { + maxBufLen = config.maxBufferLength; + } + maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength); + + // determine next candidate fragment to be loaded, based on current position and end of buffer position + // ensure up to `config.maxMaxBufferLength` of buffer upfront + + var bufferInfo = buffer_helper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole), + bufferLen = bufferInfo.len; + // Stay idle if we are still with buffer margins + if (bufferLen >= maxBufLen) { + return; + } + + // if buffer length is less than maxBufLen try to load a new fragment ... + logger["b" /* logger */].trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...'); + + // set next load level : this will trigger a playlist load if needed + this.level = hls.nextLoadLevel = level; + + var levelDetails = levelInfo.details; + // if level info not retrieved yet, switch state and wait for level retrieval + // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load + // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist) + if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) { + this.state = State.WAITING_LEVEL; + return; + } + + // we just got done loading the final fragment and there is no other buffered range after ... + // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between + // so we should not switch to ENDED in that case, to be able to buffer them + // dont switch to ENDED if we need to backtrack last fragment + var fragPrevious = this.fragPrevious; + if (!levelDetails.live && fragPrevious && !fragPrevious.backtracked && fragPrevious.sn === levelDetails.endSN && !bufferInfo.nextStart) { + // fragPrevious is last fragment. retrieve level duration using last frag start offset + duration + // real duration might be lower than initial duration if there are drifts between real frag duration and playlist signaling + var duration = Math.min(media.duration, fragPrevious.start + fragPrevious.duration); + // if everything (almost) til the end is buffered, let's signal eos + // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference (audio/video offsets...) + // tolerate up to one frag duration to cope with these cases. + // also cope with almost zero last frag duration (max last frag duration with 200ms) refer to https://github.com/video-dev/hls.js/pull/657 + if (duration - Math.max(bufferInfo.end, fragPrevious.start) <= Math.max(0.2, fragPrevious.duration)) { + // Finalize the media stream + var data = {}; + if (this.altAudio) { + data.type = 'video'; + } + this.hls.trigger(events["a" /* default */].BUFFER_EOS, data); + this.state = State.ENDED; + return; + } + } + + // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..) + this._fetchPayloadOrEos(pos, bufferInfo, levelDetails); + }; + + StreamController.prototype._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) { + var fragPrevious = this.fragPrevious, + level = this.level, + fragments = levelDetails.fragments, + fragLen = fragments.length; + + // empty playlist + if (fragLen === 0) { + return; + } + + // find fragment index, contiguous with end of buffer position + var start = fragments[0].start, + end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration, + bufferEnd = bufferInfo.end, + frag = void 0; + + if (levelDetails.initSegment && !levelDetails.initSegment.data) { + frag = levelDetails.initSegment; + } else { + // in case of live playlist we need to ensure that requested position is not located before playlist start + if (levelDetails.live) { + var initialLiveManifestSize = this.config.initialLiveManifestSize; + if (fragLen < initialLiveManifestSize) { + logger["b" /* logger */].warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize); + return; + } + + frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen); + // if it explicitely returns null don't load any fragment and exit function now + if (frag === null) { + return; + } + } else { + // VoD playlist: if bufferEnd before start of playlist, load first fragment + if (bufferEnd < start) { + frag = fragments[0]; + } + } + } + if (!frag) { + frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails); + } + if (frag) { + this._loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd); + } + return; + }; + + StreamController.prototype._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) { + var config = this.hls.config, + media = this.media; + + var frag = void 0; + + // check if requested position is within seekable boundaries : + //logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`); + var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration; + + if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) { + var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails); + logger["b" /* logger */].log('buffer end: ' + bufferEnd.toFixed(3) + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3)); + bufferEnd = liveSyncPosition; + if (media && media.readyState && media.duration > liveSyncPosition) { + media.currentTime = liveSyncPosition; + } + this.nextLoadPosition = liveSyncPosition; + } + + // if end of buffer greater than live edge, don't load any fragment + // this could happen if live playlist intermittently slides in the past. + // level 1 loaded [182580161,182580167] + // level 1 loaded [182580162,182580169] + // Loading 182580168 of [182580162 ,182580169],level 1 .. + // Loading 182580169 of [182580162 ,182580169],level 1 .. + // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168 + // level 1 loaded [182580164,182580171] + // + // don't return null in case media not loaded yet (readystate === 0) + if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) { + return null; + } + + if (this.startFragRequested && !levelDetails.PTSKnown) { + /* we are switching level on live playlist, but we don't have any PTS info for that quality level ... + try to load frag matching with next SN. + even if SN are not synchronized between playlists, loading this frag will help us + compute playlist sliding and find the right one after in case it was not the right consecutive one */ + if (fragPrevious) { + var targetSN = fragPrevious.sn + 1; + if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) { + var fragNext = fragments[targetSN - levelDetails.startSN]; + if (fragPrevious.cc === fragNext.cc) { + frag = fragNext; + logger["b" /* logger */].log('live playlist, switching playlist, load frag with next SN: ' + frag.sn); + } + } + // next frag SN not available (or not with same continuity counter) + // look for a frag sharing the same CC + if (!frag) { + frag = binary_search.search(fragments, function (frag) { + return fragPrevious.cc - frag.cc; + }); + if (frag) { + logger["b" /* logger */].log('live playlist, switching playlist, load frag with same CC: ' + frag.sn); + } + } + } + if (!frag) { + /* we have no idea about which fragment should be loaded. + so let's load mid fragment. it will help computing playlist sliding and find the right one + */ + frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))]; + logger["b" /* logger */].log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn); + } + } + return frag; + }; + + StreamController.prototype._findFragment = function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) { + var config = this.hls.config; + var frag = void 0; + var foundFrag = void 0; + var maxFragLookUpTolerance = config.maxFragLookUpTolerance; + var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined; + var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) { + // offset should be within fragment boundary - config.maxFragLookUpTolerance + // this is to cope with situations like + // bufferEnd = 9.991 + // frag[Ø] : [0,10] + // frag[1] : [10,20] + // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here + // frag start frag start+duration + // |-----------------------------| + // <---> <---> + // ...--------><-----------------------------><---------.... + // previous frag matching fragment next frag + // return -1 return 0 return 1 + //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`); + // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments + var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)); + if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) { + return 1; + } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element + else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { + return -1; + } + return 0; + }; + + if (bufferEnd < end) { + if (bufferEnd > end - maxFragLookUpTolerance) { + maxFragLookUpTolerance = 0; + } + // Prefer the next fragment if it's within tolerance + if (fragNext && !fragmentWithinToleranceTest(fragNext)) { + foundFrag = fragNext; + } else { + foundFrag = binary_search.search(fragments, fragmentWithinToleranceTest); + } + } else { + // reach end of playlist + foundFrag = fragments[fragLen - 1]; + } + if (foundFrag) { + frag = foundFrag; + var curSNIdx = frag.sn - levelDetails.startSN; + var sameLevel = fragPrevious && frag.level === fragPrevious.level; + var prevFrag = fragments[curSNIdx - 1]; + var nextFrag = fragments[curSNIdx + 1]; + //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn); + if (fragPrevious && frag.sn === fragPrevious.sn) { + if (sameLevel && !frag.backtracked) { + if (frag.sn < levelDetails.endSN) { + var deltaPTS = fragPrevious.deltaPTS; + // if there is a significant delta between audio and video, larger than max allowed hole, + // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped) + // let's try to load previous fragment again to get last keyframe + // then we will reload again current fragment (that way we should be able to fill the buffer hole ...) + if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) { + frag = prevFrag; + logger["b" /* logger */].warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this'); + // decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded + fragPrevious.loadCounter--; + } else { + frag = nextFrag; + logger["b" /* logger */].log('SN just loaded, load next one: ' + frag.sn); + } + } else { + frag = null; + } + } else if (frag.backtracked) { + // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes + if (nextFrag && nextFrag.backtracked) { + logger["b" /* logger */].warn('Already backtracked from fragment ' + nextFrag.sn + ', will not backtrack to fragment ' + frag.sn + '. Loading fragment ' + nextFrag.sn); + frag = nextFrag; + } else { + // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe + // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment + logger["b" /* logger */].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe'); + frag.dropped = 0; + if (prevFrag) { + if (prevFrag.loadCounter) { + prevFrag.loadCounter--; + } + frag = prevFrag; + frag.backtracked = true; + } else if (curSNIdx) { + // can't backtrack on very first fragment + frag = null; + } + } + } + } + } + return frag; + }; + + StreamController.prototype._loadFragmentOrKey = function _loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd) { + var hls = this.hls, + config = hls.config; + + //logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3)); + if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) { + logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level); + this.state = State.KEY_LOADING; + hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag }); + } else { + logger["b" /* logger */].log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3)); + // ensure that we are not reloading the same fragments in loop ... + if (this.fragLoadIdx !== undefined) { + this.fragLoadIdx++; + } else { + this.fragLoadIdx = 0; + } + if (frag.loadCounter) { + frag.loadCounter++; + var maxThreshold = config.fragLoadingLoopThreshold; + // if this frag has already been loaded 3 times, and if it has been reloaded recently + if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag }); + return; + } + } else { + frag.loadCounter = 1; + } + frag.loadIdx = this.fragLoadIdx; + frag.autoLevel = hls.autoLevelEnabled; + frag.bitrateTest = this.bitrateTest; + + this.fragCurrent = frag; + this.startFragRequested = true; + // Don't update nextLoadPosition for fragments which are not buffered + if (!isNaN(frag.sn) && !frag.bitrateTest) { + this.nextLoadPosition = frag.start + frag.duration; + } + hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag }); + // lazy demuxer init, as this could take some time ... do it during frag loading + if (!this.demuxer) { + this.demuxer = new demux_demuxer(hls, 'main'); + } + this.state = State.FRAG_LOADING; + return; + } + }; + + StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) { + return binary_search.search(this._bufferedFrags, function (frag) { + if (position < frag.startPTS) { + return -1; + } else if (position > frag.endPTS) { + return 1; + } + return 0; + }); + }; + + StreamController.prototype.followingBufferedFrag = function followingBufferedFrag(frag) { + if (frag) { + // try to get range of next fragment (500ms after this range) + return this.getBufferedFrag(frag.endPTS + 0.5); + } + return null; + }; + + StreamController.prototype._checkFragmentChanged = function _checkFragmentChanged() { + var fragPlayingCurrent, + currentTime, + video = this.media; + if (video && video.readyState && video.seeking === false) { + currentTime = video.currentTime; + /* if video element is in seeked state, currentTime can only increase. + (assuming that playback rate is positive ...) + As sometimes currentTime jumps back to zero after a + media decode error, check this, to avoid seeking back to + wrong position after a media decode error + */ + if (currentTime > video.playbackRate * this.lastCurrentTime) { + this.lastCurrentTime = currentTime; + } + if (buffer_helper.isBuffered(video, currentTime)) { + fragPlayingCurrent = this.getBufferedFrag(currentTime); + } else if (buffer_helper.isBuffered(video, currentTime + 0.1)) { + /* ensure that FRAG_CHANGED event is triggered at startup, + when first video frame is displayed and playback is paused. + add a tolerance of 100ms, in case current position is not buffered, + check if current pos+100ms is buffered and use that buffer range + for FRAG_CHANGED event reporting */ + fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1); + } + if (fragPlayingCurrent) { + var fragPlaying = fragPlayingCurrent; + if (fragPlaying !== this.fragPlaying) { + this.hls.trigger(events["a" /* default */].FRAG_CHANGED, { frag: fragPlaying }); + var fragPlayingLevel = fragPlaying.level; + if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) { + this.hls.trigger(events["a" /* default */].LEVEL_SWITCHED, { level: fragPlayingLevel }); + } + this.fragPlaying = fragPlaying; + } + } + } + }; + + /* + on immediate level switch : + - pause playback if playing + - cancel any pending load request + - and trigger a buffer flush + */ + + + StreamController.prototype.immediateLevelSwitch = function immediateLevelSwitch() { + logger["b" /* logger */].log('immediateLevelSwitch'); + if (!this.immediateSwitch) { + this.immediateSwitch = true; + var media = this.media, + previouslyPaused = void 0; + if (media) { + previouslyPaused = media.paused; + media.pause(); + } else { + // don't restart playback after instant level switch in case media not attached + previouslyPaused = true; + } + this.previouslyPaused = previouslyPaused; + } + var fragCurrent = this.fragCurrent; + if (fragCurrent && fragCurrent.loader) { + fragCurrent.loader.abort(); + } + this.fragCurrent = null; + // increase fragment load Index to avoid frag loop loading error after buffer flush + if (this.fragLoadIdx !== undefined) { + this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; + } + // flush everything + this.flushMainBuffer(0, Number.POSITIVE_INFINITY); + }; + + /* + on immediate level switch end, after new fragment has been buffered : + - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered) + - resume the playback if needed + */ + + + StreamController.prototype.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() { + var media = this.media; + if (media && media.buffered.length) { + this.immediateSwitch = false; + if (buffer_helper.isBuffered(media, media.currentTime)) { + // only nudge if currentTime is buffered + media.currentTime -= 0.0001; + } + if (!this.previouslyPaused) { + media.play(); + } + } + }; + + StreamController.prototype.nextLevelSwitch = function nextLevelSwitch() { + /* try to switch ASAP without breaking video playback : + in order to ensure smooth but quick level switching, + we need to find the next flushable buffer range + we should take into account new segment fetch time + */ + var media = this.media; + // ensure that media is defined and that metadata are available (to retrieve currentTime) + if (media && media.readyState) { + var fetchdelay = void 0, + fragPlayingCurrent = void 0, + nextBufferedFrag = void 0; + if (this.fragLoadIdx !== undefined) { + // increase fragment load Index to avoid frag loop loading error after buffer flush + this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; + } + fragPlayingCurrent = this.getBufferedFrag(media.currentTime); + if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) { + // flush buffer preceding current fragment (flush until current fragment start offset) + // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ... + this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1); + } + if (!media.paused) { + // add a safety delay of 1s + var nextLevelId = this.hls.nextLoadLevel, + nextLevel = this.levels[nextLevelId], + fragLastKbps = this.fragLastKbps; + if (fragLastKbps && this.fragCurrent) { + fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1; + } else { + fetchdelay = 0; + } + } else { + fetchdelay = 0; + } + //logger.log('fetchdelay:'+fetchdelay); + // find buffer range that will be reached once new fragment will be fetched + nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay); + if (nextBufferedFrag) { + // we can flush buffer range following this one without stalling playback + nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag); + if (nextBufferedFrag) { + // if we are here, we can also cancel any loading/demuxing in progress, as they are useless + var fragCurrent = this.fragCurrent; + if (fragCurrent && fragCurrent.loader) { + fragCurrent.loader.abort(); + } + this.fragCurrent = null; + // start flush position is the start PTS of next buffered frag. + // we use frag.naxStartPTS which is max(audio startPTS, video startPTS). + // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment + this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY); + } + } + } + }; + + StreamController.prototype.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) { + this.state = State.BUFFER_FLUSHING; + var flushScope = { startOffset: startOffset, endOffset: endOffset }; + // if alternate audio tracks are used, only flush video, otherwise flush everything + if (this.altAudio) { + flushScope.type = 'video'; + } + this.hls.trigger(events["a" /* default */].BUFFER_FLUSHING, flushScope); + }; + + StreamController.prototype.onMediaAttached = function onMediaAttached(data) { + var media = this.media = this.mediaBuffer = data.media; + this.onvseeking = this.onMediaSeeking.bind(this); + this.onvseeked = this.onMediaSeeked.bind(this); + this.onvended = this.onMediaEnded.bind(this); + media.addEventListener('seeking', this.onvseeking); + media.addEventListener('seeked', this.onvseeked); + media.addEventListener('ended', this.onvended); + var config = this.config; + if (this.levels && config.autoStartLoad) { + this.hls.startLoad(config.startPosition); + } + }; + + StreamController.prototype.onMediaDetaching = function onMediaDetaching() { + var media = this.media; + if (media && media.ended) { + logger["b" /* logger */].log('MSE detaching and video ended, reset startPosition'); + this.startPosition = this.lastCurrentTime = 0; + } + + // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery + var levels = this.levels; + if (levels) { + // reset fragment load counter + levels.forEach(function (level) { + if (level.details) { + level.details.fragments.forEach(function (fragment) { + fragment.loadCounter = undefined; + fragment.backtracked = undefined; + }); + } + }); + } + // remove video listeners + if (media) { + media.removeEventListener('seeking', this.onvseeking); + media.removeEventListener('seeked', this.onvseeked); + media.removeEventListener('ended', this.onvended); + this.onvseeking = this.onvseeked = this.onvended = null; + } + this.media = this.mediaBuffer = null; + this.loadedmetadata = false; + this.stopLoad(); + }; + + StreamController.prototype.onMediaSeeking = function onMediaSeeking() { + var media = this.media, + currentTime = media ? media.currentTime : undefined, + config = this.config; + if (!isNaN(currentTime)) { + logger["b" /* logger */].log('media seeking to ' + currentTime.toFixed(3)); + } + var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media; + var bufferInfo = buffer_helper.bufferInfo(mediaBuffer, currentTime, this.config.maxBufferHole); + if (this.state === State.FRAG_LOADING) { + var fragCurrent = this.fragCurrent; + // check if we are seeking to a unbuffered area AND if frag loading is in progress + if (bufferInfo.len === 0 && fragCurrent) { + var tolerance = config.maxFragLookUpTolerance, + fragStartOffset = fragCurrent.start - tolerance, + fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; + // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything + if (currentTime < fragStartOffset || currentTime > fragEndOffset) { + if (fragCurrent.loader) { + logger["b" /* logger */].log('seeking outside of buffer while fragment load in progress, cancel fragment load'); + fragCurrent.loader.abort(); + } + this.fragCurrent = null; + this.fragPrevious = null; + // switch to IDLE state to load new fragment + this.state = State.IDLE; + } else { + logger["b" /* logger */].log('seeking outside of buffer but within currently loaded fragment range'); + } + } + } else if (this.state === State.ENDED) { + // if seeking to unbuffered area, clean up fragPrevious + if (bufferInfo.len === 0) { + this.fragPrevious = 0; + } + // switch to IDLE state to check for potential new fragment + this.state = State.IDLE; + } + if (media) { + this.lastCurrentTime = currentTime; + } + // avoid reporting fragment loop loading error in case user is seeking several times on same position + if (this.state !== State.FRAG_LOADING && this.fragLoadIdx !== undefined) { + this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold; + } + // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target + if (!this.loadedmetadata) { + this.nextLoadPosition = this.startPosition = currentTime; + } + // tick to speed up processing + this.tick(); + }; + + StreamController.prototype.onMediaSeeked = function onMediaSeeked() { + var media = this.media, + currentTime = media ? media.currentTime : undefined; + if (!isNaN(currentTime)) { + logger["b" /* logger */].log('media seeked to ' + currentTime.toFixed(3)); + } + // tick to speed up FRAGMENT_PLAYING triggering + this.tick(); + }; + + StreamController.prototype.onMediaEnded = function onMediaEnded() { + logger["b" /* logger */].log('media ended'); + // reset startPosition and lastCurrentTime to restart playback @ stream beginning + this.startPosition = this.lastCurrentTime = 0; + }; + + StreamController.prototype.onManifestLoading = function onManifestLoading() { + // reset buffer on manifest loading + logger["b" /* logger */].log('trigger BUFFER_RESET'); + this.hls.trigger(events["a" /* default */].BUFFER_RESET); + this._bufferedFrags = []; + this.stalled = false; + this.startPosition = this.lastCurrentTime = 0; + }; + + StreamController.prototype.onManifestParsed = function onManifestParsed(data) { + var aac = false, + heaac = false, + codec; + data.levels.forEach(function (level) { + // detect if we have different kind of audio codecs used amongst playlists + codec = level.audioCodec; + if (codec) { + if (codec.indexOf('mp4a.40.2') !== -1) { + aac = true; + } + if (codec.indexOf('mp4a.40.5') !== -1) { + heaac = true; + } + } + }); + this.audioCodecSwitch = aac && heaac; + if (this.audioCodecSwitch) { + logger["b" /* logger */].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'); + } + this.levels = data.levels; + this.startFragRequested = false; + var config = this.config; + if (config.autoStartLoad || this.forceStartLoad) { + this.hls.startLoad(config.startPosition); + } + }; + + StreamController.prototype.onLevelLoaded = function onLevelLoaded(data) { + var newDetails = data.details; + var newLevelId = data.level; + var lastLevel = this.levels[this.levelLastLoaded]; + var curLevel = this.levels[newLevelId]; + var duration = newDetails.totalduration; + var sliding = 0; + + logger["b" /* logger */].log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration); + + if (newDetails.live) { + var curDetails = curLevel.details; + if (curDetails && newDetails.fragments.length > 0) { + // we already have details for that level, merge them + mergeDetails(curDetails, newDetails); + sliding = newDetails.fragments[0].start; + this.liveSyncPosition = this.computeLivePosition(sliding, curDetails); + if (newDetails.PTSKnown && !isNaN(sliding)) { + logger["b" /* logger */].log('live playlist sliding:' + sliding.toFixed(3)); + } else { + logger["b" /* logger */].log('live playlist - outdated PTS, unknown sliding'); + alignDiscontinuities(this.fragPrevious, lastLevel, newDetails); + } + } else { + logger["b" /* logger */].log('live playlist - first load, unknown sliding'); + newDetails.PTSKnown = false; + alignDiscontinuities(this.fragPrevious, lastLevel, newDetails); + } + } else { + newDetails.PTSKnown = false; + } + // override level info + curLevel.details = newDetails; + this.levelLastLoaded = newLevelId; + this.hls.trigger(events["a" /* default */].LEVEL_UPDATED, { details: newDetails, level: newLevelId }); + + if (this.startFragRequested === false) { + // compute start position if set to -1. use it straight away if value is defined + if (this.startPosition === -1 || this.lastCurrentTime === -1) { + // first, check if start time offset has been set in playlist, if yes, use this value + var startTimeOffset = newDetails.startTimeOffset; + if (!isNaN(startTimeOffset)) { + if (startTimeOffset < 0) { + logger["b" /* logger */].log('negative start time offset ' + startTimeOffset + ', count from end of last fragment'); + startTimeOffset = sliding + duration + startTimeOffset; + } + logger["b" /* logger */].log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset); + this.startPosition = startTimeOffset; + } else { + // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3) + if (newDetails.live) { + this.startPosition = this.computeLivePosition(sliding, newDetails); + logger["b" /* logger */].log('configure startPosition to ' + this.startPosition); + } else { + this.startPosition = 0; + } + } + this.lastCurrentTime = this.startPosition; + } + this.nextLoadPosition = this.startPosition; + } + // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment + if (this.state === State.WAITING_LEVEL) { + this.state = State.IDLE; + } + //trigger handler right now + this.tick(); + }; + + StreamController.prototype.onKeyLoaded = function onKeyLoaded() { + if (this.state === State.KEY_LOADING) { + this.state = State.IDLE; + this.tick(); + } + }; + + StreamController.prototype.onFragLoaded = function onFragLoaded(data) { + var fragCurrent = this.fragCurrent, + fragLoaded = data.frag; + if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) { + var stats = data.stats, + currentLevel = this.levels[fragCurrent.level], + details = currentLevel.details; + logger["b" /* logger */].log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level); + // reset frag bitrate test in any case after frag loaded event + this.bitrateTest = false; + this.stats = stats; + // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0 + // then this means that we should be able to load a fragment at a higher quality level + if (fragLoaded.bitrateTest === true && this.hls.nextLoadLevel) { + // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo + this.state = State.IDLE; + this.startFragRequested = false; + stats.tparsed = stats.tbuffered = performance.now(); + this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' }); + this.tick(); + } else if (fragLoaded.sn === 'initSegment') { + this.state = State.IDLE; + stats.tparsed = stats.tbuffered = performance.now(); + details.initSegment.data = data.payload; + this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' }); + this.tick(); + } else { + this.state = State.PARSING; + // transmux the MPEG-TS data to ISO-BMFF segments + var duration = details.totalduration, + level = fragCurrent.level, + sn = fragCurrent.sn, + audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec; + if (this.audioCodecSwap) { + logger["b" /* logger */].log('swapping playlist audio codec'); + if (audioCodec === undefined) { + audioCodec = this.lastAudioCodec; + } + if (audioCodec) { + if (audioCodec.indexOf('mp4a.40.5') !== -1) { + audioCodec = 'mp4a.40.2'; + } else { + audioCodec = 'mp4a.40.5'; + } + } + } + this.pendingBuffering = true; + this.appended = false; + logger["b" /* logger */].log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc); + var demuxer = this.demuxer; + if (!demuxer) { + demuxer = this.demuxer = new demux_demuxer(this.hls, 'main'); + } + // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments) + var media = this.media; + var mediaSeeking = media && media.seeking; + var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live); + var initSegmentData = details.initSegment ? details.initSegment.data : []; + demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, duration, accurateTimeOffset, undefined); + } + } + this.fragLoadError = 0; + }; + + StreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) { + var fragCurrent = this.fragCurrent; + var fragNew = data.frag; + if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) { + var tracks = data.tracks, + trackName, + track; + + // if audio track is expected to come from audio stream controller, discard any coming from main + if (tracks.audio && this.altAudio) { + delete tracks.audio; + } + // include levelCodec in audio and video tracks + track = tracks.audio; + if (track) { + var audioCodec = this.levels[this.level].audioCodec, + ua = navigator.userAgent.toLowerCase(); + if (audioCodec && this.audioCodecSwap) { + logger["b" /* logger */].log('swapping playlist audio codec'); + if (audioCodec.indexOf('mp4a.40.5') !== -1) { + audioCodec = 'mp4a.40.2'; + } else { + audioCodec = 'mp4a.40.5'; + } + } + // in case AAC and HE-AAC audio codecs are signalled in manifest + // force HE-AAC , as it seems that most browsers prefers that way, + // except for mono streams OR on FF + // these conditions might need to be reviewed ... + if (this.audioCodecSwitch) { + // don't force HE-AAC if mono stream + if (track.metadata.channelCount !== 1 && + // don't force HE-AAC if firefox + ua.indexOf('firefox') === -1) { + audioCodec = 'mp4a.40.5'; + } + } + // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise + if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { + // Exclude mpeg audio + audioCodec = 'mp4a.40.2'; + logger["b" /* logger */].log('Android: force audio codec to ' + audioCodec); + } + track.levelCodec = audioCodec; + track.id = data.id; + } + track = tracks.video; + if (track) { + track.levelCodec = this.levels[this.level].videoCodec; + track.id = data.id; + } + this.hls.trigger(events["a" /* default */].BUFFER_CODECS, tracks); + // loop through tracks that are going to be provided to bufferController + for (trackName in tracks) { + track = tracks[trackName]; + logger["b" /* logger */].log('main track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']'); + var initSegment = track.initSegment; + if (initSegment) { + this.appended = true; + // arm pending Buffering flag before appending a segment + this.pendingBuffering = true; + this.hls.trigger(events["a" /* default */].BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' }); + } + } + //trigger handler right now + this.tick(); + } + }; + + StreamController.prototype.onFragParsingData = function onFragParsingData(data) { + var _this2 = this; + + var fragCurrent = this.fragCurrent; + var fragNew = data.frag; + if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller + this.state === State.PARSING) { + var level = this.levels[this.level], + frag = fragCurrent; + if (isNaN(data.endPTS)) { + data.endPTS = data.startPTS + fragCurrent.duration; + data.endDTS = data.startDTS + fragCurrent.duration; + } + + logger["b" /* logger */].log('Parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb + ',dropped:' + (data.dropped || 0)); + + // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments) + if (data.type === 'video') { + frag.dropped = data.dropped; + if (frag.dropped) { + if (!frag.backtracked) { + var levelDetails = level.details; + if (levelDetails && frag.sn === levelDetails.startSN) { + logger["b" /* logger */].warn('missing video frame(s) on first frag, appending with gap'); + } else { + logger["b" /* logger */].warn('missing video frame(s), backtracking fragment'); + // Return back to the IDLE state without appending to buffer + // Causes findFragments to backtrack a segment and find the keyframe + // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment + frag.backtracked = true; + this.nextLoadPosition = data.startPTS; + this.state = State.IDLE; + this.fragPrevious = frag; + this.tick(); + return; + } + } else { + logger["b" /* logger */].warn('Already backtracked on this fragment, appending with the gap'); + } + } else { + // Only reset the backtracked flag if we've loaded the frag without any dropped frames + frag.backtracked = false; + } + } + + var drift = updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS), + hls = this.hls; + hls.trigger(events["a" /* default */].LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS }); + + // has remuxer dropped video frames located before first keyframe ? + [data.data1, data.data2].forEach(function (buffer) { + // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending) + // in that case it is useless to append following segments + if (buffer && buffer.length && _this2.state === State.PARSING) { + _this2.appended = true; + // arm pending Buffering flag before appending a segment + _this2.pendingBuffering = true; + hls.trigger(events["a" /* default */].BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' }); + } + }); + //trigger handler right now + this.tick(); + } + }; + + StreamController.prototype.onFragParsed = function onFragParsed(data) { + var fragCurrent = this.fragCurrent; + var fragNew = data.frag; + if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) { + this.stats.tparsed = performance.now(); + this.state = State.PARSED; + this._checkAppendedParsed(); + } + }; + + StreamController.prototype.onAudioTrackSwitching = function onAudioTrackSwitching(data) { + // if any URL found on new audio track, it is an alternate audio track + var altAudio = !!data.url, + trackId = data.id; + // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered + // don't do anything if we switch to alt audio: audio stream controller is handling it. + // we will just have to change buffer scheduling on audioTrackSwitched + if (!altAudio) { + if (this.mediaBuffer !== this.media) { + logger["b" /* logger */].log('switching on main audio, use media.buffered to schedule main fragment loading'); + this.mediaBuffer = this.media; + var fragCurrent = this.fragCurrent; + // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch + if (fragCurrent.loader) { + logger["b" /* logger */].log('switching to main audio track, cancel main fragment load'); + fragCurrent.loader.abort(); + } + this.fragCurrent = null; + this.fragPrevious = null; + // destroy demuxer to force init segment generation (following audio switch) + if (this.demuxer) { + this.demuxer.destroy(); + this.demuxer = null; + } + // switch to IDLE state to load new fragment + this.state = State.IDLE; + } + var hls = this.hls; + // switching to main audio, flush all audio and trigger track switched + hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); + hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId }); + this.altAudio = false; + } + }; + + StreamController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) { + var trackId = data.id, + altAudio = !!this.hls.audioTracks[trackId].url; + if (altAudio) { + var videoBuffer = this.videoBuffer; + // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered + if (videoBuffer && this.mediaBuffer !== videoBuffer) { + logger["b" /* logger */].log('switching on alternate audio, use video.buffered to schedule main fragment loading'); + this.mediaBuffer = videoBuffer; + } + } + this.altAudio = altAudio; + this.tick(); + }; + + StreamController.prototype.onBufferCreated = function onBufferCreated(data) { + var tracks = data.tracks, + mediaTrack = void 0, + name = void 0, + alternate = false; + for (var type in tracks) { + var track = tracks[type]; + if (track.id === 'main') { + name = type; + mediaTrack = track; + // keep video source buffer reference + if (type === 'video') { + this.videoBuffer = tracks[type].buffer; + } + } else { + alternate = true; + } + } + if (alternate && mediaTrack) { + logger["b" /* logger */].log('alternate track found, use ' + name + '.buffered to schedule main fragment loading'); + this.mediaBuffer = mediaTrack.buffer; + } else { + this.mediaBuffer = this.media; + } + }; + + StreamController.prototype.onBufferAppended = function onBufferAppended(data) { + if (data.parent === 'main') { + var state = this.state; + if (state === State.PARSING || state === State.PARSED) { + // check if all buffers have been appended + this.pendingBuffering = data.pending > 0; + this._checkAppendedParsed(); + } + } + }; + + StreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() { + //trigger handler right now + if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) { + var frag = this.fragCurrent; + if (frag) { + var media = this.mediaBuffer ? this.mediaBuffer : this.media; + logger["b" /* logger */].log('main buffered : ' + timeRanges.toString(media.buffered)); + // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams + var bufferedFrags = this._bufferedFrags.filter(function (frag) { + return buffer_helper.isBuffered(media, (frag.startPTS + frag.endPTS) / 2); + }); + // push new range + bufferedFrags.push(frag); + // sort frags, as we use BinarySearch for lookup in getBufferedFrag ... + this._bufferedFrags = bufferedFrags.sort(function (a, b) { + return a.startPTS - b.startPTS; + }); + this.fragPrevious = frag; + var stats = this.stats; + stats.tbuffered = performance.now(); + // we should get rid of this.fragLastKbps + this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst)); + this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' }); + this.state = State.IDLE; + } + this.tick(); + } + }; + + StreamController.prototype.onError = function onError(data) { + var frag = data.frag || this.fragCurrent; + // don't handle frag error not related to main fragment + if (frag && frag.type !== 'main') { + return; + } + // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end + var mediaBuffered = !!this.media && buffer_helper.isBuffered(this.media, this.media.currentTime) && buffer_helper.isBuffered(this.media, this.media.currentTime + 0.5); + + switch (data.details) { + case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR: + case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT: + case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR: + case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT: + if (!data.fatal) { + // keep retrying until the limit will be reached + if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) { + // exponential backoff capped to config.fragLoadingMaxRetryTimeout + var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout); + // reset load counter to avoid frag loop loading error + frag.loadCounter = 0; + logger["b" /* logger */].warn('mediaController: frag loading failed, retry in ' + delay + ' ms'); + this.retryDate = performance.now() + delay; + // retry loading state + // if loadedmetadata is not set, it means that we are emergency switch down on first frag + // in that case, reset startFragRequested flag + if (!this.loadedmetadata) { + this.startFragRequested = false; + this.nextLoadPosition = this.startPosition; + } + this.fragLoadError++; + this.state = State.FRAG_LOADING_WAITING_RETRY; + } else { + logger["b" /* logger */].error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...'); + // switch error to fatal + data.fatal = true; + this.state = State.ERROR; + } + } + break; + case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR: + if (!data.fatal) { + // if buffer is not empty + if (mediaBuffered) { + // try to reduce max buffer length : rationale is that we could get + // frag loop loading error because of buffer eviction + this._reduceMaxBufferLength(frag.duration); + this.state = State.IDLE; + } else { + // buffer empty. report as fatal if in manual mode or if lowest level. + // level controller takes care of emergency switch down logic + if (!frag.autoLevel || frag.level === 0) { + // switch error to fatal + data.fatal = true; + this.state = State.ERROR; + } + } + } + break; + case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR: + case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT: + if (this.state !== State.ERROR) { + if (data.fatal) { + // if fatal error, stop processing + this.state = State.ERROR; + logger["b" /* logger */].warn('streamController: ' + data.details + ',switch to ' + this.state + ' state ...'); + } else { + // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE + if (!data.levelRetry && this.state === State.WAITING_LEVEL) { + this.state = State.IDLE; + } + } + } + break; + case errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR: + // if in appending state + if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) { + // reduce max buf len if current position is buffered + if (mediaBuffered) { + this._reduceMaxBufferLength(this.config.maxBufferLength); + this.state = State.IDLE; + } else { + // current position is not buffered, but browser is still complaining about buffer full error + // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708 + // in that case flush the whole buffer to recover + logger["b" /* logger */].warn('buffer full error also media.currentTime is not buffered, flush everything'); + this.fragCurrent = null; + // flush everything + this.flushMainBuffer(0, Number.POSITIVE_INFINITY); + } + } + break; + default: + break; + } + }; + + StreamController.prototype._reduceMaxBufferLength = function _reduceMaxBufferLength(minLength) { + var config = this.config; + if (config.maxMaxBufferLength >= minLength) { + // reduce max buffer length as it might be too high. we do this to avoid loop flushing ... + config.maxMaxBufferLength /= 2; + logger["b" /* logger */].warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's'); + if (this.fragLoadIdx !== undefined) { + // increase fragment load Index to avoid frag loop loading error after buffer flush + this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold; + } + } + }; + + StreamController.prototype._checkBuffer = function _checkBuffer() { + var media = this.media, + config = this.config; + // if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek + if (media && media.readyState) { + var currentTime = media.currentTime, + mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media, + buffered = mediaBuffer.buffered; + // adjust currentTime to start position on loaded metadata + if (!this.loadedmetadata && buffered.length) { + this.loadedmetadata = true; + // only adjust currentTime if different from startPosition or if startPosition not buffered + // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered + var startPosition = media.seeking ? currentTime : this.startPosition, + startPositionBuffered = buffer_helper.isBuffered(mediaBuffer, startPosition), + firstbufferedPosition = buffered.start(0), + startNotBufferedButClose = !startPositionBuffered && Math.abs(startPosition - firstbufferedPosition) < config.maxSeekHole; + // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered + if (currentTime !== startPosition || startNotBufferedButClose) { + logger["b" /* logger */].log('target start position:' + startPosition); + // if startPosition not buffered, let's seek to buffered.start(0) + if (startNotBufferedButClose) { + startPosition = firstbufferedPosition; + logger["b" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition); + } + logger["b" /* logger */].log('adjust currentTime from ' + currentTime + ' to ' + startPosition); + media.currentTime = startPosition; + } + } else if (this.immediateSwitch) { + this.immediateLevelSwitchEnd(); + } else { + var bufferInfo = buffer_helper.bufferInfo(media, currentTime, 0), + expectedPlaying = !(media.paused || // not playing when media is paused + media.ended || // not playing when media is ended + media.buffered.length === 0), + // not playing if nothing buffered + jumpThreshold = 0.5, + // tolerance needed as some browsers stalls playback before reaching buffered range end + playheadMoving = currentTime !== this.lastCurrentTime; + + if (playheadMoving) { + // played moving, but was previously stalled => now not stuck anymore + if (this.stallReported) { + logger["b" /* logger */].warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(performance.now() - this.stalled) + 'ms'); + this.stallReported = false; + } + this.stalled = undefined; + this.nudgeRetry = 0; + } else { + // playhead not moving + if (expectedPlaying) { + // playhead not moving BUT media expected to play + var tnow = performance.now(); + var hls = this.hls; + if (!this.stalled) { + // stall just detected, store current time + this.stalled = tnow; + this.stallReported = false; + } else { + // playback already stalled, check stalling duration + // if stalling for more than a given threshold, let's try to recover + var stalledDuration = tnow - this.stalled; + var bufferLen = bufferInfo.len; + var nudgeRetry = this.nudgeRetry || 0; + // have we reached stall deadline ? + if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) { + // report stalled error once + if (!this.stallReported) { + this.stallReported = true; + logger["b" /* logger */].warn('playback stalling in low buffer @' + currentTime); + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen }); + } + // if buffer len is below threshold, try to jump to start of next buffer range if close + // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range) + var nextBufferStart = bufferInfo.nextStart, + delta = nextBufferStart - currentTime; + if (nextBufferStart && delta < config.maxSeekHole && delta > 0) { + this.nudgeRetry = ++nudgeRetry; + var nudgeOffset = nudgeRetry * config.nudgeOffset; + // next buffer is close ! adjust currentTime to nextBufferStart + // this will ensure effective video decoding + logger["b" /* logger */].log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + nudgeOffset); + media.currentTime = nextBufferStart + nudgeOffset; + // reset stalled so to rearm watchdog timer + this.stalled = undefined; + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_SEEK_OVER_HOLE, fatal: false, hole: nextBufferStart + nudgeOffset - currentTime }); + } + } else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) { + // report stalled error once + if (!this.stallReported) { + this.stallReported = true; + logger["b" /* logger */].warn('playback stalling in high buffer @' + currentTime); + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen }); + } + // reset stalled so to rearm watchdog timer + this.stalled = undefined; + this.nudgeRetry = ++nudgeRetry; + if (nudgeRetry < config.nudgeMaxRetry) { + var _currentTime = media.currentTime; + var targetTime = _currentTime + nudgeRetry * config.nudgeOffset; + logger["b" /* logger */].log('adjust currentTime from ' + _currentTime + ' to ' + targetTime); + // playback stalled in buffered area ... let's nudge currentTime to try to overcome this + media.currentTime = targetTime; + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_NUDGE_ON_STALL, fatal: false }); + } else { + logger["b" /* logger */].error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error'); + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: true }); + } + } + } + } + } + } + } + }; + + StreamController.prototype.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() { + this.state = State.IDLE; + // if loadedmetadata is not set, it means that we are emergency switch down on first frag + // in that case, reset startFragRequested flag + if (!this.loadedmetadata) { + this.startFragRequested = false; + this.nextLoadPosition = this.startPosition; + } + this.tick(); + }; + + StreamController.prototype.onBufferFlushed = function onBufferFlushed() { + /* after successful buffer flushing, filter flushed fragments from bufferedFrags + use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track) + */ + var media = this.mediaBuffer ? this.mediaBuffer : this.media; + this._bufferedFrags = this._bufferedFrags.filter(function (frag) { + return buffer_helper.isBuffered(media, (frag.startPTS + frag.endPTS) / 2); + }); + + if (this.fragLoadIdx !== undefined) { + // increase fragment load Index to avoid frag loop loading error after buffer flush + this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; + } + // move to IDLE once flush complete. this should trigger new fragment loading + this.state = State.IDLE; + // reset reference to frag + this.fragPrevious = null; + }; + + StreamController.prototype.swapAudioCodec = function swapAudioCodec() { + this.audioCodecSwap = !this.audioCodecSwap; + }; + + StreamController.prototype.computeLivePosition = function computeLivePosition(sliding, levelDetails) { + var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration; + return sliding + Math.max(0, levelDetails.totalduration - targetLatency); + }; + + stream_controller__createClass(StreamController, [{ + key: 'state', + set: function set(nextState) { + if (this.state !== nextState) { + var previousState = this.state; + this._state = nextState; + logger["b" /* logger */].log('main stream:' + previousState + '->' + nextState); + this.hls.trigger(events["a" /* default */].STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState }); + } + }, + get: function get() { + return this._state; + } + }, { + key: 'currentLevel', + get: function get() { + var media = this.media; + if (media) { + var frag = this.getBufferedFrag(media.currentTime); + if (frag) { + return frag.level; + } + } + return -1; + } + }, { + key: 'nextBufferedFrag', + get: function get() { + var media = this.media; + if (media) { + // first get end range of current fragment + return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime)); + } else { + return null; + } + } + }, { + key: 'nextLevel', + get: function get() { + var frag = this.nextBufferedFrag; + if (frag) { + return frag.level; + } else { + return -1; + } + } + }, { + key: 'liveSyncPosition', + get: function get() { + return this._liveSyncPosition; + }, + set: function set(value) { + this._liveSyncPosition = value; + } + }]); + + return StreamController; +}(event_handler); + +/* harmony default export */ var stream_controller = (stream_controller_StreamController); +// CONCATENATED MODULE: ./src/controller/level-controller.js +var level_controller__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; }; }(); + +function level_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function level_controller__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; } + +function level_controller__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; } + +/* + * Level Controller +*/ + + + + + + + +var level_controller_LevelController = function (_EventHandler) { + level_controller__inherits(LevelController, _EventHandler); + + function LevelController(hls) { + level_controller__classCallCheck(this, LevelController); + + var _this = level_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].ERROR)); + + _this._manualLevel = -1; + _this.timer = null; + return _this; + } + + LevelController.prototype.destroy = function destroy() { + this.cleanTimer(); + this._manualLevel = -1; + }; + + LevelController.prototype.cleanTimer = function cleanTimer() { + if (this.timer !== null) { + clearTimeout(this.timer); + this.timer = null; + } + }; + + LevelController.prototype.startLoad = function startLoad() { + var levels = this._levels; + + this.canload = true; + this.levelRetryCount = 0; + + // clean up live level details to force reload them, and reset load errors + if (levels) { + levels.forEach(function (level) { + level.loadError = 0; + var levelDetails = level.details; + if (levelDetails && levelDetails.live) { + level.details = undefined; + } + }); + } + // speed up live playlist refresh if timer exists + if (this.timer) { + this.tick(); + } + }; + + LevelController.prototype.stopLoad = function stopLoad() { + this.canload = false; + }; + + LevelController.prototype.onManifestLoaded = function onManifestLoaded(data) { + var levels = []; + var bitrateStart = void 0; + var levelSet = {}; + var levelFromSet = null; + var videoCodecFound = false; + var audioCodecFound = false; + var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase()); + var audioTracks = []; + + // regroup redundant levels together + data.levels.forEach(function (level) { + level.loadError = 0; + level.fragmentError = false; + + videoCodecFound = videoCodecFound || !!level.videoCodec; + audioCodecFound = audioCodecFound || !!level.audioCodec || !!(level.attrs && level.attrs.AUDIO); + + // erase audio codec info if browser does not support mp4a.40.34. + // demuxer will autodetect codec and fallback to mpeg/audio + if (chromeOrFirefox === true && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) { + level.audioCodec = undefined; + } + + levelFromSet = levelSet[level.bitrate]; + + if (levelFromSet === undefined) { + level.url = [level.url]; + level.urlId = 0; + levelSet[level.bitrate] = level; + levels.push(level); + } else { + levelFromSet.url.push(level.url); + } + }); + + // remove audio-only level if we also have levels with audio+video codecs signalled + if (videoCodecFound === true && audioCodecFound === true) { + levels = levels.filter(function (_ref) { + var videoCodec = _ref.videoCodec; + return !!videoCodec; + }); + } + + // only keep levels with supported audio/video codecs + levels = levels.filter(function (_ref2) { + var audioCodec = _ref2.audioCodec, + videoCodec = _ref2.videoCodec; + + return (!audioCodec || isCodecSupportedInMp4(audioCodec)) && (!videoCodec || isCodecSupportedInMp4(videoCodec)); + }); + + if (data.audioTracks) { + audioTracks = data.audioTracks.filter(function (track) { + return !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio'); + }); + } + + if (levels.length) { + // start bitrate is the first bitrate of the manifest + bitrateStart = levels[0].bitrate; + // sort level on bitrate + levels.sort(function (a, b) { + return a.bitrate - b.bitrate; + }); + this._levels = levels; + // find index of first level in sorted levels + for (var i = 0; i < levels.length; i++) { + if (levels[i].bitrate === bitrateStart) { + this._firstLevel = i; + logger["b" /* logger */].log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart); + break; + } + } + this.hls.trigger(events["a" /* default */].MANIFEST_PARSED, { levels: levels, audioTracks: audioTracks, firstLevel: this._firstLevel, stats: data.stats, audio: audioCodecFound, video: videoCodecFound, altAudio: audioTracks.length > 0 }); + } else { + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].MEDIA_ERROR, + details: errors["a" /* ErrorDetails */].MANIFEST_INCOMPATIBLE_CODECS_ERROR, + fatal: true, + url: this.hls.url, + reason: 'no level with compatible codecs found in manifest' + }); + } + }; + + LevelController.prototype.setLevelInternal = function setLevelInternal(newLevel) { + var levels = this._levels; + var hls = this.hls; + // check if level idx is valid + if (newLevel >= 0 && newLevel < levels.length) { + // stopping live reloading timer if any + this.cleanTimer(); + if (this._level !== newLevel) { + logger["b" /* logger */].log('switching to level ' + newLevel); + this._level = newLevel; + var levelProperties = levels[newLevel]; + levelProperties.level = newLevel; + // LEVEL_SWITCH to be deprecated in next major release + hls.trigger(events["a" /* default */].LEVEL_SWITCH, levelProperties); + hls.trigger(events["a" /* default */].LEVEL_SWITCHING, levelProperties); + } + var level = levels[newLevel], + levelDetails = level.details; + // check if we need to load playlist for this level + if (!levelDetails || levelDetails.live === true) { + // level not retrieved yet, or live playlist we need to (re)load it + var urlId = level.urlId; + hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId }); + } + } else { + // invalid level id given, trigger error + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx' }); + } + }; + + LevelController.prototype.onError = function onError(data) { + var _this2 = this; + + if (data.fatal === true) { + if (data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) { + this.cleanTimer(); + } + return; + } + + var details = data.details, + levelError = false, + fragmentError = false; + var levelIndex = void 0, + level = void 0; + var config = this.hls.config; + + // try to recover not fatal errors + + switch (details) { + case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR: + case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT: + case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR: + case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR: + case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT: + levelIndex = data.frag.level; + fragmentError = true; + break; + case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR: + case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT: + levelIndex = data.context.level; + levelError = true; + break; + case errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR: + levelIndex = data.level; + break; + } + /* try to switch to a redundant stream if any available. + * if no redundant stream available, emergency switch down (if in auto mode and current level not 0) + * otherwise, we cannot recover this network error ... + */ + if (levelIndex !== undefined) { + level = this._levels[levelIndex]; + level.loadError++; + level.fragmentError = fragmentError; + + // Allow fragment retry as long as configuration allows. + // Since fragment retry logic could depend on the levels, we should not enforce retry limits when there is an issue with fragments + // FIXME Find a better abstraction where fragment/level retry management is well decoupled + if (fragmentError === true) { + // if any redundant streams available and if we haven't try them all (level.loadError is reseted on successful frag/level load. + // if level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down + var redundantLevels = level.url.length; + + if (redundantLevels > 1 && level.loadError < redundantLevels) { + level.urlId = (level.urlId + 1) % redundantLevels; + level.details = undefined; + logger["b" /* logger */].warn('level controller,' + details + ' for level ' + levelIndex + ': switching to redundant stream id ' + level.urlId); + } else { + // we could try to recover if in auto mode and current level not lowest level (0) + if (this._manualLevel === -1 && levelIndex !== 0) { + logger["b" /* logger */].warn('level controller,' + details + ': switch-down for next fragment'); + this.hls.nextAutoLevel = levelIndex - 1; + } else { + logger["b" /* logger */].warn('level controller, ' + details + ': reload a fragment'); + // reset this._level so that another call to set level() will trigger again a frag load + this._level = undefined; + } + } + } else if (levelError === true) { + if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) { + // exponential backoff capped to max retry timeout + var delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); + // reset load counter to avoid frag loop loading error + this.timer = setTimeout(function () { + return _this2.tick(); + }, delay); + // boolean used to inform stream controller not to switch back to IDLE on non fatal error + data.levelRetry = true; + this.levelRetryCount++; + logger["b" /* logger */].warn('level controller,' + details + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount); + } else { + logger["b" /* logger */].error('cannot recover ' + details + ' error'); + this._level = undefined; + // stopping live reloading timer if any + this.cleanTimer(); + // switch error to fatal + data.fatal = true; + } + } + } + }; + + // reset errors on the successful load of a fragment + + + LevelController.prototype.onFragLoaded = function onFragLoaded(_ref3) { + var frag = _ref3.frag; + + if (frag !== undefined && frag.type === 'main') { + var level = this._levels[frag.level]; + if (level !== undefined) { + level.fragmentError = false; + level.loadError = 0; + this.levelRetryCount = 0; + } + } + }; + + LevelController.prototype.onLevelLoaded = function onLevelLoaded(data) { + var _this3 = this; + + var levelId = data.level; + // only process level loaded events matching with expected level + if (levelId === this._level) { + var curLevel = this._levels[levelId]; + // reset level load error counter on successful level loaded only if there is no issues with fragments + if (curLevel.fragmentError === false) { + curLevel.loadError = 0; + this.levelRetryCount = 0; + } + var newDetails = data.details; + // if current playlist is a live playlist, arm a timer to reload it + if (newDetails.live) { + var reloadInterval = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration), + curDetails = curLevel.details; + if (curDetails && newDetails.endSN === curDetails.endSN) { + // follow HLS Spec, If the client reloads a Playlist file and finds that it has not + // changed then it MUST wait for a period of one-half the target + // duration before retrying. + reloadInterval /= 2; + logger["b" /* logger */].log('same live playlist, reload twice faster'); + } + // decrement reloadInterval with level loading delay + reloadInterval -= performance.now() - data.stats.trequest; + // in any case, don't reload more than every second + reloadInterval = Math.max(1000, Math.round(reloadInterval)); + logger["b" /* logger */].log('live playlist, reload in ' + reloadInterval + ' ms'); + this.timer = setTimeout(function () { + return _this3.tick(); + }, reloadInterval); + } else { + this.cleanTimer(); + } + } + }; + + LevelController.prototype.tick = function tick() { + var levelId = this._level; + if (levelId !== undefined && this.canload) { + var level = this._levels[levelId]; + if (level && level.url) { + var urlId = level.urlId; + this.hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: level.url[urlId], level: levelId, id: urlId }); + } + } + }; + + level_controller__createClass(LevelController, [{ + key: 'levels', + get: function get() { + return this._levels; + } + }, { + key: 'level', + get: function get() { + return this._level; + }, + set: function set(newLevel) { + var levels = this._levels; + if (levels) { + newLevel = Math.min(newLevel, levels.length - 1); + if (this._level !== newLevel || levels[newLevel].details === undefined) { + this.setLevelInternal(newLevel); + } + } + } + }, { + key: 'manualLevel', + get: function get() { + return this._manualLevel; + }, + set: function set(newLevel) { + this._manualLevel = newLevel; + if (this._startLevel === undefined) { + this._startLevel = newLevel; + } + if (newLevel !== -1) { + this.level = newLevel; + } + } + }, { + key: 'firstLevel', + get: function get() { + return this._firstLevel; + }, + set: function set(newLevel) { + this._firstLevel = newLevel; + } + }, { + key: 'startLevel', + get: function get() { + // hls.startLevel takes precedence over config.startLevel + // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest) + if (this._startLevel === undefined) { + var configStartLevel = this.hls.config.startLevel; + if (configStartLevel !== undefined) { + return configStartLevel; + } else { + return this._firstLevel; + } + } else { + return this._startLevel; + } + }, + set: function set(newLevel) { + this._startLevel = newLevel; + } + }, { + key: 'nextLoadLevel', + get: function get() { + if (this._manualLevel !== -1) { + return this._manualLevel; + } else { + return this.hls.nextAutoLevel; + } + }, + set: function set(nextLevel) { + this.level = nextLevel; + if (this._manualLevel === -1) { + this.hls.nextAutoLevel = nextLevel; + } + } + }]); + + return LevelController; +}(event_handler); + +/* harmony default export */ var level_controller = (level_controller_LevelController); +// EXTERNAL MODULE: ./src/demux/id3.js +var id3 = __webpack_require__(3); + +// CONCATENATED MODULE: ./src/controller/id3-track-controller.js +function id3_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function id3_track_controller__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; } + +function id3_track_controller__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; } + +/* + * id3 metadata track controller +*/ + + + + + +var id3_track_controller_ID3TrackController = function (_EventHandler) { + id3_track_controller__inherits(ID3TrackController, _EventHandler); + + function ID3TrackController(hls) { + id3_track_controller__classCallCheck(this, ID3TrackController); + + var _this = id3_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].FRAG_PARSING_METADATA)); + + _this.id3Track = undefined; + _this.media = undefined; + return _this; + } + + ID3TrackController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + }; + + // Add ID3 metatadata text track. + + + ID3TrackController.prototype.onMediaAttached = function onMediaAttached(data) { + this.media = data.media; + if (!this.media) { + return; + } + }; + + ID3TrackController.prototype.onMediaDetaching = function onMediaDetaching() { + this.media = undefined; + }; + + ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) { + var fragment = data.frag; + var samples = data.samples; + + // create track dynamically + if (!this.id3Track) { + this.id3Track = this.media.addTextTrack('metadata', 'id3'); + this.id3Track.mode = 'hidden'; + } + + // Attempt to recreate Safari functionality by creating + // WebKitDataCue objects when available and store the decoded + // ID3 data in the value property of the cue + var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue; + + for (var i = 0; i < samples.length; i++) { + var frames = id3["a" /* default */].getID3Frames(samples[i].data); + if (frames) { + var startTime = samples[i].pts; + var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS; + + // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE + if (startTime === endTime) { + endTime += 0.0001; + } + + for (var j = 0; j < frames.length; j++) { + var frame = frames[j]; + // Safari doesn't put the timestamp frame in the TextTrack + if (!id3["a" /* default */].isTimeStampFrame(frame)) { + var cue = new Cue(startTime, endTime, ''); + cue.value = frame; + this.id3Track.addCue(cue); + } + } + } + } + }; + + return ID3TrackController; +}(event_handler); + +/* harmony default export */ var id3_track_controller = (id3_track_controller_ID3TrackController); +// CONCATENATED MODULE: ./src/utils/ewma.js +function ewma__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/* + * compute an Exponential Weighted moving average + * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average + * - heavily inspired from shaka-player + */ + +var EWMA = function () { + + // About half of the estimated value will be from the last |halfLife| samples by weight. + function EWMA(halfLife) { + ewma__classCallCheck(this, EWMA); + + // Larger values of alpha expire historical data more slowly. + this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0; + this.estimate_ = 0; + this.totalWeight_ = 0; + } + + EWMA.prototype.sample = function sample(weight, value) { + var adjAlpha = Math.pow(this.alpha_, weight); + this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_; + this.totalWeight_ += weight; + }; + + EWMA.prototype.getTotalWeight = function getTotalWeight() { + return this.totalWeight_; + }; + + EWMA.prototype.getEstimate = function getEstimate() { + if (this.alpha_) { + var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_); + return this.estimate_ / zeroFactor; + } else { + return this.estimate_; + } + }; + + return EWMA; +}(); + +/* harmony default export */ var ewma = (EWMA); +// CONCATENATED MODULE: ./src/utils/ewma-bandwidth-estimator.js +function ewma_bandwidth_estimator__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/* + * EWMA Bandwidth Estimator + * - heavily inspired from shaka-player + * Tracks bandwidth samples and estimates available bandwidth. + * Based on the minimum of two exponentially-weighted moving averages with + * different half-lives. + */ + + + +var ewma_bandwidth_estimator_EwmaBandWidthEstimator = function () { + function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) { + ewma_bandwidth_estimator__classCallCheck(this, EwmaBandWidthEstimator); + + this.hls = hls; + this.defaultEstimate_ = defaultEstimate; + this.minWeight_ = 0.001; + this.minDelayMs_ = 50; + this.slow_ = new ewma(slow); + this.fast_ = new ewma(fast); + } + + EwmaBandWidthEstimator.prototype.sample = function sample(durationMs, numBytes) { + durationMs = Math.max(durationMs, this.minDelayMs_); + var bandwidth = 8000 * numBytes / durationMs, + + //console.log('instant bw:'+ Math.round(bandwidth)); + // we weight sample using loading duration.... + weight = durationMs / 1000; + this.fast_.sample(weight, bandwidth); + this.slow_.sample(weight, bandwidth); + }; + + EwmaBandWidthEstimator.prototype.canEstimate = function canEstimate() { + var fast = this.fast_; + return fast && fast.getTotalWeight() >= this.minWeight_; + }; + + EwmaBandWidthEstimator.prototype.getEstimate = function getEstimate() { + if (this.canEstimate()) { + //console.log('slow estimate:'+ Math.round(this.slow_.getEstimate())); + //console.log('fast estimate:'+ Math.round(this.fast_.getEstimate())); + // Take the minimum of these two estimates. This should have the effect of + // adapting down quickly, but up more slowly. + return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate()); + } else { + return this.defaultEstimate_; + } + }; + + EwmaBandWidthEstimator.prototype.destroy = function destroy() {}; + + return EwmaBandWidthEstimator; +}(); + +/* harmony default export */ var ewma_bandwidth_estimator = (ewma_bandwidth_estimator_EwmaBandWidthEstimator); +// CONCATENATED MODULE: ./src/controller/abr-controller.js +var abr_controller__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; }; }(); + +function abr_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function abr_controller__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; } + +function abr_controller__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; } + +/* + * simple ABR Controller + * - compute next level based on last fragment bw heuristics + * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling + */ + + + + + + + + +var abr_controller_AbrController = function (_EventHandler) { + abr_controller__inherits(AbrController, _EventHandler); + + function AbrController(hls) { + abr_controller__classCallCheck(this, AbrController); + + var _this = abr_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_BUFFERED, events["a" /* default */].ERROR)); + + _this.lastLoadedFragLevel = 0; + _this._nextAutoLevel = -1; + _this.hls = hls; + _this.timer = null; + _this._bwEstimator = null; + _this.onCheck = _this._abandonRulesCheck.bind(_this); + return _this; + } + + AbrController.prototype.destroy = function destroy() { + this.clearTimer(); + event_handler.prototype.destroy.call(this); + }; + + AbrController.prototype.onFragLoading = function onFragLoading(data) { + var frag = data.frag; + if (frag.type === 'main') { + if (!this.timer) { + this.timer = setInterval(this.onCheck, 100); + } + // lazy init of bw Estimator, rationale is that we use different params for Live/VoD + // so we need to wait for stream manifest / playlist type to instantiate it. + if (!this._bwEstimator) { + var hls = this.hls, + level = data.frag.level, + isLive = hls.levels[level].details.live, + config = hls.config, + ewmaFast = void 0, + ewmaSlow = void 0; + + if (isLive) { + ewmaFast = config.abrEwmaFastLive; + ewmaSlow = config.abrEwmaSlowLive; + } else { + ewmaFast = config.abrEwmaFastVoD; + ewmaSlow = config.abrEwmaSlowVoD; + } + this._bwEstimator = new ewma_bandwidth_estimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate); + } + this.fragCurrent = frag; + } + }; + + AbrController.prototype._abandonRulesCheck = function _abandonRulesCheck() { + /* + monitor fragment retrieval time... + we compute expected time of arrival of the complete fragment. + we compare it to expected time of buffer starvation + */ + var hls = this.hls, + v = hls.media, + frag = this.fragCurrent, + loader = frag.loader, + minAutoLevel = hls.minAutoLevel; + + // if loader has been destroyed or loading has been aborted, stop timer and return + if (!loader || loader.stats && loader.stats.aborted) { + logger["b" /* logger */].warn('frag loader destroy or aborted, disarm abandonRules'); + this.clearTimer(); + return; + } + var stats = loader.stats; + /* only monitor frag retrieval time if + (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) */ + if (v && stats && (!v.paused && v.playbackRate !== 0 || !v.readyState) && frag.autoLevel && frag.level) { + var requestDelay = performance.now() - stats.trequest, + playbackRate = Math.abs(v.playbackRate); + // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate + if (requestDelay > 500 * frag.duration / playbackRate) { + var levels = hls.levels, + loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay), + // byte/s; at least 1 byte/s to avoid division by zero + // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size + level = levels[frag.level], + levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate, + expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)), + pos = v.currentTime, + fragLoadedDelay = (expectedLen - stats.loaded) / loadRate, + bufferStarvationDelay = (buffer_helper.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos) / playbackRate; + // consider emergency switch down only if we have less than 2 frag buffered AND + // time to finish loading current fragment is bigger than buffer starvation delay + // ie if we risk buffer starvation if bw does not increase quickly + if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) { + var fragLevelNextLoadedDelay = void 0, + nextLoadLevel = void 0; + // lets iterate through lower level and try to find the biggest one that could avoid rebuffering + // we start from current level - 1 and we step down , until we find a matching level + for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) { + // compute time to load next fragment at lower level + // 0.8 : consider only 80% of current bw to be conservative + // 8 = bits per byte (bps/Bps) + var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate; + fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate); + if (fragLevelNextLoadedDelay < bufferStarvationDelay) { + // we found a lower level that be rebuffering free with current estimated bw ! + break; + } + } + // only emergency switch down if it takes less time to load new fragment at lowest level instead + // of finishing loading current one ... + if (fragLevelNextLoadedDelay < fragLoadedDelay) { + logger["b" /* logger */].warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel + ':fragLoadedDelay[' + nextLoadLevel + ']<fragLoadedDelay[' + (frag.level - 1) + '];bufferStarvationDelay:' + fragLevelNextLoadedDelay.toFixed(1) + '<' + fragLoadedDelay.toFixed(1) + ':' + bufferStarvationDelay.toFixed(1)); + // force next load level in auto mode + hls.nextLoadLevel = nextLoadLevel; + // update bw estimate for this fragment before cancelling load (this will help reducing the bw) + this._bwEstimator.sample(requestDelay, stats.loaded); + //abort fragment loading + loader.abort(); + // stop abandon rules timer + this.clearTimer(); + hls.trigger(events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats }); + } + } + } + } + }; + + AbrController.prototype.onFragLoaded = function onFragLoaded(data) { + var frag = data.frag; + if (frag.type === 'main' && !isNaN(frag.sn)) { + // stop monitoring bw once frag loaded + this.clearTimer(); + // store level id after successful fragment load + this.lastLoadedFragLevel = frag.level; + // reset forced auto level value so that next level will be selected + this._nextAutoLevel = -1; + + // compute level average bitrate + if (this.hls.config.abrMaxWithRealBitrate) { + var level = this.hls.levels[frag.level]; + var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded; + var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration; + level.loaded = { bytes: loadedBytes, duration: loadedDuration }; + level.realBitrate = Math.round(8 * loadedBytes / loadedDuration); + } + // if fragment has been loaded to perform a bitrate test, + if (data.frag.bitrateTest) { + var stats = data.stats; + stats.tparsed = stats.tbuffered = stats.tload; + this.onFragBuffered(data); + } + } + }; + + AbrController.prototype.onFragBuffered = function onFragBuffered(data) { + var stats = data.stats, + frag = data.frag; + // only update stats on first frag buffering + // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly + // and leading to wrong bw estimation + // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED) + if (stats.aborted !== true && frag.loadCounter === 1 && frag.type === 'main' && !isNaN(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) { + // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached + // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached + // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation + var fragLoadingProcessingMs = stats.tparsed - stats.trequest; + logger["b" /* logger */].log('latency/loading/parsing/append/kbps:' + Math.round(stats.tfirst - stats.trequest) + '/' + Math.round(stats.tload - stats.tfirst) + '/' + Math.round(stats.tparsed - stats.tload) + '/' + Math.round(stats.tbuffered - stats.tparsed) + '/' + Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest))); + this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded); + stats.bwEstimate = this._bwEstimator.getEstimate(); + // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration + if (frag.bitrateTest) { + this.bitrateTestDelay = fragLoadingProcessingMs / 1000; + } else { + this.bitrateTestDelay = 0; + } + } + }; + + AbrController.prototype.onError = function onError(data) { + // stop timer in case of frag loading error + switch (data.details) { + case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR: + case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT: + this.clearTimer(); + break; + default: + break; + } + }; + + AbrController.prototype.clearTimer = function clearTimer() { + clearInterval(this.timer); + this.timer = null; + }; + + // return next auto level + + + AbrController.prototype._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) { + for (var i = maxAutoLevel; i >= minAutoLevel; i--) { + var levelInfo = levels[i], + levelDetails = levelInfo.details, + avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration, + live = levelDetails ? levelDetails.live : false, + adjustedbw = void 0; + // follow algorithm captured from stagefright : + // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp + // Pick the highest bandwidth stream below or equal to estimated bandwidth. + // consider only 80% of the available bandwidth, but if we are switching up, + // be even more conservative (70%) to avoid overestimating and immediately + // switching back. + if (i <= currentLevel) { + adjustedbw = bwFactor * currentBw; + } else { + adjustedbw = bwUpFactor * currentBw; + } + var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate, + fetchDuration = bitrate * avgDuration / adjustedbw; + + logger["b" /* logger */].trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration); + // if adjusted bw is greater than level bitrate AND + if (adjustedbw > bitrate && ( + // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches + // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ... + // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1 + !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) { + // as we are looping from highest to lowest, this will return the best achievable quality level + return i; + } + } + // not enough time budget even with quality level 0 ... rebuffering might happen + return -1; + }; + + abr_controller__createClass(AbrController, [{ + key: 'nextAutoLevel', + get: function get() { + var forcedAutoLevel = this._nextAutoLevel; + var bwEstimator = this._bwEstimator; + // in case next auto level has been forced, and bw not available or not reliable, return forced value + if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) { + return forcedAutoLevel; + } + // compute next level using ABR logic + var nextABRAutoLevel = this._nextABRAutoLevel; + // if forced auto level has been defined, use it to cap ABR computed quality level + if (forcedAutoLevel !== -1) { + nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel); + } + return nextABRAutoLevel; + }, + set: function set(nextLevel) { + this._nextAutoLevel = nextLevel; + } + }, { + key: '_nextABRAutoLevel', + get: function get() { + var hls = this.hls, + maxAutoLevel = hls.maxAutoLevel, + levels = hls.levels, + config = hls.config, + minAutoLevel = hls.minAutoLevel; + var v = hls.media, + currentLevel = this.lastLoadedFragLevel, + currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0, + pos = v ? v.currentTime : 0, + + // playbackRate is the absolute value of the playback rate; if v.playbackRate is 0, we use 1 to load as + // if we're playing back at the normal rate. + playbackRate = v && v.playbackRate !== 0 ? Math.abs(v.playbackRate) : 1.0, + avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate, + + // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted. + bufferStarvationDelay = (buffer_helper.bufferInfo(v, pos, config.maxBufferHole).end - pos) / playbackRate; + + // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all + var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels); + if (bestLevel >= 0) { + return bestLevel; + } else { + logger["b" /* logger */].trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering'); + // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering + // if no matching level found, logic will return 0 + var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay, + bwFactor = config.abrBandWidthFactor, + bwUpFactor = config.abrBandWidthUpFactor; + if (bufferStarvationDelay === 0) { + // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test + var bitrateTestDelay = this.bitrateTestDelay; + if (bitrateTestDelay) { + // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value + // max video loading delay used in automatic start level selection : + // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level + + // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` ) + // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration + var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay; + maxStarvationDelay = maxLoadingDelay - bitrateTestDelay; + logger["b" /* logger */].trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms'); + // don't use conservative factor on bitrate test + bwFactor = bwUpFactor = 1; + } + } + bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels); + return Math.max(bestLevel, 0); + } + } + }]); + + return AbrController; +}(event_handler); + +/* harmony default export */ var abr_controller = (abr_controller_AbrController); +// CONCATENATED MODULE: ./src/controller/buffer-controller.js +function buffer_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function buffer_controller__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; } + +function buffer_controller__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; } + +/* + * Buffer Controller +*/ + + + + + + + +var buffer_controller_MediaSource = getMediaSource(); + +var buffer_controller_BufferController = function (_EventHandler) { + buffer_controller__inherits(BufferController, _EventHandler); + + function BufferController(hls) { + buffer_controller__classCallCheck(this, BufferController); + + // the value that we have set mediasource.duration to + // (the actual duration may be tweaked slighly by the browser) + var _this = buffer_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].BUFFER_RESET, events["a" /* default */].BUFFER_APPENDING, events["a" /* default */].BUFFER_CODECS, events["a" /* default */].BUFFER_EOS, events["a" /* default */].BUFFER_FLUSHING, events["a" /* default */].LEVEL_PTS_UPDATED, events["a" /* default */].LEVEL_UPDATED)); + + _this._msDuration = null; + // the value that we want to set mediaSource.duration to + _this._levelDuration = null; + + // Source Buffer listeners + _this.onsbue = _this.onSBUpdateEnd.bind(_this); + _this.onsbe = _this.onSBUpdateError.bind(_this); + _this.pendingTracks = {}; + _this.tracks = {}; + return _this; + } + + BufferController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + }; + + BufferController.prototype.onLevelPtsUpdated = function onLevelPtsUpdated(data) { + var type = data.type; + var audioTrack = this.tracks.audio; + + // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended) + // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset` + // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue + // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend` + // event if SB is in updating state. + // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486 + + if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') { + // Chrome audio mp3 track + var audioBuffer = this.sourceBuffer.audio; + var delta = Math.abs(audioBuffer.timestampOffset - data.start); + + // adjust timestamp offset if time delta is greater than 100ms + if (delta > 0.1) { + var updating = audioBuffer.updating; + + try { + audioBuffer.abort(); + } catch (err) { + updating = true; + logger["b" /* logger */].warn('can not abort audio buffer: ' + err); + } + + if (!updating) { + logger["b" /* logger */].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start); + audioBuffer.timestampOffset = data.start; + } else { + this.audioTimestampOffset = data.start; + } + } + } + }; + + BufferController.prototype.onManifestParsed = function onManifestParsed(data) { + var audioExpected = data.audio, + videoExpected = data.video || data.levels.length && data.audio, + sourceBufferNb = 0; + // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller + // sourcebuffers will be created all at once when the expected nb of tracks will be reached + // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller + // it will contain the expected nb of source buffers, no need to compute it + if (data.altAudio && (audioExpected || videoExpected)) { + sourceBufferNb = (audioExpected ? 1 : 0) + (videoExpected ? 1 : 0); + logger["b" /* logger */].log(sourceBufferNb + ' sourceBuffer(s) expected'); + } + this.sourceBufferNb = sourceBufferNb; + }; + + BufferController.prototype.onMediaAttaching = function onMediaAttaching(data) { + var media = this.media = data.media; + if (media) { + // setup the media source + var ms = this.mediaSource = new buffer_controller_MediaSource(); + //Media Source listeners + this.onmso = this.onMediaSourceOpen.bind(this); + this.onmse = this.onMediaSourceEnded.bind(this); + this.onmsc = this.onMediaSourceClose.bind(this); + ms.addEventListener('sourceopen', this.onmso); + ms.addEventListener('sourceended', this.onmse); + ms.addEventListener('sourceclose', this.onmsc); + // link video and media Source + media.src = URL.createObjectURL(ms); + } + }; + + BufferController.prototype.onMediaDetaching = function onMediaDetaching() { + logger["b" /* logger */].log('media source detaching'); + var ms = this.mediaSource; + if (ms) { + if (ms.readyState === 'open') { + try { + // endOfStream could trigger exception if any sourcebuffer is in updating state + // we don't really care about checking sourcebuffer state here, + // as we are anyway detaching the MediaSource + // let's just avoid this exception to propagate + ms.endOfStream(); + } catch (err) { + logger["b" /* logger */].warn('onMediaDetaching:' + err.message + ' while calling endOfStream'); + } + } + ms.removeEventListener('sourceopen', this.onmso); + ms.removeEventListener('sourceended', this.onmse); + ms.removeEventListener('sourceclose', this.onmsc); + + // Detach properly the MediaSource from the HTMLMediaElement as + // suggested in https://github.com/w3c/media-source/issues/53. + if (this.media) { + URL.revokeObjectURL(this.media.src); + this.media.removeAttribute('src'); + this.media.load(); + } + + this.mediaSource = null; + this.media = null; + this.pendingTracks = {}; + this.tracks = {}; + this.sourceBuffer = {}; + this.flushRange = []; + this.segments = []; + this.appended = 0; + } + this.onmso = this.onmse = this.onmsc = null; + this.hls.trigger(events["a" /* default */].MEDIA_DETACHED); + }; + + BufferController.prototype.onMediaSourceOpen = function onMediaSourceOpen() { + logger["b" /* logger */].log('media source opened'); + this.hls.trigger(events["a" /* default */].MEDIA_ATTACHED, { media: this.media }); + var mediaSource = this.mediaSource; + if (mediaSource) { + // once received, don't listen anymore to sourceopen event + mediaSource.removeEventListener('sourceopen', this.onmso); + } + this.checkPendingTracks(); + }; + + BufferController.prototype.checkPendingTracks = function checkPendingTracks() { + // if any buffer codecs pending, check if we have enough to create sourceBuffers + var pendingTracks = this.pendingTracks, + pendingTracksNb = Object.keys(pendingTracks).length; + // if any pending tracks and (if nb of pending tracks gt or equal than expected nb or if unknown expected nb) + if (pendingTracksNb && (this.sourceBufferNb <= pendingTracksNb || this.sourceBufferNb === 0)) { + // ok, let's create them now ! + this.createSourceBuffers(pendingTracks); + this.pendingTracks = {}; + // append any pending segments now ! + this.doAppending(); + } + }; + + BufferController.prototype.onMediaSourceClose = function onMediaSourceClose() { + logger["b" /* logger */].log('media source closed'); + }; + + BufferController.prototype.onMediaSourceEnded = function onMediaSourceEnded() { + logger["b" /* logger */].log('media source ended'); + }; + + BufferController.prototype.onSBUpdateEnd = function onSBUpdateEnd() { + // update timestampOffset + if (this.audioTimestampOffset) { + var audioBuffer = this.sourceBuffer.audio; + logger["b" /* logger */].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset); + audioBuffer.timestampOffset = this.audioTimestampOffset; + delete this.audioTimestampOffset; + } + + if (this._needsFlush) { + this.doFlush(); + } + + if (this._needsEos) { + this.checkEos(); + } + this.appending = false; + var parent = this.parent; + // count nb of pending segments waiting for appending on this sourcebuffer + var pending = this.segments.reduce(function (counter, segment) { + return segment.parent === parent ? counter + 1 : counter; + }, 0); + this.hls.trigger(events["a" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending }); + + // don't append in flushing mode + if (!this._needsFlush) { + this.doAppending(); + } + + this.updateMediaElementDuration(); + }; + + BufferController.prototype.onSBUpdateError = function onSBUpdateError(event) { + logger["b" /* logger */].error('sourceBuffer error:', event); + // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error + // this error might not always be fatal (it is fatal if decode error is set, in that case + // it will be followed by a mediaElement error ...) + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false }); + // we don't need to do more than that, as accordin to the spec, updateend will be fired just after + }; + + BufferController.prototype.onBufferReset = function onBufferReset() { + var sourceBuffer = this.sourceBuffer; + for (var type in sourceBuffer) { + var sb = sourceBuffer[type]; + try { + this.mediaSource.removeSourceBuffer(sb); + sb.removeEventListener('updateend', this.onsbue); + sb.removeEventListener('error', this.onsbe); + } catch (err) {} + } + this.sourceBuffer = {}; + this.flushRange = []; + this.segments = []; + this.appended = 0; + }; + + BufferController.prototype.onBufferCodecs = function onBufferCodecs(tracks) { + // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks + // if sourcebuffers already created, do nothing ... + if (Object.keys(this.sourceBuffer).length === 0) { + for (var trackName in tracks) { + this.pendingTracks[trackName] = tracks[trackName]; + } + var mediaSource = this.mediaSource; + if (mediaSource && mediaSource.readyState === 'open') { + // try to create sourcebuffers if mediasource opened + this.checkPendingTracks(); + } + } + }; + + BufferController.prototype.createSourceBuffers = function createSourceBuffers(tracks) { + var sourceBuffer = this.sourceBuffer, + mediaSource = this.mediaSource; + + for (var trackName in tracks) { + if (!sourceBuffer[trackName]) { + var track = tracks[trackName]; + // use levelCodec as first priority + var codec = track.levelCodec || track.codec; + var mimeType = track.container + ';codecs=' + codec; + logger["b" /* logger */].log('creating sourceBuffer(' + mimeType + ')'); + try { + var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType); + sb.addEventListener('updateend', this.onsbue); + sb.addEventListener('error', this.onsbe); + this.tracks[trackName] = { codec: codec, container: track.container }; + track.buffer = sb; + } catch (err) { + logger["b" /* logger */].error('error while trying to add sourceBuffer:' + err.message); + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType }); + } + } + } + this.hls.trigger(events["a" /* default */].BUFFER_CREATED, { tracks: tracks }); + }; + + BufferController.prototype.onBufferAppending = function onBufferAppending(data) { + if (!this._needsFlush) { + if (!this.segments) { + this.segments = [data]; + } else { + this.segments.push(data); + } + this.doAppending(); + } + }; + + BufferController.prototype.onBufferAppendFail = function onBufferAppendFail(data) { + logger["b" /* logger */].error('sourceBuffer error:', data.event); + // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error + // this error might not always be fatal (it is fatal if decode error is set, in that case + // it will be followed by a mediaElement error ...) + this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false }); + }; + + // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos() + + + BufferController.prototype.onBufferEos = function onBufferEos(data) { + var sb = this.sourceBuffer; + var dataType = data.type; + for (var type in sb) { + if (!dataType || type === dataType) { + if (!sb[type].ended) { + sb[type].ended = true; + logger["b" /* logger */].log(type + ' sourceBuffer now EOS'); + } + } + } + this.checkEos(); + }; + + // if all source buffers are marked as ended, signal endOfStream() to MediaSource. + + + BufferController.prototype.checkEos = function checkEos() { + var sb = this.sourceBuffer, + mediaSource = this.mediaSource; + if (!mediaSource || mediaSource.readyState !== 'open') { + this._needsEos = false; + return; + } + for (var type in sb) { + var sbobj = sb[type]; + if (!sbobj.ended) { + return; + } + if (sbobj.updating) { + this._needsEos = true; + return; + } + } + logger["b" /* logger */].log('all media data available, signal endOfStream() to MediaSource and stop loading fragment'); + //Notify the media element that it now has all of the media data + try { + mediaSource.endOfStream(); + } catch (e) { + logger["b" /* logger */].warn('exception while calling mediaSource.endOfStream()'); + } + this._needsEos = false; + }; + + BufferController.prototype.onBufferFlushing = function onBufferFlushing(data) { + this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type }); + // attempt flush immediatly + this.flushBufferCounter = 0; + this.doFlush(); + }; + + BufferController.prototype.onLevelUpdated = function onLevelUpdated(event) { + var details = event.details; + if (details.fragments.length === 0) { + return; + } + this._levelDuration = details.totalduration + details.fragments[0].start; + this.updateMediaElementDuration(); + }; + + // https://github.com/video-dev/hls.js/issues/355 + + + BufferController.prototype.updateMediaElementDuration = function updateMediaElementDuration() { + var media = this.media, + mediaSource = this.mediaSource, + sourceBuffer = this.sourceBuffer, + levelDuration = this._levelDuration; + if (levelDuration === null || !media || !mediaSource || !sourceBuffer || media.readyState === 0 || mediaSource.readyState !== 'open') { + return; + } + for (var type in sourceBuffer) { + if (sourceBuffer[type].updating) { + // can't set duration whilst a buffer is updating + return; + } + } + if (this._msDuration === null) { + // initialise to the value that the media source is reporting + this._msDuration = mediaSource.duration; + } + var duration = media.duration; + // levelDuration was the last value we set. + // not using mediaSource.duration as the browser may tweak this value + // only update mediasource duration if its value increase, this is to avoid + // flushing already buffered portion when switching between quality level + if (levelDuration > this._msDuration && levelDuration > duration || duration === Infinity || isNaN(duration)) { + logger["b" /* logger */].log('Updating mediasource duration to ' + levelDuration.toFixed(3)); + this._msDuration = mediaSource.duration = levelDuration; + } + }; + + BufferController.prototype.doFlush = function doFlush() { + // loop through all buffer ranges to flush + while (this.flushRange.length) { + var range = this.flushRange[0]; + // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer + if (this.flushBuffer(range.start, range.end, range.type)) { + // range flushed, remove from flush array + this.flushRange.shift(); + this.flushBufferCounter = 0; + } else { + this._needsFlush = true; + // avoid looping, wait for SB update end to retrigger a flush + return; + } + } + if (this.flushRange.length === 0) { + // everything flushed + this._needsFlush = false; + + // let's recompute this.appended, which is used to avoid flush looping + var appended = 0; + var sourceBuffer = this.sourceBuffer; + try { + for (var type in sourceBuffer) { + appended += sourceBuffer[type].buffered.length; + } + } catch (error) { + // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource + // this is harmess at this stage, catch this to avoid reporting an internal exception + logger["b" /* logger */].error('error while accessing sourceBuffer.buffered'); + } + this.appended = appended; + this.hls.trigger(events["a" /* default */].BUFFER_FLUSHED); + } + }; + + BufferController.prototype.doAppending = function doAppending() { + var hls = this.hls, + sourceBuffer = this.sourceBuffer, + segments = this.segments; + if (Object.keys(sourceBuffer).length) { + if (this.media.error) { + this.segments = []; + logger["b" /* logger */].error('trying to append although a media error occured, flush segment and abort'); + return; + } + if (this.appending) { + //logger.log(`sb appending in progress`); + return; + } + if (segments && segments.length) { + var segment = segments.shift(); + try { + var type = segment.type, + sb = sourceBuffer[type]; + if (sb) { + if (!sb.updating) { + // reset sourceBuffer ended flag before appending segment + sb.ended = false; + //logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`); + this.parent = segment.parent; + sb.appendBuffer(segment.data); + this.appendError = 0; + this.appended++; + this.appending = true; + } else { + segments.unshift(segment); + } + } else { + // in case we don't have any source buffer matching with this segment type, + // it means that Mediasource fails to create sourcebuffer + // discard this segment, and trigger update end + this.onSBUpdateEnd(); + } + } catch (err) { + // in case any error occured while appending, put back segment in segments table + logger["b" /* logger */].error('error while trying to append buffer:' + err.message); + segments.unshift(segment); + var event = { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, parent: segment.parent }; + if (err.code !== 22) { + if (this.appendError) { + this.appendError++; + } else { + this.appendError = 1; + } + event.details = errors["a" /* ErrorDetails */].BUFFER_APPEND_ERROR; + /* with UHD content, we could get loop of quota exceeded error until + browser is able to evict some data from sourcebuffer. retrying help recovering this + */ + if (this.appendError > hls.config.appendErrorMaxRetry) { + logger["b" /* logger */].log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer'); + segments = []; + event.fatal = true; + hls.trigger(events["a" /* default */].ERROR, event); + return; + } else { + event.fatal = false; + hls.trigger(events["a" /* default */].ERROR, event); + } + } else { + // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror + // let's stop appending any segments, and report BUFFER_FULL_ERROR error + this.segments = []; + event.details = errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR; + event.fatal = false; + hls.trigger(events["a" /* default */].ERROR, event); + return; + } + } + } + } + }; + + /* + flush specified buffered range, + return true once range has been flushed. + as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end + */ + + + BufferController.prototype.flushBuffer = function flushBuffer(startOffset, endOffset, typeIn) { + var sb, + i, + bufStart, + bufEnd, + flushStart, + flushEnd, + sourceBuffer = this.sourceBuffer; + if (Object.keys(sourceBuffer).length) { + logger["b" /* logger */].log('flushBuffer,pos/start/end: ' + this.media.currentTime.toFixed(3) + '/' + startOffset + '/' + endOffset); + // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments + if (this.flushBufferCounter < this.appended) { + for (var type in sourceBuffer) { + // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one + // if no, let's flush all sourcebuffers + if (typeIn && type !== typeIn) { + continue; + } + sb = sourceBuffer[type]; + // we are going to flush buffer, mark source buffer as 'not ended' + sb.ended = false; + if (!sb.updating) { + try { + for (i = 0; i < sb.buffered.length; i++) { + bufStart = sb.buffered.start(i); + bufEnd = sb.buffered.end(i); + // workaround firefox not able to properly flush multiple buffered range. + if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) { + flushStart = startOffset; + flushEnd = endOffset; + } else { + flushStart = Math.max(bufStart, startOffset); + flushEnd = Math.min(bufEnd, endOffset); + } + /* sometimes sourcebuffer.remove() does not flush + the exact expected time range. + to avoid rounding issues/infinite loop, + only flush buffer range of length greater than 500ms. + */ + if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) { + this.flushBufferCounter++; + logger["b" /* logger */].log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime); + sb.remove(flushStart, flushEnd); + return false; + } + } + } catch (e) { + logger["b" /* logger */].warn('exception while accessing sourcebuffer, it might have been removed from MediaSource'); + } + } else { + //logger.log('abort ' + type + ' append in progress'); + // this will abort any appending in progress + //sb.abort(); + logger["b" /* logger */].warn('cannot flush, sb updating in progress'); + return false; + } + } + } else { + logger["b" /* logger */].warn('abort flushing too many retries'); + } + logger["b" /* logger */].log('buffer flushed'); + } + // everything flushed ! + return true; + }; + + return BufferController; +}(event_handler); + +/* harmony default export */ var buffer_controller = (buffer_controller_BufferController); +// CONCATENATED MODULE: ./src/controller/cap-level-controller.js +var cap_level_controller__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; }; }(); + +function cap_level_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function cap_level_controller__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; } + +function cap_level_controller__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; } + +/* + * cap stream level to media size dimension controller +*/ + + + + +var cap_level_controller_CapLevelController = function (_EventHandler) { + cap_level_controller__inherits(CapLevelController, _EventHandler); + + function CapLevelController(hls) { + cap_level_controller__classCallCheck(this, CapLevelController); + + return cap_level_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FPS_DROP_LEVEL_CAPPING, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MANIFEST_PARSED)); + } + + CapLevelController.prototype.destroy = function destroy() { + if (this.hls.config.capLevelToPlayerSize) { + this.media = this.restrictedLevels = null; + this.autoLevelCapping = Number.POSITIVE_INFINITY; + if (this.timer) { + this.timer = clearInterval(this.timer); + } + } + }; + + CapLevelController.prototype.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) { + // Don't add a restricted level more than once + if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) { + this.restrictedLevels.push(data.droppedLevel); + } + }; + + CapLevelController.prototype.onMediaAttaching = function onMediaAttaching(data) { + this.media = data.media instanceof HTMLVideoElement ? data.media : null; + }; + + CapLevelController.prototype.onManifestParsed = function onManifestParsed(data) { + var hls = this.hls; + this.restrictedLevels = []; + if (hls.config.capLevelToPlayerSize) { + this.autoLevelCapping = Number.POSITIVE_INFINITY; + this.levels = data.levels; + hls.firstLevel = this.getMaxLevel(data.firstLevel); + clearInterval(this.timer); + this.timer = setInterval(this.detectPlayerSize.bind(this), 1000); + this.detectPlayerSize(); + } + }; + + CapLevelController.prototype.detectPlayerSize = function detectPlayerSize() { + if (this.media) { + var levelsLength = this.levels ? this.levels.length : 0; + if (levelsLength) { + var hls = this.hls; + hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1); + if (hls.autoLevelCapping > this.autoLevelCapping) { + // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch + // usually happen when the user go to the fullscreen mode. + hls.streamController.nextLevelSwitch(); + } + this.autoLevelCapping = hls.autoLevelCapping; + } + } + }; + + /* + * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled) + */ + + + CapLevelController.prototype.getMaxLevel = function getMaxLevel(capLevelIndex) { + var _this2 = this; + + if (!this.levels) { + return -1; + } + + var validLevels = this.levels.filter(function (level, index) { + return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex; + }); + + return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight); + }; + + CapLevelController.isLevelAllowed = function isLevelAllowed(level) { + var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + return restrictedLevels.indexOf(level) === -1; + }; + + CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) { + if (!levels || levels && !levels.length) { + return -1; + } + + // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next + // to determine whether we've chosen the greatest bandwidth for the media's dimensions + var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) { + if (!nextLevel) { + return true; + } + return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height; + }; + + // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to + // the max level + var maxLevelIndex = levels.length - 1; + + for (var i = 0; i < levels.length; i += 1) { + var level = levels[i]; + if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) { + maxLevelIndex = i; + break; + } + } + + return maxLevelIndex; + }; + + cap_level_controller__createClass(CapLevelController, [{ + key: 'mediaWidth', + get: function get() { + var width = void 0; + var media = this.media; + if (media) { + width = media.width || media.clientWidth || media.offsetWidth; + width *= CapLevelController.contentScaleFactor; + } + return width; + } + }, { + key: 'mediaHeight', + get: function get() { + var height = void 0; + var media = this.media; + if (media) { + height = media.height || media.clientHeight || media.offsetHeight; + height *= CapLevelController.contentScaleFactor; + } + return height; + } + }], [{ + key: 'contentScaleFactor', + get: function get() { + var pixelRatio = 1; + try { + pixelRatio = window.devicePixelRatio; + } catch (e) {} + return pixelRatio; + } + }]); + + return CapLevelController; +}(event_handler); + +/* harmony default export */ var cap_level_controller = (cap_level_controller_CapLevelController); +// CONCATENATED MODULE: ./src/controller/fps-controller.js +function fps_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function fps_controller__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; } + +function fps_controller__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; } + +/* + * FPS Controller +*/ + + + + + +var fps_controller_FPSController = function (_EventHandler) { + fps_controller__inherits(FPSController, _EventHandler); + + function FPSController(hls) { + fps_controller__classCallCheck(this, FPSController); + + return fps_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING)); + } + + FPSController.prototype.destroy = function destroy() { + if (this.timer) { + clearInterval(this.timer); + } + this.isVideoPlaybackQualityAvailable = false; + }; + + FPSController.prototype.onMediaAttaching = function onMediaAttaching(data) { + var config = this.hls.config; + if (config.capLevelOnFPSDrop) { + var video = this.video = data.media instanceof HTMLVideoElement ? data.media : null; + if (typeof video.getVideoPlaybackQuality === 'function') { + this.isVideoPlaybackQualityAvailable = true; + } + clearInterval(this.timer); + this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod); + } + }; + + FPSController.prototype.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) { + var currentTime = performance.now(); + if (decodedFrames) { + if (this.lastTime) { + var currentPeriod = currentTime - this.lastTime, + currentDropped = droppedFrames - this.lastDroppedFrames, + currentDecoded = decodedFrames - this.lastDecodedFrames, + droppedFPS = 1000 * currentDropped / currentPeriod, + hls = this.hls; + hls.trigger(events["a" /* default */].FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames }); + if (droppedFPS > 0) { + //logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod)); + if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) { + var currentLevel = hls.currentLevel; + logger["b" /* logger */].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel); + if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) { + currentLevel = currentLevel - 1; + hls.trigger(events["a" /* default */].FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel }); + hls.autoLevelCapping = currentLevel; + hls.streamController.nextLevelSwitch(); + } + } + } + } + this.lastTime = currentTime; + this.lastDroppedFrames = droppedFrames; + this.lastDecodedFrames = decodedFrames; + } + }; + + FPSController.prototype.checkFPSInterval = function checkFPSInterval() { + var video = this.video; + if (video) { + if (this.isVideoPlaybackQualityAvailable) { + var videoPlaybackQuality = video.getVideoPlaybackQuality(); + this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames); + } else { + this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount); + } + } + }; + + return FPSController; +}(event_handler); + +/* harmony default export */ var fps_controller = (fps_controller_FPSController); +// CONCATENATED MODULE: ./src/utils/xhr-loader.js +function xhr_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * XHR based logger +*/ + + + +var xhr_loader_XhrLoader = function () { + function XhrLoader(config) { + xhr_loader__classCallCheck(this, XhrLoader); + + if (config && config.xhrSetup) { + this.xhrSetup = config.xhrSetup; + } + } + + XhrLoader.prototype.destroy = function destroy() { + this.abort(); + this.loader = null; + }; + + XhrLoader.prototype.abort = function abort() { + var loader = this.loader; + if (loader && loader.readyState !== 4) { + this.stats.aborted = true; + loader.abort(); + } + + window.clearTimeout(this.requestTimeout); + this.requestTimeout = null; + window.clearTimeout(this.retryTimeout); + this.retryTimeout = null; + }; + + XhrLoader.prototype.load = function load(context, config, callbacks) { + this.context = context; + this.config = config; + this.callbacks = callbacks; + this.stats = { trequest: performance.now(), retry: 0 }; + this.retryDelay = config.retryDelay; + this.loadInternal(); + }; + + XhrLoader.prototype.loadInternal = function loadInternal() { + var xhr, + context = this.context; + xhr = this.loader = new XMLHttpRequest(); + + var stats = this.stats; + stats.tfirst = 0; + stats.loaded = 0; + var xhrSetup = this.xhrSetup; + + try { + if (xhrSetup) { + try { + xhrSetup(xhr, context.url); + } catch (e) { + // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");} + // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN + xhr.open('GET', context.url, true); + xhrSetup(xhr, context.url); + } + } + if (!xhr.readyState) { + xhr.open('GET', context.url, true); + } + } catch (e) { + // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS + this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr); + return; + } + + if (context.rangeEnd) { + xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1)); + } + xhr.onreadystatechange = this.readystatechange.bind(this); + xhr.onprogress = this.loadprogress.bind(this); + xhr.responseType = context.responseType; + + // setup timeout before we perform request + this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout); + xhr.send(); + }; + + XhrLoader.prototype.readystatechange = function readystatechange(event) { + var xhr = event.currentTarget, + readyState = xhr.readyState, + stats = this.stats, + context = this.context, + config = this.config; + + // don't proceed if xhr has been aborted + if (stats.aborted) { + return; + } + + // >= HEADERS_RECEIVED + if (readyState >= 2) { + // clear xhr timeout and rearm it if readyState less than 4 + window.clearTimeout(this.requestTimeout); + if (stats.tfirst === 0) { + stats.tfirst = Math.max(performance.now(), stats.trequest); + } + if (readyState === 4) { + var status = xhr.status; + // http status between 200 to 299 are all successful + if (status >= 200 && status < 300) { + stats.tload = Math.max(stats.tfirst, performance.now()); + var data = void 0, + len = void 0; + if (context.responseType === 'arraybuffer') { + data = xhr.response; + len = data.byteLength; + } else { + data = xhr.responseText; + len = data.length; + } + stats.loaded = stats.total = len; + var response = { url: xhr.responseURL, data: data }; + this.callbacks.onSuccess(response, stats, context, xhr); + } else { + // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error + if (stats.retry >= config.maxRetry || status >= 400 && status < 499) { + logger["b" /* logger */].error(status + ' while loading ' + context.url); + this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr); + } else { + // retry + logger["b" /* logger */].warn(status + ' while loading ' + context.url + ', retrying in ' + this.retryDelay + '...'); + // aborts and resets internal state + this.destroy(); + // schedule retry + this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay); + // set exponential backoff + this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay); + stats.retry++; + } + } + } else { + // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet + this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout); + } + } + }; + + XhrLoader.prototype.loadtimeout = function loadtimeout() { + logger["b" /* logger */].warn('timeout while loading ' + this.context.url); + this.callbacks.onTimeout(this.stats, this.context, null); + }; + + XhrLoader.prototype.loadprogress = function loadprogress(event) { + var xhr = event.currentTarget, + stats = this.stats; + + stats.loaded = event.loaded; + if (event.lengthComputable) { + stats.total = event.total; + } + var onProgress = this.callbacks.onProgress; + if (onProgress) { + // third arg is to provide on progress data + onProgress(stats, this.context, null, xhr); + } + }; + + return XhrLoader; +}(); + +/* harmony default export */ var xhr_loader = (xhr_loader_XhrLoader); +// CONCATENATED MODULE: ./src/controller/audio-track-controller.js +var audio_track_controller__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; }; }(); + +function audio_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function audio_track_controller__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; } + +function audio_track_controller__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; } + +/* + * audio track controller +*/ + + + + + + +var audio_track_controller_AudioTrackController = function (_EventHandler) { + audio_track_controller__inherits(AudioTrackController, _EventHandler); + + function AudioTrackController(hls) { + audio_track_controller__classCallCheck(this, AudioTrackController); + + var _this = audio_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].AUDIO_TRACK_LOADED, events["a" /* default */].ERROR)); + + _this.ticks = 0; + _this.ontick = _this.tick.bind(_this); + return _this; + } + + AudioTrackController.prototype.destroy = function destroy() { + this.cleanTimer(); + event_handler.prototype.destroy.call(this); + }; + + AudioTrackController.prototype.cleanTimer = function cleanTimer() { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + }; + + AudioTrackController.prototype.tick = function tick() { + this.ticks++; + if (this.ticks === 1) { + this.doTick(); + if (this.ticks > 1) { + setTimeout(this.tick, 1); + } + this.ticks = 0; + } + }; + + AudioTrackController.prototype.doTick = function doTick() { + this.updateTrack(this.trackId); + }; + + AudioTrackController.prototype.onError = function onError(data) { + if (data.fatal && data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) { + this.cleanTimer(); + } + }; + + AudioTrackController.prototype.onManifestLoading = function onManifestLoading() { + // reset audio tracks on manifest loading + this.tracks = []; + this.trackId = -1; + }; + + AudioTrackController.prototype.onManifestParsed = function onManifestParsed(data) { + var _this2 = this; + + var tracks = data.audioTracks || []; + var defaultFound = false; + this.tracks = tracks; + this.hls.trigger(events["a" /* default */].AUDIO_TRACKS_UPDATED, { audioTracks: tracks }); + // loop through available audio tracks and autoselect default if needed + var id = 0; + tracks.forEach(function (track) { + if (track.default && !defaultFound) { + _this2.audioTrack = id; + defaultFound = true; + return; + } + id++; + }); + if (defaultFound === false && tracks.length) { + logger["b" /* logger */].log('no default audio track defined, use first audio track as default'); + this.audioTrack = 0; + } + }; + + AudioTrackController.prototype.onAudioTrackLoaded = function onAudioTrackLoaded(data) { + if (data.id < this.tracks.length) { + logger["b" /* logger */].log('audioTrack ' + data.id + ' loaded'); + this.tracks[data.id].details = data.details; + // check if current playlist is a live playlist + if (data.details.live && !this.timer) { + // if live playlist we will have to reload it periodically + // set reload period to playlist target duration + this.timer = setInterval(this.ontick, 1000 * data.details.targetduration); + } + if (!data.details.live && this.timer) { + // playlist is not live and timer is armed : stopping it + this.cleanTimer(); + } + } + }; + + /** get alternate audio tracks list from playlist **/ + + + AudioTrackController.prototype.setAudioTrackInternal = function setAudioTrackInternal(newId) { + // check if level idx is valid + if (newId >= 0 && newId < this.tracks.length) { + // stopping live reloading timer if any + this.cleanTimer(); + this.trackId = newId; + logger["b" /* logger */].log('switching to audioTrack ' + newId); + var audioTrack = this.tracks[newId], + hls = this.hls, + type = audioTrack.type, + url = audioTrack.url, + eventObj = { id: newId, type: type, url: url }; + // keep AUDIO_TRACK_SWITCH for legacy reason + hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCH, eventObj); + hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHING, eventObj); + // check if we need to load playlist for this audio Track + var details = audioTrack.details; + if (url && (details === undefined || details.live === true)) { + // track not retrieved yet, or live playlist we need to (re)load it + logger["b" /* logger */].log('(re)loading playlist for audioTrack ' + newId); + hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADING, { url: url, id: newId }); + } + } + }; + + AudioTrackController.prototype.updateTrack = function updateTrack(newId) { + // check if level idx is valid + if (newId >= 0 && newId < this.tracks.length) { + // stopping live reloading timer if any + this.cleanTimer(); + this.trackId = newId; + logger["b" /* logger */].log('updating audioTrack ' + newId); + var audioTrack = this.tracks[newId], + url = audioTrack.url; + // check if we need to load playlist for this audio Track + var details = audioTrack.details; + if (url && (details === undefined || details.live === true)) { + // track not retrieved yet, or live playlist we need to (re)load it + logger["b" /* logger */].log('(re)loading playlist for audioTrack ' + newId); + this.hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADING, { url: url, id: newId }); + } + } + }; + + audio_track_controller__createClass(AudioTrackController, [{ + key: 'audioTracks', + get: function get() { + return this.tracks; + } + + /** get index of the selected audio track (index in audio track lists) **/ + + }, { + key: 'audioTrack', + get: function get() { + return this.trackId; + } + + /** select an audio track, based on its index in audio track lists**/ + , + set: function set(audioTrackId) { + if (this.trackId !== audioTrackId || this.tracks[audioTrackId].details === undefined) { + this.setAudioTrackInternal(audioTrackId); + } + } + }]); + + return AudioTrackController; +}(event_handler); + +/* harmony default export */ var audio_track_controller = (audio_track_controller_AudioTrackController); +// CONCATENATED MODULE: ./src/controller/audio-stream-controller.js +var audio_stream_controller__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; }; }(); + +function audio_stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function audio_stream_controller__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; } + +function audio_stream_controller__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; } + +/* + * Audio Stream Controller +*/ + + + + + + + + + + + +var audio_stream_controller_State = { + STOPPED: 'STOPPED', + STARTING: 'STARTING', + IDLE: 'IDLE', + PAUSED: 'PAUSED', + KEY_LOADING: 'KEY_LOADING', + FRAG_LOADING: 'FRAG_LOADING', + FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY', + WAITING_TRACK: 'WAITING_TRACK', + PARSING: 'PARSING', + PARSED: 'PARSED', + BUFFER_FLUSHING: 'BUFFER_FLUSHING', + ENDED: 'ENDED', + ERROR: 'ERROR', + WAITING_INIT_PTS: 'WAITING_INIT_PTS' +}; + +var audio_stream_controller_AudioStreamController = function (_EventHandler) { + audio_stream_controller__inherits(AudioStreamController, _EventHandler); + + function AudioStreamController(hls) { + audio_stream_controller__classCallCheck(this, AudioStreamController); + + var _this = audio_stream_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].AUDIO_TRACKS_UPDATED, events["a" /* default */].AUDIO_TRACK_SWITCHING, events["a" /* default */].AUDIO_TRACK_LOADED, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, events["a" /* default */].FRAG_PARSING_DATA, events["a" /* default */].FRAG_PARSED, events["a" /* default */].ERROR, events["a" /* default */].BUFFER_CREATED, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].BUFFER_FLUSHED, events["a" /* default */].INIT_PTS_FOUND)); + + _this.config = hls.config; + _this.audioCodecSwap = false; + _this.ticks = 0; + _this._state = audio_stream_controller_State.STOPPED; + _this.ontick = _this.tick.bind(_this); + _this.initPTS = []; + _this.waitingFragment = null; + _this.videoTrackCC = null; + return _this; + } + + AudioStreamController.prototype.destroy = function destroy() { + this.stopLoad(); + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + event_handler.prototype.destroy.call(this); + this.state = audio_stream_controller_State.STOPPED; + }; + + //Signal that video PTS was found + + + AudioStreamController.prototype.onInitPtsFound = function onInitPtsFound(data) { + var demuxerId = data.id, + cc = data.frag.cc, + initPTS = data.initPTS; + if (demuxerId === 'main') { + //Always update the new INIT PTS + //Can change due level switch + this.initPTS[cc] = initPTS; + this.videoTrackCC = cc; + logger["b" /* logger */].log('InitPTS for cc:' + cc + ' found from video track:' + initPTS); + + //If we are waiting we need to demux/remux the waiting frag + //With the new initPTS + if (this.state === audio_stream_controller_State.WAITING_INIT_PTS) { + this.tick(); + } + } + }; + + AudioStreamController.prototype.startLoad = function startLoad(startPosition) { + if (this.tracks) { + var lastCurrentTime = this.lastCurrentTime; + this.stopLoad(); + if (!this.timer) { + this.timer = setInterval(this.ontick, 100); + } + this.fragLoadError = 0; + if (lastCurrentTime > 0 && startPosition === -1) { + logger["b" /* logger */].log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3)); + this.state = audio_stream_controller_State.IDLE; + } else { + this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition; + this.state = audio_stream_controller_State.STARTING; + } + this.nextLoadPosition = this.startPosition = this.lastCurrentTime; + this.tick(); + } else { + this.startPosition = startPosition; + this.state = audio_stream_controller_State.STOPPED; + } + }; + + AudioStreamController.prototype.stopLoad = function stopLoad() { + var frag = this.fragCurrent; + if (frag) { + if (frag.loader) { + frag.loader.abort(); + } + this.fragCurrent = null; + } + this.fragPrevious = null; + if (this.demuxer) { + this.demuxer.destroy(); + this.demuxer = null; + } + this.state = audio_stream_controller_State.STOPPED; + }; + + AudioStreamController.prototype.tick = function tick() { + this.ticks++; + if (this.ticks === 1) { + this.doTick(); + if (this.ticks > 1) { + setTimeout(this.tick, 1); + } + this.ticks = 0; + } + }; + + AudioStreamController.prototype.doTick = function doTick() { + var pos, + track, + trackDetails, + hls = this.hls, + config = hls.config; + //logger.log('audioStream:' + this.state); + switch (this.state) { + case audio_stream_controller_State.ERROR: + //don't do anything in error state to avoid breaking further ... + case audio_stream_controller_State.PAUSED: + //don't do anything in paused state either ... + case audio_stream_controller_State.BUFFER_FLUSHING: + break; + case audio_stream_controller_State.STARTING: + this.state = audio_stream_controller_State.WAITING_TRACK; + this.loadedmetadata = false; + break; + case audio_stream_controller_State.IDLE: + var tracks = this.tracks; + // audio tracks not received => exit loop + if (!tracks) { + break; + } + // if video not attached AND + // start fragment already requested OR start frag prefetch disable + // exit loop + // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop + if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) { + break; + } + // determine next candidate fragment to be loaded, based on current position and + // end of buffer position + // if we have not yet loaded any fragment, start loading from start position + if (this.loadedmetadata) { + pos = this.media.currentTime; + } else { + pos = this.nextLoadPosition; + if (pos === undefined) { + break; + } + } + var media = this.mediaBuffer ? this.mediaBuffer : this.media, + videoBuffer = this.videoBuffer ? this.videoBuffer : this.media, + bufferInfo = buffer_helper.bufferInfo(media, pos, config.maxBufferHole), + mainBufferInfo = buffer_helper.bufferInfo(videoBuffer, pos, config.maxBufferHole), + bufferLen = bufferInfo.len, + bufferEnd = bufferInfo.end, + fragPrevious = this.fragPrevious, + + // ensure we buffer at least config.maxBufferLength (default 30s) + // once we reach that threshold, don't buffer more than video (mainBufferInfo.len) + maxBufLen = Math.max(config.maxBufferLength, mainBufferInfo.len), + audioSwitch = this.audioSwitch, + trackId = this.trackId; + + // if buffer length is less than maxBufLen try to load a new fragment + if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) { + trackDetails = tracks[trackId].details; + // if track info not retrieved yet, switch state and wait for track retrieval + if (typeof trackDetails === 'undefined') { + this.state = audio_stream_controller_State.WAITING_TRACK; + break; + } + + // we just got done loading the final fragment, check if we need to finalize media stream + if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN) { + // if we are not seeking or if we are seeking but everything (almost) til the end is buffered, let's signal eos + // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference when switching + // between different renditions. using half frag duration should help cope with these cases. + if (!this.media.seeking || this.media.duration - bufferEnd < fragPrevious.duration / 2) { + // Finalize the media stream + this.hls.trigger(events["a" /* default */].BUFFER_EOS, { type: 'audio' }); + this.state = audio_stream_controller_State.ENDED; + break; + } + } + + // find fragment index, contiguous with end of buffer position + var fragments = trackDetails.fragments, + fragLen = fragments.length, + start = fragments[0].start, + end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration, + frag = void 0; + + // When switching audio track, reload audio as close as possible to currentTime + if (audioSwitch) { + if (trackDetails.live && !trackDetails.PTSKnown) { + logger["b" /* logger */].log('switching audiotrack, live stream, unknown PTS,load first fragment'); + bufferEnd = 0; + } else { + bufferEnd = pos; + // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime + if (trackDetails.PTSKnown && pos < start) { + // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start + if (bufferInfo.end > start || bufferInfo.nextStart) { + logger["b" /* logger */].log('alt audio track ahead of main track, seek to start of alt audio track'); + this.media.currentTime = start + 0.05; + } else { + return; + } + } + } + } + if (trackDetails.initSegment && !trackDetails.initSegment.data) { + frag = trackDetails.initSegment; + } + // if bufferEnd before start of playlist, load first fragment + else if (bufferEnd <= start) { + frag = fragments[0]; + if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) { + // Ensure we find a fragment which matches the continuity of the video track + frag = findFragWithCC(fragments, this.videoTrackCC); + } + if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) { + // we just loaded this first fragment, and we are still lagging behind the start of the live playlist + // let's force seek to start + var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start; + logger["b" /* logger */].log('no alt audio available @currentTime:' + this.media.currentTime + ', seeking @' + (nextBuffered + 0.05)); + this.media.currentTime = nextBuffered + 0.05; + return; + } + } else { + var foundFrag = void 0; + var maxFragLookUpTolerance = config.maxFragLookUpTolerance; + var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined; + var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) { + // offset should be within fragment boundary - config.maxFragLookUpTolerance + // this is to cope with situations like + // bufferEnd = 9.991 + // frag[Ø] : [0,10] + // frag[1] : [10,20] + // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here + // frag start frag start+duration + // |-----------------------------| + // <---> <---> + // ...--------><-----------------------------><---------.... + // previous frag matching fragment next frag + // return -1 return 0 return 1 + //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`); + // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments + var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration); + if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) { + return 1; + } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element + else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { + return -1; + } + return 0; + }; + + if (bufferEnd < end) { + if (bufferEnd > end - maxFragLookUpTolerance) { + maxFragLookUpTolerance = 0; + } + // Prefer the next fragment if it's within tolerance + if (fragNext && !fragmentWithinToleranceTest(fragNext)) { + foundFrag = fragNext; + } else { + foundFrag = binary_search.search(fragments, fragmentWithinToleranceTest); + } + } else { + // reach end of playlist + foundFrag = fragments[fragLen - 1]; + } + if (foundFrag) { + frag = foundFrag; + start = foundFrag.start; + //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn); + if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) { + if (frag.sn < trackDetails.endSN) { + frag = fragments[frag.sn + 1 - trackDetails.startSN]; + logger["b" /* logger */].log('SN just loaded, load next one: ' + frag.sn); + } else { + frag = null; + } + } + } + } + if (frag) { + //logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3)); + if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) { + logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId); + this.state = audio_stream_controller_State.KEY_LOADING; + hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag }); + } else { + logger["b" /* logger */].log('Loading ' + frag.sn + ', cc: ' + frag.cc + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3)); + // ensure that we are not reloading the same fragments in loop ... + if (this.fragLoadIdx !== undefined) { + this.fragLoadIdx++; + } else { + this.fragLoadIdx = 0; + } + if (frag.loadCounter) { + frag.loadCounter++; + var maxThreshold = config.fragLoadingLoopThreshold; + // if this frag has already been loaded 3 times, and if it has been reloaded recently + if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) { + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag }); + return; + } + } else { + frag.loadCounter = 1; + } + frag.loadIdx = this.fragLoadIdx; + this.fragCurrent = frag; + this.startFragRequested = true; + if (!isNaN(frag.sn)) { + this.nextLoadPosition = frag.start + frag.duration; + } + hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag }); + this.state = audio_stream_controller_State.FRAG_LOADING; + } + } + } + break; + case audio_stream_controller_State.WAITING_TRACK: + track = this.tracks[this.trackId]; + // check if playlist is already loaded + if (track && track.details) { + this.state = audio_stream_controller_State.IDLE; + } + break; + case audio_stream_controller_State.FRAG_LOADING_WAITING_RETRY: + var now = performance.now(); + var retryDate = this.retryDate; + media = this.media; + var isSeeking = media && media.seeking; + // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading + if (!retryDate || now >= retryDate || isSeeking) { + logger["b" /* logger */].log('audioStreamController: retryDate reached, switch back to IDLE state'); + this.state = audio_stream_controller_State.IDLE; + } + break; + case audio_stream_controller_State.WAITING_INIT_PTS: + var videoTrackCC = this.videoTrackCC; + if (this.initPTS[videoTrackCC] === undefined) { + break; + } + + // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS + var waitingFrag = this.waitingFragment; + if (waitingFrag) { + var waitingFragCC = waitingFrag.frag.cc; + if (videoTrackCC !== waitingFragCC) { + track = this.tracks[this.trackId]; + if (track.details && track.details.live) { + logger["b" /* logger */].warn('Waiting fragment CC (' + waitingFragCC + ') does not match video track CC (' + videoTrackCC + ')'); + this.waitingFragment = null; + this.state = audio_stream_controller_State.IDLE; + } + } else { + this.state = audio_stream_controller_State.FRAG_LOADING; + this.onFragLoaded(this.waitingFragment); + this.waitingFragment = null; + } + } else { + this.state = audio_stream_controller_State.IDLE; + } + + break; + case audio_stream_controller_State.STOPPED: + case audio_stream_controller_State.FRAG_LOADING: + case audio_stream_controller_State.PARSING: + case audio_stream_controller_State.PARSED: + case audio_stream_controller_State.ENDED: + break; + default: + break; + } + }; + + AudioStreamController.prototype.onMediaAttached = function onMediaAttached(data) { + var media = this.media = this.mediaBuffer = data.media; + this.onvseeking = this.onMediaSeeking.bind(this); + this.onvended = this.onMediaEnded.bind(this); + media.addEventListener('seeking', this.onvseeking); + media.addEventListener('ended', this.onvended); + var config = this.config; + if (this.tracks && config.autoStartLoad) { + this.startLoad(config.startPosition); + } + }; + + AudioStreamController.prototype.onMediaDetaching = function onMediaDetaching() { + var media = this.media; + if (media && media.ended) { + logger["b" /* logger */].log('MSE detaching and video ended, reset startPosition'); + this.startPosition = this.lastCurrentTime = 0; + } + + // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery + var tracks = this.tracks; + if (tracks) { + // reset fragment load counter + tracks.forEach(function (track) { + if (track.details) { + track.details.fragments.forEach(function (fragment) { + fragment.loadCounter = undefined; + }); + } + }); + } + // remove video listeners + if (media) { + media.removeEventListener('seeking', this.onvseeking); + media.removeEventListener('ended', this.onvended); + this.onvseeking = this.onvseeked = this.onvended = null; + } + this.media = this.mediaBuffer = this.videoBuffer = null; + this.loadedmetadata = false; + this.stopLoad(); + }; + + AudioStreamController.prototype.onMediaSeeking = function onMediaSeeking() { + if (this.state === audio_stream_controller_State.ENDED) { + // switch to IDLE state to check for potential new fragment + this.state = audio_stream_controller_State.IDLE; + } + if (this.media) { + this.lastCurrentTime = this.media.currentTime; + } + // avoid reporting fragment loop loading error in case user is seeking several times on same position + if (this.fragLoadIdx !== undefined) { + this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; + } + // tick to speed up processing + this.tick(); + }; + + AudioStreamController.prototype.onMediaEnded = function onMediaEnded() { + // reset startPosition and lastCurrentTime to restart playback @ stream beginning + this.startPosition = this.lastCurrentTime = 0; + }; + + AudioStreamController.prototype.onAudioTracksUpdated = function onAudioTracksUpdated(data) { + logger["b" /* logger */].log('audio tracks updated'); + this.tracks = data.audioTracks; + }; + + AudioStreamController.prototype.onAudioTrackSwitching = function onAudioTrackSwitching(data) { + // if any URL found on new audio track, it is an alternate audio track + var altAudio = !!data.url; + this.trackId = data.id; + + this.fragCurrent = null; + this.state = audio_stream_controller_State.PAUSED; + this.waitingFragment = null; + // destroy useless demuxer when switching audio to main + if (!altAudio) { + if (this.demuxer) { + this.demuxer.destroy(); + this.demuxer = null; + } + } else { + // switching to audio track, start timer if not already started + if (!this.timer) { + this.timer = setInterval(this.ontick, 100); + } + } + + //should we switch tracks ? + if (altAudio) { + this.audioSwitch = true; + //main audio track are handled by stream-controller, just do something if switching to alt audio track + this.state = audio_stream_controller_State.IDLE; + // increase fragment load Index to avoid frag loop loading error after buffer flush + if (this.fragLoadIdx !== undefined) { + this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold; + } + } + this.tick(); + }; + + AudioStreamController.prototype.onAudioTrackLoaded = function onAudioTrackLoaded(data) { + var newDetails = data.details, + trackId = data.id, + track = this.tracks[trackId], + duration = newDetails.totalduration, + sliding = 0; + + logger["b" /* logger */].log('track ' + trackId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration); + + if (newDetails.live) { + var curDetails = track.details; + if (curDetails && newDetails.fragments.length > 0) { + // we already have details for that level, merge them + mergeDetails(curDetails, newDetails); + sliding = newDetails.fragments[0].start; + // TODO + //this.liveSyncPosition = this.computeLivePosition(sliding, curDetails); + if (newDetails.PTSKnown) { + logger["b" /* logger */].log('live audio playlist sliding:' + sliding.toFixed(3)); + } else { + logger["b" /* logger */].log('live audio playlist - outdated PTS, unknown sliding'); + } + } else { + newDetails.PTSKnown = false; + logger["b" /* logger */].log('live audio playlist - first load, unknown sliding'); + } + } else { + newDetails.PTSKnown = false; + } + track.details = newDetails; + + // compute start position + if (!this.startFragRequested) { + // compute start position if set to -1. use it straight away if value is defined + if (this.startPosition === -1) { + // first, check if start time offset has been set in playlist, if yes, use this value + var startTimeOffset = newDetails.startTimeOffset; + if (!isNaN(startTimeOffset)) { + logger["b" /* logger */].log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset); + this.startPosition = startTimeOffset; + } else { + this.startPosition = 0; + } + } + this.nextLoadPosition = this.startPosition; + } + // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment + if (this.state === audio_stream_controller_State.WAITING_TRACK) { + this.state = audio_stream_controller_State.IDLE; + } + //trigger handler right now + this.tick(); + }; + + AudioStreamController.prototype.onKeyLoaded = function onKeyLoaded() { + if (this.state === audio_stream_controller_State.KEY_LOADING) { + this.state = audio_stream_controller_State.IDLE; + this.tick(); + } + }; + + AudioStreamController.prototype.onFragLoaded = function onFragLoaded(data) { + var fragCurrent = this.fragCurrent, + fragLoaded = data.frag; + if (this.state === audio_stream_controller_State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) { + var track = this.tracks[this.trackId], + details = track.details, + duration = details.totalduration, + trackId = fragCurrent.level, + sn = fragCurrent.sn, + cc = fragCurrent.cc, + audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2', + stats = this.stats = data.stats; + if (sn === 'initSegment') { + this.state = audio_stream_controller_State.IDLE; + + stats.tparsed = stats.tbuffered = performance.now(); + details.initSegment.data = data.payload; + this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' }); + this.tick(); + } else { + this.state = audio_stream_controller_State.PARSING; + // transmux the MPEG-TS data to ISO-BMFF segments + this.appended = false; + if (!this.demuxer) { + this.demuxer = new demux_demuxer(this.hls, 'audio'); + } + //Check if we have video initPTS + // If not we need to wait for it + var initPTS = this.initPTS[cc]; + var initSegmentData = details.initSegment ? details.initSegment.data : []; + if (details.initSegment || initPTS !== undefined) { + this.pendingBuffering = true; + logger["b" /* logger */].log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId); + // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) + var accurateTimeOffset = false; //details.PTSKnown || !details.live; + this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS); + } else { + logger["b" /* logger */].log('unknown video PTS for continuity counter ' + cc + ', waiting for video PTS before demuxing audio frag ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId); + this.waitingFragment = data; + this.state = audio_stream_controller_State.WAITING_INIT_PTS; + } + } + } + this.fragLoadError = 0; + }; + + AudioStreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) { + var fragCurrent = this.fragCurrent; + var fragNew = data.frag; + if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) { + var tracks = data.tracks, + track = void 0; + + // delete any video track found on audio demuxer + if (tracks.video) { + delete tracks.video; + } + + // include levelCodec in audio and video tracks + track = tracks.audio; + if (track) { + track.levelCodec = track.codec; + track.id = data.id; + this.hls.trigger(events["a" /* default */].BUFFER_CODECS, tracks); + logger["b" /* logger */].log('audio track:audio,container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']'); + var initSegment = track.initSegment; + if (initSegment) { + var appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' }; + if (this.audioSwitch) { + this.pendingData = [appendObj]; + } else { + this.appended = true; + // arm pending Buffering flag before appending a segment + this.pendingBuffering = true; + this.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj); + } + } + //trigger handler right now + this.tick(); + } + } + }; + + AudioStreamController.prototype.onFragParsingData = function onFragParsingData(data) { + var _this2 = this; + + var fragCurrent = this.fragCurrent; + var fragNew = data.frag; + if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) { + var trackId = this.trackId, + track = this.tracks[trackId], + hls = this.hls; + + if (isNaN(data.endPTS)) { + data.endPTS = data.startPTS + fragCurrent.duration; + data.endDTS = data.startDTS + fragCurrent.duration; + } + + logger["b" /* 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); + updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS); + + var audioSwitch = this.audioSwitch, + media = this.media, + appendOnBufferFlush = false; + //Only flush audio from old audio tracks when PTS is known on new audio track + if (audioSwitch && media) { + if (media.readyState) { + var currentTime = media.currentTime; + logger["b" /* logger */].log('switching audio track : currentTime:' + currentTime); + if (currentTime >= data.startPTS) { + logger["b" /* logger */].log('switching audio track : flushing all audio'); + this.state = audio_stream_controller_State.BUFFER_FLUSHING; + hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); + appendOnBufferFlush = true; + //Lets announce that the initial audio track switch flush occur + this.audioSwitch = false; + hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId }); + } + } else { + //Lets announce that the initial audio track switch flush occur + this.audioSwitch = false; + hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId }); + } + } + + var pendingData = this.pendingData; + if (!this.audioSwitch) { + [data.data1, data.data2].forEach(function (buffer) { + if (buffer && buffer.length) { + pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' }); + } + }); + if (!appendOnBufferFlush && pendingData.length) { + pendingData.forEach(function (appendObj) { + // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending) + // in that case it is useless to append following segments + if (_this2.state === audio_stream_controller_State.PARSING) { + // arm pending Buffering flag before appending a segment + _this2.pendingBuffering = true; + _this2.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj); + } + }); + this.pendingData = []; + this.appended = true; + } + } + //trigger handler right now + this.tick(); + } + }; + + AudioStreamController.prototype.onFragParsed = function onFragParsed(data) { + var fragCurrent = this.fragCurrent; + var fragNew = data.frag; + if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) { + this.stats.tparsed = performance.now(); + this.state = audio_stream_controller_State.PARSED; + this._checkAppendedParsed(); + } + }; + + AudioStreamController.prototype.onBufferCreated = function onBufferCreated(data) { + var audioTrack = data.tracks.audio; + if (audioTrack) { + this.mediaBuffer = audioTrack.buffer; + this.loadedmetadata = true; + } + if (data.tracks.video) { + this.videoBuffer = data.tracks.video.buffer; + } + }; + + AudioStreamController.prototype.onBufferAppended = function onBufferAppended(data) { + if (data.parent === 'audio') { + var state = this.state; + if (state === audio_stream_controller_State.PARSING || state === audio_stream_controller_State.PARSED) { + // check if all buffers have been appended + this.pendingBuffering = data.pending > 0; + this._checkAppendedParsed(); + } + } + }; + + AudioStreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() { + //trigger handler right now + if (this.state === audio_stream_controller_State.PARSED && (!this.appended || !this.pendingBuffering)) { + var frag = this.fragCurrent, + stats = this.stats, + hls = this.hls; + if (frag) { + this.fragPrevious = frag; + stats.tbuffered = performance.now(); + hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' }); + var media = this.mediaBuffer ? this.mediaBuffer : this.media; + logger["b" /* logger */].log('audio buffered : ' + timeRanges.toString(media.buffered)); + if (this.audioSwitch && this.appended) { + this.audioSwitch = false; + hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: this.trackId }); + } + this.state = audio_stream_controller_State.IDLE; + } + this.tick(); + } + }; + + AudioStreamController.prototype.onError = function onError(data) { + var frag = data.frag; + // don't handle frag error not related to audio fragment + if (frag && frag.type !== 'audio') { + return; + } + switch (data.details) { + case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR: + case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT: + if (!data.fatal) { + var loadError = this.fragLoadError; + if (loadError) { + loadError++; + } else { + loadError = 1; + } + var config = this.config; + if (loadError <= config.fragLoadingMaxRetry) { + this.fragLoadError = loadError; + // reset load counter to avoid frag loop loading error + frag.loadCounter = 0; + // exponential backoff capped to config.fragLoadingMaxRetryTimeout + var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout); + logger["b" /* logger */].warn('audioStreamController: frag loading failed, retry in ' + delay + ' ms'); + this.retryDate = performance.now() + delay; + // retry loading state + this.state = audio_stream_controller_State.FRAG_LOADING_WAITING_RETRY; + } else { + logger["b" /* logger */].error('audioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...'); + // switch error to fatal + data.fatal = true; + this.state = audio_stream_controller_State.ERROR; + } + } + break; + case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR: + case errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR: + case errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT: + case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR: + case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT: + // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received + if (this.state !== audio_stream_controller_State.ERROR) { + // if fatal error, stop processing, otherwise move to IDLE to retry loading + this.state = data.fatal ? audio_stream_controller_State.ERROR : audio_stream_controller_State.IDLE; + logger["b" /* logger */].warn('audioStreamController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...'); + } + break; + case errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR: + // if in appending state + if (data.parent === 'audio' && (this.state === audio_stream_controller_State.PARSING || this.state === audio_stream_controller_State.PARSED)) { + var media = this.mediaBuffer, + currentTime = this.media.currentTime, + mediaBuffered = media && buffer_helper.isBuffered(media, currentTime) && buffer_helper.isBuffered(media, currentTime + 0.5); + // reduce max buf len if current position is buffered + if (mediaBuffered) { + var _config = this.config; + if (_config.maxMaxBufferLength >= _config.maxBufferLength) { + // reduce max buffer length as it might be too high. we do this to avoid loop flushing ... + _config.maxMaxBufferLength /= 2; + logger["b" /* logger */].warn('audio:reduce max buffer length to ' + _config.maxMaxBufferLength + 's'); + // increase fragment load Index to avoid frag loop loading error after buffer flush + this.fragLoadIdx += 2 * _config.fragLoadingLoopThreshold; + } + this.state = audio_stream_controller_State.IDLE; + } else { + // current position is not buffered, but browser is still complaining about buffer full error + // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708 + // in that case flush the whole audio buffer to recover + logger["b" /* logger */].warn('buffer full error also media.currentTime is not buffered, flush audio buffer'); + this.fragCurrent = null; + // flush everything + this.state = audio_stream_controller_State.BUFFER_FLUSHING; + this.hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' }); + } + } + break; + default: + break; + } + }; + + AudioStreamController.prototype.onBufferFlushed = function onBufferFlushed() { + var _this3 = this; + + var pendingData = this.pendingData; + if (pendingData && pendingData.length) { + logger["b" /* logger */].log('appending pending audio data on Buffer Flushed'); + pendingData.forEach(function (appendObj) { + _this3.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj); + }); + this.appended = true; + this.pendingData = []; + this.state = audio_stream_controller_State.PARSED; + } else { + // move to IDLE once flush complete. this should trigger new fragment loading + this.state = audio_stream_controller_State.IDLE; + // reset reference to frag + this.fragPrevious = null; + this.tick(); + } + }; + + audio_stream_controller__createClass(AudioStreamController, [{ + key: 'state', + set: function set(nextState) { + if (this.state !== nextState) { + var previousState = this.state; + this._state = nextState; + logger["b" /* logger */].log('audio stream:' + previousState + '->' + nextState); + } + }, + get: function get() { + return this._state; + } + }]); + + return AudioStreamController; +}(event_handler); + +/* harmony default export */ var audio_stream_controller = (audio_stream_controller_AudioStreamController); +// CONCATENATED MODULE: ./src/utils/vttcue.js +/** + * Copyright 2013 vtt.js Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* harmony default export */ var vttcue = ((function () { + if (typeof window !== 'undefined' && window.VTTCue) { + return window.VTTCue; + } + + var autoKeyword = 'auto'; + var directionSetting = { + '': true, + lr: true, + rl: true + }; + var alignSetting = { + start: true, + middle: true, + end: true, + left: true, + right: true + }; + + function findDirectionSetting(value) { + if (typeof value !== 'string') { + return false; + } + var dir = directionSetting[value.toLowerCase()]; + return dir ? value.toLowerCase() : false; + } + + function findAlignSetting(value) { + if (typeof value !== 'string') { + return false; + } + var align = alignSetting[value.toLowerCase()]; + return align ? value.toLowerCase() : false; + } + + function extend(obj) { + var i = 1; + for (; i < arguments.length; i++) { + var cobj = arguments[i]; + for (var p in cobj) { + obj[p] = cobj[p]; + } + } + + return obj; + } + + function VTTCue(startTime, endTime, text) { + var cue = this; + var isIE8 = function () { + if (typeof navigator === 'undefined') { + return; + } + return (/MSIE\s8\.0/.test(navigator.userAgent) + ); + }(); + var baseObj = {}; + + if (isIE8) { + cue = document.createElement('custom'); + } else { + baseObj.enumerable = true; + } + + /** + * Shim implementation specific properties. These properties are not in + * the spec. + */ + + // Lets us know when the VTTCue's data has changed in such a way that we need + // to recompute its display state. This lets us compute its display state + // lazily. + cue.hasBeenReset = false; + + /** + * VTTCue and TextTrackCue properties + * http://dev.w3.org/html5/webvtt/#vttcue-interface + */ + + var _id = ''; + var _pauseOnExit = false; + var _startTime = startTime; + var _endTime = endTime; + var _text = text; + var _region = null; + var _vertical = ''; + var _snapToLines = true; + var _line = 'auto'; + var _lineAlign = 'start'; + var _position = 50; + var _positionAlign = 'middle'; + var _size = 50; + var _align = 'middle'; + + Object.defineProperty(cue, 'id', extend({}, baseObj, { + get: function get() { + return _id; + }, + set: function set(value) { + _id = '' + value; + } + })); + + Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, { + get: function get() { + return _pauseOnExit; + }, + set: function set(value) { + _pauseOnExit = !!value; + } + })); + + Object.defineProperty(cue, 'startTime', extend({}, baseObj, { + get: function get() { + return _startTime; + }, + set: function set(value) { + if (typeof value !== 'number') { + throw new TypeError('Start time must be set to a number.'); + } + _startTime = value; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'endTime', extend({}, baseObj, { + get: function get() { + return _endTime; + }, + set: function set(value) { + if (typeof value !== 'number') { + throw new TypeError('End time must be set to a number.'); + } + _endTime = value; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'text', extend({}, baseObj, { + get: function get() { + return _text; + }, + set: function set(value) { + _text = '' + value; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'region', extend({}, baseObj, { + get: function get() { + return _region; + }, + set: function set(value) { + _region = value; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'vertical', extend({}, baseObj, { + get: function get() { + return _vertical; + }, + set: function set(value) { + var setting = findDirectionSetting(value); + // Have to check for false because the setting an be an empty string. + if (setting === false) { + throw new SyntaxError('An invalid or illegal string was specified.'); + } + _vertical = setting; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, { + get: function get() { + return _snapToLines; + }, + set: function set(value) { + _snapToLines = !!value; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'line', extend({}, baseObj, { + get: function get() { + return _line; + }, + set: function set(value) { + if (typeof value !== 'number' && value !== autoKeyword) { + throw new SyntaxError('An invalid number or illegal string was specified.'); + } + _line = value; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, { + get: function get() { + return _lineAlign; + }, + set: function set(value) { + var setting = findAlignSetting(value); + if (!setting) { + throw new SyntaxError('An invalid or illegal string was specified.'); + } + _lineAlign = setting; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'position', extend({}, baseObj, { + get: function get() { + return _position; + }, + set: function set(value) { + if (value < 0 || value > 100) { + throw new Error('Position must be between 0 and 100.'); + } + _position = value; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, { + get: function get() { + return _positionAlign; + }, + set: function set(value) { + var setting = findAlignSetting(value); + if (!setting) { + throw new SyntaxError('An invalid or illegal string was specified.'); + } + _positionAlign = setting; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'size', extend({}, baseObj, { + get: function get() { + return _size; + }, + set: function set(value) { + if (value < 0 || value > 100) { + throw new Error('Size must be between 0 and 100.'); + } + _size = value; + this.hasBeenReset = true; + } + })); + + Object.defineProperty(cue, 'align', extend({}, baseObj, { + get: function get() { + return _align; + }, + set: function set(value) { + var setting = findAlignSetting(value); + if (!setting) { + throw new SyntaxError('An invalid or illegal string was specified.'); + } + _align = setting; + this.hasBeenReset = true; + } + })); + + /** + * Other <track> spec defined properties + */ + + // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state + cue.displayState = undefined; + + if (isIE8) { + return cue; + } + } + + /** + * VTTCue methods + */ + + VTTCue.prototype.getCueAsHTML = function () { + // Assume WebVTT.convertCueToDOMTree is on the global. + var WebVTT = window.WebVTT; + return WebVTT.convertCueToDOMTree(window, this.text); + }; + + return VTTCue; +})()); +// CONCATENATED MODULE: ./src/utils/vttparser.js +/* + * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716 + */ + + + +var StringDecoder = function StringDecoder() { + return { + decode: function decode(data) { + if (!data) { + return ''; + } + if (typeof data !== 'string') { + throw new Error('Error - expected string data.'); + } + return decodeURIComponent(encodeURIComponent(data)); + } + }; +}; + +function VTTParser() { + this.window = window; + this.state = 'INITIAL'; + this.buffer = ''; + this.decoder = new StringDecoder(); + this.regionList = []; +} + +// Try to parse input as a time stamp. +function parseTimeStamp(input) { + + function computeSeconds(h, m, s, f) { + return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; + } + + var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); + if (!m) { + return null; + } + + if (m[3]) { + // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] + return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]); + } else if (m[1] > 59) { + // Timestamp takes the form of [hours]:[minutes].[milliseconds] + // First position is hours as it's over 59. + return computeSeconds(m[1], m[2], 0, m[4]); + } else { + // Timestamp takes the form of [minutes]:[seconds].[milliseconds] + return computeSeconds(0, m[1], m[2], m[4]); + } +} + +// A settings object holds key/value pairs and will ignore anything but the first +// assignment to a specific key. +function Settings() { + this.values = Object.create(null); +} + +Settings.prototype = { + // Only accept the first assignment to any key. + set: function set(k, v) { + if (!this.get(k) && v !== '') { + this.values[k] = v; + } + }, + // Return the value for a key, or a default value. + // If 'defaultKey' is passed then 'dflt' is assumed to be an object with + // a number of possible default values as properties where 'defaultKey' is + // the key of the property that will be chosen; otherwise it's assumed to be + // a single value. + get: function get(k, dflt, defaultKey) { + if (defaultKey) { + return this.has(k) ? this.values[k] : dflt[defaultKey]; + } + return this.has(k) ? this.values[k] : dflt; + }, + // Check whether we have a value for a key. + has: function has(k) { + return k in this.values; + }, + // Accept a setting if its one of the given alternatives. + alt: function alt(k, v, a) { + for (var n = 0; n < a.length; ++n) { + if (v === a[n]) { + this.set(k, v); + break; + } + } + }, + // Accept a setting if its a valid (signed) integer. + integer: function integer(k, v) { + if (/^-?\d+$/.test(v)) { + // integer + this.set(k, parseInt(v, 10)); + } + }, + // Accept a setting if its a valid percentage. + percent: function percent(k, v) { + var m; + if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) { + v = parseFloat(v); + if (v >= 0 && v <= 100) { + this.set(k, v); + return true; + } + } + return false; + } +}; + +// Helper function to parse input into groups separated by 'groupDelim', and +// interprete each group as a key/value pair separated by 'keyValueDelim'. +function parseOptions(input, callback, keyValueDelim, groupDelim) { + var groups = groupDelim ? input.split(groupDelim) : [input]; + for (var i in groups) { + if (typeof groups[i] !== 'string') { + continue; + } + var kv = groups[i].split(keyValueDelim); + if (kv.length !== 2) { + continue; + } + var k = kv[0]; + var v = kv[1]; + callback(k, v); + } +} + +var defaults = new vttcue(0, 0, 0); +// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244 +// Safari doesn't yet support this change, but FF and Chrome do. +var center = defaults.align === 'middle' ? 'middle' : 'center'; + +function parseCue(input, cue, regionList) { + // Remember the original input if we need to throw an error. + var oInput = input; + // 4.1 WebVTT timestamp + function consumeTimeStamp() { + var ts = parseTimeStamp(input); + if (ts === null) { + throw new Error('Malformed timestamp: ' + oInput); + } + // Remove time stamp from input. + input = input.replace(/^[^\sa-zA-Z-]+/, ''); + return ts; + } + + // 4.4.2 WebVTT cue settings + function consumeCueSettings(input, cue) { + var settings = new Settings(); + + parseOptions(input, function (k, v) { + switch (k) { + case 'region': + // Find the last region we parsed with the same region id. + for (var i = regionList.length - 1; i >= 0; i--) { + if (regionList[i].id === v) { + settings.set(k, regionList[i].region); + break; + } + } + break; + case 'vertical': + settings.alt(k, v, ['rl', 'lr']); + break; + case 'line': + var vals = v.split(','), + vals0 = vals[0]; + settings.integer(k, vals0); + if (settings.percent(k, vals0)) { + settings.set('snapToLines', false); + } + settings.alt(k, vals0, ['auto']); + if (vals.length === 2) { + settings.alt('lineAlign', vals[1], ['start', center, 'end']); + } + break; + case 'position': + vals = v.split(','); + settings.percent(k, vals[0]); + if (vals.length === 2) { + settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']); + } + break; + case 'size': + settings.percent(k, v); + break; + case 'align': + settings.alt(k, v, ['start', center, 'end', 'left', 'right']); + break; + } + }, /:/, /\s/); + + // Apply default values for any missing fields. + cue.region = settings.get('region', null); + cue.vertical = settings.get('vertical', ''); + var line = settings.get('line', 'auto'); + if (line === 'auto' && defaults.line === -1) { + // set numeric line number for Safari + line = -1; + } + cue.line = line; + cue.lineAlign = settings.get('lineAlign', 'start'); + cue.snapToLines = settings.get('snapToLines', true); + cue.size = settings.get('size', 100); + cue.align = settings.get('align', center); + var position = settings.get('position', 'auto'); + if (position === 'auto' && defaults.position === 50) { + // set numeric position for Safari + position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50; + } + cue.position = position; + } + + function skipWhitespace() { + input = input.replace(/^\s+/, ''); + } + + // 4.1 WebVTT cue timings. + skipWhitespace(); + cue.startTime = consumeTimeStamp(); // (1) collect cue start time + skipWhitespace(); + if (input.substr(0, 3) !== '-->') { + // (3) next characters must match '-->' + throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput); + } + input = input.substr(3); + skipWhitespace(); + cue.endTime = consumeTimeStamp(); // (5) collect cue end time + + // 4.1 WebVTT cue settings list. + skipWhitespace(); + consumeCueSettings(input, cue); +} + +function fixLineBreaks(input) { + return input.replace(/<br(?: \/)?>/gi, '\n'); +} + +VTTParser.prototype = { + parse: function parse(data) { + var self = this; + + // If there is no data then we won't decode it, but will just try to parse + // whatever is in buffer already. This may occur in circumstances, for + // example when flush() is called. + if (data) { + // Try to decode the data that we received. + self.buffer += self.decoder.decode(data, { stream: true }); + } + + function collectNextLine() { + var buffer = self.buffer; + var pos = 0; + + buffer = fixLineBreaks(buffer); + + while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { + ++pos; + } + var line = buffer.substr(0, pos); + // Advance the buffer early in case we fail below. + if (buffer[pos] === '\r') { + ++pos; + } + if (buffer[pos] === '\n') { + ++pos; + } + self.buffer = buffer.substr(pos); + return line; + } + + // 3.2 WebVTT metadata header syntax + function parseHeader(input) { + parseOptions(input, function (k, v) { + switch (k) { + case 'Region': + // 3.3 WebVTT region metadata header syntax + console.log('parse region', v); + //parseRegion(v); + break; + } + }, /:/); + } + + // 5.1 WebVTT file parsing. + try { + var line; + if (self.state === 'INITIAL') { + // We can't start parsing until we have the first line. + if (!/\r\n|\n/.test(self.buffer)) { + return this; + } + + line = collectNextLine(); + // strip of UTF-8 BOM if any + // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8 + var m = line.match(/^()?WEBVTT([ \t].*)?$/); + if (!m || !m[0]) { + throw new Error('Malformed WebVTT signature.'); + } + + self.state = 'HEADER'; + } + + var alreadyCollectedLine = false; + while (self.buffer) { + // We can't parse a line until we have the full line. + if (!/\r\n|\n/.test(self.buffer)) { + return this; + } + + if (!alreadyCollectedLine) { + line = collectNextLine(); + } else { + alreadyCollectedLine = false; + } + + switch (self.state) { + case 'HEADER': + // 13-18 - Allow a header (metadata) under the WEBVTT line. + if (/:/.test(line)) { + parseHeader(line); + } else if (!line) { + // An empty line terminates the header and starts the body (cues). + self.state = 'ID'; + } + continue; + case 'NOTE': + // Ignore NOTE blocks. + if (!line) { + self.state = 'ID'; + } + continue; + case 'ID': + // Check for the start of NOTE blocks. + if (/^NOTE($|[ \t])/.test(line)) { + self.state = 'NOTE'; + break; + } + // 19-29 - Allow any number of line terminators, then initialize new cue values. + if (!line) { + continue; + } + self.cue = new vttcue(0, 0, ''); + self.state = 'CUE'; + // 30-39 - Check if self line contains an optional identifier or timing data. + if (line.indexOf('-->') === -1) { + self.cue.id = line; + continue; + } + // Process line as start of a cue. + /*falls through*/ + case 'CUE': + // 40 - Collect cue timings and settings. + try { + parseCue(line, self.cue, self.regionList); + } catch (e) { + // In case of an error ignore rest of the cue. + self.cue = null; + self.state = 'BADCUE'; + continue; + } + self.state = 'CUETEXT'; + continue; + case 'CUETEXT': + var hasSubstring = line.indexOf('-->') !== -1; + // 34 - If we have an empty line then report the cue. + // 35 - If we have the special substring '-->' then report the cue, + // but do not collect the line as we need to process the current + // one as a new cue. + if (!line || hasSubstring && (alreadyCollectedLine = true)) { + // We are done parsing self cue. + if (self.oncue) { + self.oncue(self.cue); + } + self.cue = null; + self.state = 'ID'; + continue; + } + if (self.cue.text) { + self.cue.text += '\n'; + } + self.cue.text += line; + continue; + case 'BADCUE': + // BADCUE + // 54-62 - Collect and discard the remaining cue. + if (!line) { + self.state = 'ID'; + } + continue; + } + } + } catch (e) { + + // If we are currently parsing a cue, report what we have. + if (self.state === 'CUETEXT' && self.cue && self.oncue) { + self.oncue(self.cue); + } + self.cue = null; + // Enter BADWEBVTT state if header was not parsed correctly otherwise + // another exception occurred so enter BADCUE state. + self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE'; + } + return this; + }, + flush: function flush() { + var self = this; + try { + // Finish decoding the stream. + self.buffer += self.decoder.decode(); + // Synthesize the end of the current cue or region. + if (self.cue || self.state === 'HEADER') { + self.buffer += '\n\n'; + self.parse(); + } + // If we've flushed, parsed, and we're still on the INITIAL state then + // that means we don't have enough of the stream to parse the first + // line. + if (self.state === 'INITIAL') { + throw new Error('Malformed WebVTT signature.'); + } + } catch (e) { + throw e; + } + if (self.onflush) { + self.onflush(); + } + return this; + } +}; + + + +/* harmony default export */ var vttparser = (VTTParser); +// CONCATENATED MODULE: ./src/utils/cues.js + + +function newCue(track, startTime, endTime, captionScreen) { + var row; + var cue; + var indenting; + var indent; + var text; + var VTTCue = window.VTTCue || window.TextTrackCue; + + for (var r = 0; r < captionScreen.rows.length; r++) { + row = captionScreen.rows[r]; + indenting = true; + indent = 0; + text = ''; + + if (!row.isEmpty()) { + for (var c = 0; c < row.chars.length; c++) { + if (row.chars[c].uchar.match(/\s/) && indenting) { + indent++; + } else { + text += row.chars[c].uchar; + indenting = false; + } + } + //To be used for cleaning-up orphaned roll-up captions + row.cueStartTime = startTime; + + // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE + if (startTime === endTime) { + endTime += 0.0001; + } + + cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim())); + + if (indent >= 16) { + indent--; + } else { + indent++; + } + + // VTTCue.line get's flakey when using controls, so let's now include line 13&14 + // also, drop line 1 since it's to close to the top + if (navigator.userAgent.match(/Firefox\//)) { + cue.line = r + 1; + } else { + cue.line = r > 7 ? r - 2 : r + 1; + } + cue.align = 'left'; + // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break + cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0))); + track.addCue(cue); + } + } +} +// CONCATENATED MODULE: ./src/utils/cea-608-parser.js +function cea_608_parser__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * + * This code was ported from the dash.js project at: + * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js + * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2 + * + * The original copyright appears below: + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and contributor + * rights, including patent rights, and no such rights are granted under this license. + * + * Copyright (c) 2015-2016, DASH Industry Forum. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * 2. Neither the name of Dash Industry Forum nor the names of its + * contributors may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +/** + * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes + */ + +var specialCea608CharsCodes = { + 0x2a: 0xe1, // lowercase a, acute accent + 0x5c: 0xe9, // lowercase e, acute accent + 0x5e: 0xed, // lowercase i, acute accent + 0x5f: 0xf3, // lowercase o, acute accent + 0x60: 0xfa, // lowercase u, acute accent + 0x7b: 0xe7, // lowercase c with cedilla + 0x7c: 0xf7, // division symbol + 0x7d: 0xd1, // uppercase N tilde + 0x7e: 0xf1, // lowercase n tilde + 0x7f: 0x2588, // Full block + // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS + // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F + // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES + 0x80: 0xae, // Registered symbol (R) + 0x81: 0xb0, // degree sign + 0x82: 0xbd, // 1/2 symbol + 0x83: 0xbf, // Inverted (open) question mark + 0x84: 0x2122, // Trademark symbol (TM) + 0x85: 0xa2, // Cents symbol + 0x86: 0xa3, // Pounds sterling + 0x87: 0x266a, // Music 8'th note + 0x88: 0xe0, // lowercase a, grave accent + 0x89: 0x20, // transparent space (regular) + 0x8a: 0xe8, // lowercase e, grave accent + 0x8b: 0xe2, // lowercase a, circumflex accent + 0x8c: 0xea, // lowercase e, circumflex accent + 0x8d: 0xee, // lowercase i, circumflex accent + 0x8e: 0xf4, // lowercase o, circumflex accent + 0x8f: 0xfb, // lowercase u, circumflex accent + // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS + // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F + 0x90: 0xc1, // capital letter A with acute + 0x91: 0xc9, // capital letter E with acute + 0x92: 0xd3, // capital letter O with acute + 0x93: 0xda, // capital letter U with acute + 0x94: 0xdc, // capital letter U with diaresis + 0x95: 0xfc, // lowercase letter U with diaeresis + 0x96: 0x2018, // opening single quote + 0x97: 0xa1, // inverted exclamation mark + 0x98: 0x2a, // asterisk + 0x99: 0x2019, // closing single quote + 0x9a: 0x2501, // box drawings heavy horizontal + 0x9b: 0xa9, // copyright sign + 0x9c: 0x2120, // Service mark + 0x9d: 0x2022, // (round) bullet + 0x9e: 0x201c, // Left double quotation mark + 0x9f: 0x201d, // Right double quotation mark + 0xa0: 0xc0, // uppercase A, grave accent + 0xa1: 0xc2, // uppercase A, circumflex + 0xa2: 0xc7, // uppercase C with cedilla + 0xa3: 0xc8, // uppercase E, grave accent + 0xa4: 0xca, // uppercase E, circumflex + 0xa5: 0xcb, // capital letter E with diaresis + 0xa6: 0xeb, // lowercase letter e with diaresis + 0xa7: 0xce, // uppercase I, circumflex + 0xa8: 0xcf, // uppercase I, with diaresis + 0xa9: 0xef, // lowercase i, with diaresis + 0xaa: 0xd4, // uppercase O, circumflex + 0xab: 0xd9, // uppercase U, grave accent + 0xac: 0xf9, // lowercase u, grave accent + 0xad: 0xdb, // uppercase U, circumflex + 0xae: 0xab, // left-pointing double angle quotation mark + 0xaf: 0xbb, // right-pointing double angle quotation mark + // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS + // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F + 0xb0: 0xc3, // Uppercase A, tilde + 0xb1: 0xe3, // Lowercase a, tilde + 0xb2: 0xcd, // Uppercase I, acute accent + 0xb3: 0xcc, // Uppercase I, grave accent + 0xb4: 0xec, // Lowercase i, grave accent + 0xb5: 0xd2, // Uppercase O, grave accent + 0xb6: 0xf2, // Lowercase o, grave accent + 0xb7: 0xd5, // Uppercase O, tilde + 0xb8: 0xf5, // Lowercase o, tilde + 0xb9: 0x7b, // Open curly brace + 0xba: 0x7d, // Closing curly brace + 0xbb: 0x5c, // Backslash + 0xbc: 0x5e, // Caret + 0xbd: 0x5f, // Underscore + 0xbe: 0x7c, // Pipe (vertical line) + 0xbf: 0x223c, // Tilde operator + 0xc0: 0xc4, // Uppercase A, umlaut + 0xc1: 0xe4, // Lowercase A, umlaut + 0xc2: 0xd6, // Uppercase O, umlaut + 0xc3: 0xf6, // Lowercase o, umlaut + 0xc4: 0xdf, // Esszett (sharp S) + 0xc5: 0xa5, // Yen symbol + 0xc6: 0xa4, // Generic currency sign + 0xc7: 0x2503, // Box drawings heavy vertical + 0xc8: 0xc5, // Uppercase A, ring + 0xc9: 0xe5, // Lowercase A, ring + 0xca: 0xd8, // Uppercase O, stroke + 0xcb: 0xf8, // Lowercase o, strok + 0xcc: 0x250f, // Box drawings heavy down and right + 0xcd: 0x2513, // Box drawings heavy down and left + 0xce: 0x2517, // Box drawings heavy up and right + 0xcf: 0x251b // Box drawings heavy up and left +}; + +/** + * Utils + */ +var getCharForByte = function getCharForByte(byte) { + var charCode = byte; + if (specialCea608CharsCodes.hasOwnProperty(byte)) { + charCode = specialCea608CharsCodes[byte]; + } + return String.fromCharCode(charCode); +}; + +var NR_ROWS = 15, + NR_COLS = 100; +// Tables to look up row from PAC data +var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 }; +var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 }; +var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 }; +var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 }; + +var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent']; + +/** + * Simple logger class to be able to write with time-stamps and filter on level. + */ +var cea_608_parser_logger = { + verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 }, + time: null, + verboseLevel: 0, // Only write errors + setTime: function setTime(newTime) { + this.time = newTime; + }, + log: function log(severity, msg) { + var minLevel = this.verboseFilter[severity]; + if (this.verboseLevel >= minLevel) { + console.log(this.time + ' [' + severity + '] ' + msg); + } + } +}; + +var numArrayToHexArray = function numArrayToHexArray(numArray) { + var hexArray = []; + for (var j = 0; j < numArray.length; j++) { + hexArray.push(numArray[j].toString(16)); + } + return hexArray; +}; + +var PenState = function () { + function PenState(foreground, underline, italics, background, flash) { + cea_608_parser__classCallCheck(this, PenState); + + this.foreground = foreground || 'white'; + this.underline = underline || false; + this.italics = italics || false; + this.background = background || 'black'; + this.flash = flash || false; + } + + PenState.prototype.reset = function reset() { + this.foreground = 'white'; + this.underline = false; + this.italics = false; + this.background = 'black'; + this.flash = false; + }; + + PenState.prototype.setStyles = function setStyles(styles) { + var attribs = ['foreground', 'underline', 'italics', 'background', 'flash']; + for (var i = 0; i < attribs.length; i++) { + var style = attribs[i]; + if (styles.hasOwnProperty(style)) { + this[style] = styles[style]; + } + } + }; + + PenState.prototype.isDefault = function isDefault() { + return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash; + }; + + PenState.prototype.equals = function equals(other) { + return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash; + }; + + PenState.prototype.copy = function copy(newPenState) { + this.foreground = newPenState.foreground; + this.underline = newPenState.underline; + this.italics = newPenState.italics; + this.background = newPenState.background; + this.flash = newPenState.flash; + }; + + PenState.prototype.toString = function toString() { + return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash; + }; + + return PenState; +}(); + +/** + * Unicode character with styling and background. + * @constructor + */ + + +var StyledUnicodeChar = function () { + function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) { + cea_608_parser__classCallCheck(this, StyledUnicodeChar); + + this.uchar = uchar || ' '; // unicode character + this.penState = new PenState(foreground, underline, italics, background, flash); + } + + StyledUnicodeChar.prototype.reset = function reset() { + this.uchar = ' '; + this.penState.reset(); + }; + + StyledUnicodeChar.prototype.setChar = function setChar(uchar, newPenState) { + this.uchar = uchar; + this.penState.copy(newPenState); + }; + + StyledUnicodeChar.prototype.setPenState = function setPenState(newPenState) { + this.penState.copy(newPenState); + }; + + StyledUnicodeChar.prototype.equals = function equals(other) { + return this.uchar === other.uchar && this.penState.equals(other.penState); + }; + + StyledUnicodeChar.prototype.copy = function copy(newChar) { + this.uchar = newChar.uchar; + this.penState.copy(newChar.penState); + }; + + StyledUnicodeChar.prototype.isEmpty = function isEmpty() { + return this.uchar === ' ' && this.penState.isDefault(); + }; + + return StyledUnicodeChar; +}(); + +/** + * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar. + * @constructor + */ + + +var Row = function () { + function Row() { + cea_608_parser__classCallCheck(this, Row); + + this.chars = []; + for (var i = 0; i < NR_COLS; i++) { + this.chars.push(new StyledUnicodeChar()); + } + this.pos = 0; + this.currPenState = new PenState(); + } + + Row.prototype.equals = function equals(other) { + var equal = true; + for (var i = 0; i < NR_COLS; i++) { + if (!this.chars[i].equals(other.chars[i])) { + equal = false; + break; + } + } + return equal; + }; + + Row.prototype.copy = function copy(other) { + for (var i = 0; i < NR_COLS; i++) { + this.chars[i].copy(other.chars[i]); + } + }; + + Row.prototype.isEmpty = function isEmpty() { + var empty = true; + for (var i = 0; i < NR_COLS; i++) { + if (!this.chars[i].isEmpty()) { + empty = false; + break; + } + } + return empty; + }; + + /** + * Set the cursor to a valid column. + */ + + + Row.prototype.setCursor = function setCursor(absPos) { + if (this.pos !== absPos) { + this.pos = absPos; + } + if (this.pos < 0) { + cea_608_parser_logger.log('ERROR', 'Negative cursor position ' + this.pos); + this.pos = 0; + } else if (this.pos > NR_COLS) { + cea_608_parser_logger.log('ERROR', 'Too large cursor position ' + this.pos); + this.pos = NR_COLS; + } + }; + + /** + * Move the cursor relative to current position. + */ + + + Row.prototype.moveCursor = function moveCursor(relPos) { + var newPos = this.pos + relPos; + if (relPos > 1) { + for (var i = this.pos + 1; i < newPos + 1; i++) { + this.chars[i].setPenState(this.currPenState); + } + } + this.setCursor(newPos); + }; + + /** + * Backspace, move one step back and clear character. + */ + + + Row.prototype.backSpace = function backSpace() { + this.moveCursor(-1); + this.chars[this.pos].setChar(' ', this.currPenState); + }; + + Row.prototype.insertChar = function insertChar(byte) { + if (byte >= 0x90) { + //Extended char + this.backSpace(); + } + var char = getCharForByte(byte); + if (this.pos >= NR_COLS) { + cea_608_parser_logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!'); + return; + } + this.chars[this.pos].setChar(char, this.currPenState); + this.moveCursor(1); + }; + + Row.prototype.clearFromPos = function clearFromPos(startPos) { + var i; + for (i = startPos; i < NR_COLS; i++) { + this.chars[i].reset(); + } + }; + + Row.prototype.clear = function clear() { + this.clearFromPos(0); + this.pos = 0; + this.currPenState.reset(); + }; + + Row.prototype.clearToEndOfRow = function clearToEndOfRow() { + this.clearFromPos(this.pos); + }; + + Row.prototype.getTextString = function getTextString() { + var chars = []; + var empty = true; + for (var i = 0; i < NR_COLS; i++) { + var char = this.chars[i].uchar; + if (char !== ' ') { + empty = false; + } + chars.push(char); + } + if (empty) { + return ''; + } else { + return chars.join(''); + } + }; + + Row.prototype.setPenStyles = function setPenStyles(styles) { + this.currPenState.setStyles(styles); + var currChar = this.chars[this.pos]; + currChar.setPenState(this.currPenState); + }; + + return Row; +}(); + +/** + * Keep a CEA-608 screen of 32x15 styled characters + * @constructor +*/ + + +var CaptionScreen = function () { + function CaptionScreen() { + cea_608_parser__classCallCheck(this, CaptionScreen); + + this.rows = []; + for (var i = 0; i < NR_ROWS; i++) { + this.rows.push(new Row()); // Note that we use zero-based numbering (0-14) + } + this.currRow = NR_ROWS - 1; + this.nrRollUpRows = null; + this.reset(); + } + + CaptionScreen.prototype.reset = function reset() { + for (var i = 0; i < NR_ROWS; i++) { + this.rows[i].clear(); + } + this.currRow = NR_ROWS - 1; + }; + + CaptionScreen.prototype.equals = function equals(other) { + var equal = true; + for (var i = 0; i < NR_ROWS; i++) { + if (!this.rows[i].equals(other.rows[i])) { + equal = false; + break; + } + } + return equal; + }; + + CaptionScreen.prototype.copy = function copy(other) { + for (var i = 0; i < NR_ROWS; i++) { + this.rows[i].copy(other.rows[i]); + } + }; + + CaptionScreen.prototype.isEmpty = function isEmpty() { + var empty = true; + for (var i = 0; i < NR_ROWS; i++) { + if (!this.rows[i].isEmpty()) { + empty = false; + break; + } + } + return empty; + }; + + CaptionScreen.prototype.backSpace = function backSpace() { + var row = this.rows[this.currRow]; + row.backSpace(); + }; + + CaptionScreen.prototype.clearToEndOfRow = function clearToEndOfRow() { + var row = this.rows[this.currRow]; + row.clearToEndOfRow(); + }; + + /** + * Insert a character (without styling) in the current row. + */ + + + CaptionScreen.prototype.insertChar = function insertChar(char) { + var row = this.rows[this.currRow]; + row.insertChar(char); + }; + + CaptionScreen.prototype.setPen = function setPen(styles) { + var row = this.rows[this.currRow]; + row.setPenStyles(styles); + }; + + CaptionScreen.prototype.moveCursor = function moveCursor(relPos) { + var row = this.rows[this.currRow]; + row.moveCursor(relPos); + }; + + CaptionScreen.prototype.setCursor = function setCursor(absPos) { + cea_608_parser_logger.log('INFO', 'setCursor: ' + absPos); + var row = this.rows[this.currRow]; + row.setCursor(absPos); + }; + + CaptionScreen.prototype.setPAC = function setPAC(pacData) { + cea_608_parser_logger.log('INFO', 'pacData = ' + JSON.stringify(pacData)); + var newRow = pacData.row - 1; + if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) { + newRow = this.nrRollUpRows - 1; + } + + //Make sure this only affects Roll-up Captions by checking this.nrRollUpRows + if (this.nrRollUpRows && this.currRow !== newRow) { + //clear all rows first + for (var i = 0; i < NR_ROWS; i++) { + this.rows[i].clear(); + } + + //Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location + //topRowIndex - the start of rows to copy (inclusive index) + var topRowIndex = this.currRow + 1 - this.nrRollUpRows; + //We only copy if the last position was already shown. + //We use the cueStartTime value to check this. + var lastOutputScreen = this.lastOutputScreen; + if (lastOutputScreen) { + var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime; + if (prevLineTime && prevLineTime < cea_608_parser_logger.time) { + for (var _i = 0; _i < this.nrRollUpRows; _i++) { + this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]); + } + } + } + } + + this.currRow = newRow; + var row = this.rows[this.currRow]; + if (pacData.indent !== null) { + var indent = pacData.indent; + var prevPos = Math.max(indent - 1, 0); + row.setCursor(pacData.indent); + pacData.color = row.chars[prevPos].penState.foreground; + } + var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false }; + this.setPen(styles); + }; + + /** + * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility). + */ + + + CaptionScreen.prototype.setBkgData = function setBkgData(bkgData) { + + cea_608_parser_logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData)); + this.backSpace(); + this.setPen(bkgData); + this.insertChar(0x20); //Space + }; + + CaptionScreen.prototype.setRollUpRows = function setRollUpRows(nrRows) { + this.nrRollUpRows = nrRows; + }; + + CaptionScreen.prototype.rollUp = function rollUp() { + if (this.nrRollUpRows === null) { + cea_608_parser_logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet'); + return; //Not properly setup + } + cea_608_parser_logger.log('TEXT', this.getDisplayText()); + var topRowIndex = this.currRow + 1 - this.nrRollUpRows; + var topRow = this.rows.splice(topRowIndex, 1)[0]; + topRow.clear(); + this.rows.splice(this.currRow, 0, topRow); + cea_608_parser_logger.log('INFO', 'Rolling up'); + //logger.log('TEXT', this.get_display_text()) + }; + + /** + * Get all non-empty rows with as unicode text. + */ + + + CaptionScreen.prototype.getDisplayText = function getDisplayText(asOneRow) { + asOneRow = asOneRow || false; + var displayText = []; + var text = ''; + var rowNr = -1; + for (var i = 0; i < NR_ROWS; i++) { + var rowText = this.rows[i].getTextString(); + if (rowText) { + rowNr = i + 1; + if (asOneRow) { + displayText.push('Row ' + rowNr + ': \'' + rowText + '\''); + } else { + displayText.push(rowText.trim()); + } + } + } + if (displayText.length > 0) { + if (asOneRow) { + text = '[' + displayText.join(' | ') + ']'; + } else { + text = displayText.join('\n'); + } + } + return text; + }; + + CaptionScreen.prototype.getTextAndFormat = function getTextAndFormat() { + return this.rows; + }; + + return CaptionScreen; +}(); + +//var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT']; + +var Cea608Channel = function () { + function Cea608Channel(channelNumber, outputFilter) { + cea_608_parser__classCallCheck(this, Cea608Channel); + + this.chNr = channelNumber; + this.outputFilter = outputFilter; + this.mode = null; + this.verbose = 0; + this.displayedMemory = new CaptionScreen(); + this.nonDisplayedMemory = new CaptionScreen(); + this.lastOutputScreen = new CaptionScreen(); + this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; + this.writeScreen = this.displayedMemory; + this.mode = null; + this.cueStartTime = null; // Keeps track of where a cue started. + } + + Cea608Channel.prototype.reset = function reset() { + this.mode = null; + this.displayedMemory.reset(); + this.nonDisplayedMemory.reset(); + this.lastOutputScreen.reset(); + this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1]; + this.writeScreen = this.displayedMemory; + this.mode = null; + this.cueStartTime = null; + this.lastCueEndTime = null; + }; + + Cea608Channel.prototype.getHandler = function getHandler() { + return this.outputFilter; + }; + + Cea608Channel.prototype.setHandler = function setHandler(newHandler) { + this.outputFilter = newHandler; + }; + + Cea608Channel.prototype.setPAC = function setPAC(pacData) { + this.writeScreen.setPAC(pacData); + }; + + Cea608Channel.prototype.setBkgData = function setBkgData(bkgData) { + this.writeScreen.setBkgData(bkgData); + }; + + Cea608Channel.prototype.setMode = function setMode(newMode) { + if (newMode === this.mode) { + return; + } + this.mode = newMode; + cea_608_parser_logger.log('INFO', 'MODE=' + newMode); + if (this.mode === 'MODE_POP-ON') { + this.writeScreen = this.nonDisplayedMemory; + } else { + this.writeScreen = this.displayedMemory; + this.writeScreen.reset(); + } + if (this.mode !== 'MODE_ROLL-UP') { + this.displayedMemory.nrRollUpRows = null; + this.nonDisplayedMemory.nrRollUpRows = null; + } + this.mode = newMode; + }; + + Cea608Channel.prototype.insertChars = function insertChars(chars) { + for (var i = 0; i < chars.length; i++) { + this.writeScreen.insertChar(chars[i]); + } + var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP'; + cea_608_parser_logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true)); + if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') { + cea_608_parser_logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true)); + this.outputDataUpdate(); + } + }; + + Cea608Channel.prototype.ccRCL = function ccRCL() { + // Resume Caption Loading (switch mode to Pop On) + cea_608_parser_logger.log('INFO', 'RCL - Resume Caption Loading'); + this.setMode('MODE_POP-ON'); + }; + + Cea608Channel.prototype.ccBS = function ccBS() { + // BackSpace + cea_608_parser_logger.log('INFO', 'BS - BackSpace'); + if (this.mode === 'MODE_TEXT') { + return; + } + this.writeScreen.backSpace(); + if (this.writeScreen === this.displayedMemory) { + this.outputDataUpdate(); + } + }; + + Cea608Channel.prototype.ccAOF = function ccAOF() { + // Reserved (formerly Alarm Off) + return; + }; + + Cea608Channel.prototype.ccAON = function ccAON() { + // Reserved (formerly Alarm On) + return; + }; + + Cea608Channel.prototype.ccDER = function ccDER() { + // Delete to End of Row + cea_608_parser_logger.log('INFO', 'DER- Delete to End of Row'); + this.writeScreen.clearToEndOfRow(); + this.outputDataUpdate(); + }; + + Cea608Channel.prototype.ccRU = function ccRU(nrRows) { + //Roll-Up Captions-2,3,or 4 Rows + cea_608_parser_logger.log('INFO', 'RU(' + nrRows + ') - Roll Up'); + this.writeScreen = this.displayedMemory; + this.setMode('MODE_ROLL-UP'); + this.writeScreen.setRollUpRows(nrRows); + }; + + Cea608Channel.prototype.ccFON = function ccFON() { + //Flash On + cea_608_parser_logger.log('INFO', 'FON - Flash On'); + this.writeScreen.setPen({ flash: true }); + }; + + Cea608Channel.prototype.ccRDC = function ccRDC() { + // Resume Direct Captioning (switch mode to PaintOn) + cea_608_parser_logger.log('INFO', 'RDC - Resume Direct Captioning'); + this.setMode('MODE_PAINT-ON'); + }; + + Cea608Channel.prototype.ccTR = function ccTR() { + // Text Restart in text mode (not supported, however) + cea_608_parser_logger.log('INFO', 'TR'); + this.setMode('MODE_TEXT'); + }; + + Cea608Channel.prototype.ccRTD = function ccRTD() { + // Resume Text Display in Text mode (not supported, however) + cea_608_parser_logger.log('INFO', 'RTD'); + this.setMode('MODE_TEXT'); + }; + + Cea608Channel.prototype.ccEDM = function ccEDM() { + // Erase Displayed Memory + cea_608_parser_logger.log('INFO', 'EDM - Erase Displayed Memory'); + this.displayedMemory.reset(); + this.outputDataUpdate(true); + }; + + Cea608Channel.prototype.ccCR = function ccCR() { + // Carriage Return + cea_608_parser_logger.log('CR - Carriage Return'); + this.writeScreen.rollUp(); + this.outputDataUpdate(true); + }; + + Cea608Channel.prototype.ccENM = function ccENM() { + //Erase Non-Displayed Memory + cea_608_parser_logger.log('INFO', 'ENM - Erase Non-displayed Memory'); + this.nonDisplayedMemory.reset(); + }; + + Cea608Channel.prototype.ccEOC = function ccEOC() { + //End of Caption (Flip Memories) + cea_608_parser_logger.log('INFO', 'EOC - End Of Caption'); + if (this.mode === 'MODE_POP-ON') { + var tmp = this.displayedMemory; + this.displayedMemory = this.nonDisplayedMemory; + this.nonDisplayedMemory = tmp; + this.writeScreen = this.nonDisplayedMemory; + cea_608_parser_logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText()); + } + this.outputDataUpdate(true); + }; + + Cea608Channel.prototype.ccTO = function ccTO(nrCols) { + // Tab Offset 1,2, or 3 columns + cea_608_parser_logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset'); + this.writeScreen.moveCursor(nrCols); + }; + + Cea608Channel.prototype.ccMIDROW = function ccMIDROW(secondByte) { + // Parse MIDROW command + var styles = { flash: false }; + styles.underline = secondByte % 2 === 1; + styles.italics = secondByte >= 0x2e; + if (!styles.italics) { + var colorIndex = Math.floor(secondByte / 2) - 0x10; + var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta']; + styles.foreground = colors[colorIndex]; + } else { + styles.foreground = 'white'; + } + cea_608_parser_logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles)); + this.writeScreen.setPen(styles); + }; + + Cea608Channel.prototype.outputDataUpdate = function outputDataUpdate() { + var dispatch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + var t = cea_608_parser_logger.time; + if (t === null) { + return; + } + if (this.outputFilter) { + if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { + // Start of a new cue + this.cueStartTime = t; + } else { + if (!this.displayedMemory.equals(this.lastOutputScreen)) { + if (this.outputFilter.newCue) { + this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen); + if (dispatch === true && this.outputFilter.dispatchCue) { + this.outputFilter.dispatchCue(); + } + } + this.cueStartTime = this.displayedMemory.isEmpty() ? null : t; + } + } + this.lastOutputScreen.copy(this.displayedMemory); + } + }; + + Cea608Channel.prototype.cueSplitAtTime = function cueSplitAtTime(t) { + if (this.outputFilter) { + if (!this.displayedMemory.isEmpty()) { + if (this.outputFilter.newCue) { + this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory); + } + this.cueStartTime = t; + } + } + }; + + return Cea608Channel; +}(); + +var Cea608Parser = function () { + function Cea608Parser(field, out1, out2) { + cea_608_parser__classCallCheck(this, Cea608Parser); + + this.field = field || 1; + this.outputs = [out1, out2]; + this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)]; + this.currChNr = -1; // Will be 1 or 2 + this.lastCmdA = null; // First byte of last command + this.lastCmdB = null; // Second byte of last command + this.bufferedData = []; + this.startTime = null; + this.lastTime = null; + this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 }; + } + + Cea608Parser.prototype.getHandler = function getHandler(index) { + return this.channels[index].getHandler(); + }; + + Cea608Parser.prototype.setHandler = function setHandler(index, newHandler) { + this.channels[index].setHandler(newHandler); + }; + + /** + * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs. + */ + + + Cea608Parser.prototype.addData = function addData(t, byteList) { + var cmdFound, + a, + b, + charsFound = false; + + this.lastTime = t; + cea_608_parser_logger.setTime(t); + + for (var i = 0; i < byteList.length; i += 2) { + a = byteList[i] & 0x7f; + b = byteList[i + 1] & 0x7f; + if (a === 0 && b === 0) { + this.dataCounters.padding += 2; + continue; + } else { + cea_608_parser_logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')'); + } + cmdFound = this.parseCmd(a, b); + if (!cmdFound) { + cmdFound = this.parseMidrow(a, b); + } + if (!cmdFound) { + cmdFound = this.parsePAC(a, b); + } + if (!cmdFound) { + cmdFound = this.parseBackgroundAttributes(a, b); + } + if (!cmdFound) { + charsFound = this.parseChars(a, b); + if (charsFound) { + if (this.currChNr && this.currChNr >= 0) { + var channel = this.channels[this.currChNr - 1]; + channel.insertChars(charsFound); + } else { + cea_608_parser_logger.log('WARNING', 'No channel found yet. TEXT-MODE?'); + } + } + } + if (cmdFound) { + this.dataCounters.cmd += 2; + } else if (charsFound) { + this.dataCounters.char += 2; + } else { + this.dataCounters.other += 2; + cea_608_parser_logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]])); + } + } + }; + + /** + * Parse Command. + * @returns {Boolean} Tells if a command was found + */ + + + Cea608Parser.prototype.parseCmd = function parseCmd(a, b) { + var chNr = null; + + var cond1 = (a === 0x14 || a === 0x1C) && 0x20 <= b && b <= 0x2F; + var cond2 = (a === 0x17 || a === 0x1F) && 0x21 <= b && b <= 0x23; + if (!(cond1 || cond2)) { + return false; + } + + if (a === this.lastCmdA && b === this.lastCmdB) { + this.lastCmdA = null; + this.lastCmdB = null; // Repeated commands are dropped (once) + cea_608_parser_logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped'); + return true; + } + + if (a === 0x14 || a === 0x17) { + chNr = 1; + } else { + chNr = 2; // (a === 0x1C || a=== 0x1f) + } + + var channel = this.channels[chNr - 1]; + + if (a === 0x14 || a === 0x1C) { + if (b === 0x20) { + channel.ccRCL(); + } else if (b === 0x21) { + channel.ccBS(); + } else if (b === 0x22) { + channel.ccAOF(); + } else if (b === 0x23) { + channel.ccAON(); + } else if (b === 0x24) { + channel.ccDER(); + } else if (b === 0x25) { + channel.ccRU(2); + } else if (b === 0x26) { + channel.ccRU(3); + } else if (b === 0x27) { + channel.ccRU(4); + } else if (b === 0x28) { + channel.ccFON(); + } else if (b === 0x29) { + channel.ccRDC(); + } else if (b === 0x2A) { + channel.ccTR(); + } else if (b === 0x2B) { + channel.ccRTD(); + } else if (b === 0x2C) { + channel.ccEDM(); + } else if (b === 0x2D) { + channel.ccCR(); + } else if (b === 0x2E) { + channel.ccENM(); + } else if (b === 0x2F) { + channel.ccEOC(); + } + } else { + //a == 0x17 || a == 0x1F + channel.ccTO(b - 0x20); + } + this.lastCmdA = a; + this.lastCmdB = b; + this.currChNr = chNr; + return true; + }; + + /** + * Parse midrow styling command + * @returns {Boolean} + */ + + + Cea608Parser.prototype.parseMidrow = function parseMidrow(a, b) { + var chNr = null; + + if ((a === 0x11 || a === 0x19) && 0x20 <= b && b <= 0x2f) { + if (a === 0x11) { + chNr = 1; + } else { + chNr = 2; + } + if (chNr !== this.currChNr) { + cea_608_parser_logger.log('ERROR', 'Mismatch channel in midrow parsing'); + return false; + } + var channel = this.channels[chNr - 1]; + channel.ccMIDROW(b); + cea_608_parser_logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')'); + return true; + } + return false; + }; + /** + * Parse Preable Access Codes (Table 53). + * @returns {Boolean} Tells if PAC found + */ + + + Cea608Parser.prototype.parsePAC = function parsePAC(a, b) { + + var chNr = null; + var row = null; + + var case1 = (0x11 <= a && a <= 0x17 || 0x19 <= a && a <= 0x1F) && 0x40 <= b && b <= 0x7F; + var case2 = (a === 0x10 || a === 0x18) && 0x40 <= b && b <= 0x5F; + if (!(case1 || case2)) { + return false; + } + + if (a === this.lastCmdA && b === this.lastCmdB) { + this.lastCmdA = null; + this.lastCmdB = null; + return true; // Repeated commands are dropped (once) + } + + chNr = a <= 0x17 ? 1 : 2; + + if (0x40 <= b && b <= 0x5F) { + row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a]; + } else { + // 0x60 <= b <= 0x7F + row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a]; + } + var pacData = this.interpretPAC(row, b); + var channel = this.channels[chNr - 1]; + channel.setPAC(pacData); + this.lastCmdA = a; + this.lastCmdB = b; + this.currChNr = chNr; + return true; + }; + + /** + * Interpret the second byte of the pac, and return the information. + * @returns {Object} pacData with style parameters. + */ + + + Cea608Parser.prototype.interpretPAC = function interpretPAC(row, byte) { + var pacIndex = byte; + var pacData = { color: null, italics: false, indent: null, underline: false, row: row }; + + if (byte > 0x5F) { + pacIndex = byte - 0x60; + } else { + pacIndex = byte - 0x40; + } + pacData.underline = (pacIndex & 1) === 1; + if (pacIndex <= 0xd) { + pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)]; + } else if (pacIndex <= 0xf) { + pacData.italics = true; + pacData.color = 'white'; + } else { + pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4; + } + return pacData; // Note that row has zero offset. The spec uses 1. + }; + + /** + * Parse characters. + * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise. + */ + + + Cea608Parser.prototype.parseChars = function parseChars(a, b) { + + var channelNr = null, + charCodes = null, + charCode1 = null; + + if (a >= 0x19) { + channelNr = 2; + charCode1 = a - 8; + } else { + channelNr = 1; + charCode1 = a; + } + if (0x11 <= charCode1 && charCode1 <= 0x13) { + // Special character + var oneCode = b; + if (charCode1 === 0x11) { + oneCode = b + 0x50; + } else if (charCode1 === 0x12) { + oneCode = b + 0x70; + } else { + oneCode = b + 0x90; + } + cea_608_parser_logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr); + charCodes = [oneCode]; + } else if (0x20 <= a && a <= 0x7f) { + charCodes = b === 0 ? [a] : [a, b]; + } + if (charCodes) { + var hexCodes = numArrayToHexArray(charCodes); + cea_608_parser_logger.log('DEBUG', 'Char codes = ' + hexCodes.join(',')); + this.lastCmdA = null; + this.lastCmdB = null; + } + return charCodes; + }; + + /** + * Parse extended background attributes as well as new foreground color black. + * @returns{Boolean} Tells if background attributes are found + */ + + + Cea608Parser.prototype.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) { + var bkgData, index, chNr, channel; + + var case1 = (a === 0x10 || a === 0x18) && 0x20 <= b && b <= 0x2f; + var case2 = (a === 0x17 || a === 0x1f) && 0x2d <= b && b <= 0x2f; + if (!(case1 || case2)) { + return false; + } + bkgData = {}; + if (a === 0x10 || a === 0x18) { + index = Math.floor((b - 0x20) / 2); + bkgData.background = backgroundColors[index]; + if (b % 2 === 1) { + bkgData.background = bkgData.background + '_semi'; + } + } else if (b === 0x2d) { + bkgData.background = 'transparent'; + } else { + bkgData.foreground = 'black'; + if (b === 0x2f) { + bkgData.underline = true; + } + } + chNr = a < 0x18 ? 1 : 2; + channel = this.channels[chNr - 1]; + channel.setBkgData(bkgData); + this.lastCmdA = null; + this.lastCmdB = null; + return true; + }; + + /** + * Reset state of parser and its channels. + */ + + + Cea608Parser.prototype.reset = function reset() { + for (var i = 0; i < this.channels.length; i++) { + if (this.channels[i]) { + this.channels[i].reset(); + } + } + this.lastCmdA = null; + this.lastCmdB = null; + }; + + /** + * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty. + */ + + + Cea608Parser.prototype.cueSplitAtTime = function cueSplitAtTime(t) { + for (var i = 0; i < this.channels.length; i++) { + if (this.channels[i]) { + this.channels[i].cueSplitAtTime(t); + } + } + }; + + return Cea608Parser; +}(); + +/* harmony default export */ var cea_608_parser = (Cea608Parser); +// CONCATENATED MODULE: ./src/utils/output-filter.js +function output_filter__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var OutputFilter = function () { + function OutputFilter(timelineController, track) { + output_filter__classCallCheck(this, OutputFilter); + + this.timelineController = timelineController; + this.track = track; + this.startTime = null; + this.endTime = null; + this.screen = null; + } + + OutputFilter.prototype.dispatchCue = function dispatchCue() { + if (this.startTime === null) { + return; + } + this.timelineController.addCues('textTrack' + this.track, this.startTime, this.endTime, this.screen); + this.startTime = null; + }; + + OutputFilter.prototype.newCue = function newCue(startTime, endTime, screen) { + if (this.startTime === null || this.startTime > startTime) { + this.startTime = startTime; + } + this.endTime = endTime; + this.screen = screen; + this.timelineController.createCaptionsTrack(this.track); + }; + + return OutputFilter; +}(); + +/* harmony default export */ var output_filter = (OutputFilter); +// CONCATENATED MODULE: ./src/utils/webvtt-parser.js + + + +// String.prototype.startsWith is not supported in IE11 +var startsWith = function startsWith(inputString, searchString, position) { + return inputString.substr(position || 0, searchString.length) === searchString; +}; + +var cueString2millis = function cueString2millis(timeString) { + var ts = parseInt(timeString.substr(-3)); + var secs = parseInt(timeString.substr(-6, 2)); + var mins = parseInt(timeString.substr(-9, 2)); + var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0; + + if (isNaN(ts) || isNaN(secs) || isNaN(mins) || isNaN(hours)) { + return -1; + } + + ts += 1000 * secs; + ts += 60 * 1000 * mins; + ts += 60 * 60 * 1000 * hours; + + return ts; +}; + +// From https://github.com/darkskyapp/string-hash +var hash = function hash(text) { + var hash = 5381; + var i = text.length; + while (i) { + hash = hash * 33 ^ text.charCodeAt(--i); + } + return (hash >>> 0).toString(); +}; + +var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) { + var currCC = vttCCs[cc]; + var prevCC = vttCCs[currCC.prevCC]; + + // This is the first discontinuity or cues have been processed since the last discontinuity + // Offset = current discontinuity time + if (!prevCC || !prevCC.new && currCC.new) { + vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start; + currCC.new = false; + return; + } + + // There have been discontinuities since cues were last parsed. + // Offset = time elapsed + while (prevCC && prevCC.new) { + vttCCs.ccOffset += currCC.start - prevCC.start; + currCC.new = false; + currCC = prevCC; + prevCC = vttCCs[currCC.prevCC]; + } + + vttCCs.presentationOffset = presentationTime; +}; + +var WebVTTParser = { + parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) { + // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character. + var re = /\r\n|\n\r|\n|\r/g; + // Uint8Array.prototype.reduce is not implemented in IE11 + var vttLines = Object(id3["b" /* utf8ArrayToStr */])(new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n'); + + var cueTime = '00:00.000'; + var mpegTs = 0; + var localTime = 0; + var presentationTime = 0; + var cues = []; + var parsingError = void 0; + var inHeader = true; + // let VTTCue = VTTCue || window.TextTrackCue; + + // Create parser object using VTTCue with TextTrackCue fallback on certain browsers. + var parser = new vttparser(); + + parser.oncue = function (cue) { + // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline. + var currCC = vttCCs[cc]; + var cueOffset = vttCCs.ccOffset; + + // Update offsets for new discontinuities + if (currCC && currCC.new) { + if (localTime !== undefined) { + // When local time is provided, offset = discontinuity start time - local time + cueOffset = vttCCs.ccOffset = currCC.start; + } else { + calculateOffset(vttCCs, cc, presentationTime); + } + } + + if (presentationTime) { + // If we have MPEGTS, offset = presentation time + discontinuity offset + cueOffset = presentationTime + vttCCs.ccOffset - vttCCs.presentationOffset; + } + + cue.startTime += cueOffset - localTime; + cue.endTime += cueOffset - localTime; + + // Create a unique hash id for a cue based on start/end times and text. + // This helps timeline-controller to avoid showing repeated captions. + cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text); + + // Fix encoding of special characters. TODO: Test with all sorts of weird characters. + cue.text = decodeURIComponent(encodeURIComponent(cue.text)); + if (cue.endTime > 0) { + cues.push(cue); + } + }; + + parser.onparsingerror = function (e) { + parsingError = e; + }; + + parser.onflush = function () { + if (parsingError && errorCallBack) { + errorCallBack(parsingError); + return; + } + callBack(cues); + }; + + // Go through contents line by line. + vttLines.forEach(function (line) { + if (inHeader) { + // Look for X-TIMESTAMP-MAP in header. + if (startsWith(line, 'X-TIMESTAMP-MAP=')) { + // Once found, no more are allowed anyway, so stop searching. + inHeader = false; + // Extract LOCAL and MPEGTS. + line.substr(16).split(',').forEach(function (timestamp) { + if (startsWith(timestamp, 'LOCAL:')) { + cueTime = timestamp.substr(6); + } else if (startsWith(timestamp, 'MPEGTS:')) { + mpegTs = parseInt(timestamp.substr(7)); + } + }); + try { + // Calculate subtitle offset in milliseconds. + // If sync PTS is less than zero, we have a 33-bit wraparound, which is fixed by adding 2^33 = 8589934592. + syncPTS = syncPTS < 0 ? syncPTS + 8589934592 : syncPTS; + // Adjust MPEGTS by sync PTS. + mpegTs -= syncPTS; + // Convert cue time to seconds + localTime = cueString2millis(cueTime) / 1000; + // Convert MPEGTS to seconds from 90kHz. + presentationTime = mpegTs / 90000; + + if (localTime === -1) { + parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line); + } + } catch (e) { + parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line); + } + // Return without parsing X-TIMESTAMP-MAP line. + return; + } else if (line === '') { + inHeader = false; + } + } + // Parse line by default. + parser.parse(line + '\n'); + }); + + parser.flush(); + } +}; + +/* harmony default export */ var webvtt_parser = (WebVTTParser); +// CONCATENATED MODULE: ./src/controller/timeline-controller.js +function timeline_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function timeline_controller__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; } + +function timeline_controller__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; } + +/* + * Timeline Controller +*/ + + + + + + + + +function clearCurrentCues(track) { + if (track && track.cues) { + while (track.cues.length > 0) { + track.removeCue(track.cues[0]); + } + } +} + +function reuseVttTextTrack(inUseTrack, manifestTrack) { + return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2); +} + +function intersection(x1, x2, y1, y2) { + return Math.min(x2, y2) - Math.max(x1, y1); +} + +var timeline_controller_TimelineController = function (_EventHandler) { + timeline_controller__inherits(TimelineController, _EventHandler); + + function TimelineController(hls) { + timeline_controller__classCallCheck(this, TimelineController); + + var _this = timeline_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].FRAG_PARSING_USERDATA, events["a" /* default */].FRAG_DECRYPTED, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].LEVEL_SWITCHING, events["a" /* default */].INIT_PTS_FOUND)); + + _this.hls = hls; + _this.config = hls.config; + _this.enabled = true; + _this.Cues = hls.config.cueHandler; + _this.textTracks = []; + _this.tracks = []; + _this.unparsedVttFrags = []; + _this.initPTS = undefined; + _this.cueRanges = []; + + if (_this.config.enableCEA708Captions) { + var channel1 = new output_filter(_this, 1); + var channel2 = new output_filter(_this, 2); + + _this.cea608Parser = new cea_608_parser(0, channel1, channel2); + } + return _this; + } + + TimelineController.prototype.addCues = function addCues(channel, startTime, endTime, screen) { + // skip cues which overlap more than 50% with previously parsed time ranges + var ranges = this.cueRanges; + var merged = false; + for (var i = ranges.length; i--;) { + var cueRange = ranges[i]; + var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime); + if (overlap >= 0) { + cueRange[0] = Math.min(cueRange[0], startTime); + cueRange[1] = Math.max(cueRange[1], endTime); + merged = true; + if (overlap / (endTime - startTime) > 0.5) { + return; + } + } + } + if (!merged) { + ranges.push([startTime, endTime]); + } + this.Cues.newCue(this[channel], startTime, endTime, screen); + }; + + // Triggered when an initial PTS is found; used for synchronisation of WebVTT. + + + TimelineController.prototype.onInitPtsFound = function onInitPtsFound(data) { + var _this2 = this; + + if (typeof this.initPTS === 'undefined') { + this.initPTS = data.initPTS; + } + + // Due to asynchrony, initial PTS may arrive later than the first VTT fragments are loaded. + // Parse any unparsed fragments upon receiving the initial PTS. + if (this.unparsedVttFrags.length) { + this.unparsedVttFrags.forEach(function (frag) { + _this2.onFragLoaded(frag); + }); + this.unparsedVttFrags = []; + } + }; + + TimelineController.prototype.getExistingTrack = function getExistingTrack(channelNumber) { + var media = this.media; + if (media) { + for (var i = 0; i < media.textTracks.length; i++) { + var textTrack = media.textTracks[i]; + var propName = 'textTrack' + channelNumber; + if (textTrack[propName] === true) { + return textTrack; + } + } + } + return null; + }; + + TimelineController.prototype.sendAddTrackEvent = function sendAddTrackEvent(track, media) { + var e = null; + try { + e = new window.Event('addtrack'); + } catch (err) { + //for IE11 + e = document.createEvent('Event'); + e.initEvent('addtrack', false, false); + } + e.track = track; + media.dispatchEvent(e); + }; + + TimelineController.prototype.createCaptionsTrack = function createCaptionsTrack(track) { + var trackVar = 'textTrack' + track; + if (!this[trackVar]) { + //Enable reuse of existing text track. + var existingTrack = this.getExistingTrack(track); + if (!existingTrack) { + var textTrack = this.createTextTrack('captions', this.config['captionsTextTrack' + track + 'Label'], this.config.captionsTextTrack1LanguageCode); + if (textTrack) { + textTrack[trackVar] = true; + this[trackVar] = textTrack; + } + } else { + this[trackVar] = existingTrack; + clearCurrentCues(this[trackVar]); + + this.sendAddTrackEvent(this[trackVar], this.media); + } + } + }; + + TimelineController.prototype.createTextTrack = function createTextTrack(kind, label, lang) { + var media = this.media; + if (media) { + return media.addTextTrack(kind, label, lang); + } + }; + + TimelineController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + }; + + TimelineController.prototype.onMediaAttaching = function onMediaAttaching(data) { + this.media = data.media; + this._cleanTracks(); + }; + + TimelineController.prototype.onMediaDetaching = function onMediaDetaching() { + clearCurrentCues(this.textTrack1); + clearCurrentCues(this.textTrack2); + }; + + TimelineController.prototype.onManifestLoading = function onManifestLoading() { + this.lastSn = -1; // Detect discontiguity in fragment parsing + this.prevCC = -1; + this.vttCCs = { ccOffset: 0, presentationOffset: 0 }; // Detect discontinuity in subtitle manifests + this._cleanTracks(); + }; + + TimelineController.prototype._cleanTracks = function _cleanTracks() { + // clear outdated subtitles + var media = this.media; + if (media) { + var textTracks = media.textTracks; + if (textTracks) { + for (var i = 0; i < textTracks.length; i++) { + clearCurrentCues(textTracks[i]); + } + } + } + }; + + TimelineController.prototype.onManifestLoaded = function onManifestLoaded(data) { + var _this3 = this; + + this.textTracks = []; + this.unparsedVttFrags = this.unparsedVttFrags || []; + this.initPTS = undefined; + this.cueRanges = []; + + if (this.config.enableWebVTT) { + this.tracks = data.subtitles || []; + var inUseTracks = this.media ? this.media.textTracks : []; + + this.tracks.forEach(function (track, index) { + var textTrack = void 0; + if (index < inUseTracks.length) { + var inUseTrack = inUseTracks[index]; + // Reuse tracks with the same label, but do not reuse 608/708 tracks + if (reuseVttTextTrack(inUseTrack, track)) { + textTrack = inUseTrack; + } + } + if (!textTrack) { + textTrack = _this3.createTextTrack('subtitles', track.name, track.lang); + } + textTrack.mode = track.default ? 'showing' : 'hidden'; + _this3.textTracks.push(textTrack); + }); + } + }; + + TimelineController.prototype.onLevelSwitching = function onLevelSwitching() { + this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE'; + }; + + TimelineController.prototype.onFragLoaded = function onFragLoaded(data) { + var frag = data.frag, + payload = data.payload; + if (frag.type === 'main') { + var sn = frag.sn; + // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack + if (sn !== this.lastSn + 1) { + var cea608Parser = this.cea608Parser; + if (cea608Parser) { + cea608Parser.reset(); + } + } + this.lastSn = sn; + } + // If fragment is subtitle type, parse as WebVTT. + else if (frag.type === 'subtitle') { + if (payload.byteLength) { + // We need an initial synchronisation PTS. Store fragments as long as none has arrived. + if (typeof this.initPTS === 'undefined') { + this.unparsedVttFrags.push(data); + return; + } + + var decryptData = frag.decryptdata; + // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait. + if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') { + this._parseVTTs(frag, payload); + } + } else { + // In case there is no payload, finish unsuccessfully. + this.hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag }); + } + } + }; + + TimelineController.prototype._parseVTTs = function _parseVTTs(frag, payload) { + var vttCCs = this.vttCCs; + if (!vttCCs[frag.cc]) { + vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true }; + this.prevCC = frag.cc; + } + var textTracks = this.textTracks, + hls = this.hls; + + // Parse the WebVTT file contents. + webvtt_parser.parse(payload, this.initPTS, vttCCs, frag.cc, function (cues) { + var currentTrack = textTracks[frag.trackId]; + // Add cues and trigger event with success true. + cues.forEach(function (cue) { + // Sometimes there are cue overlaps on segmented vtts so the same + // cue can appear more than once in different vtt files. + // This avoid showing duplicated cues with same timecode and text. + if (!currentTrack.cues.getCueById(cue.id)) { + try { + currentTrack.addCue(cue); + } catch (err) { + var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text); + textTrackCue.id = cue.id; + currentTrack.addCue(textTrackCue); + } + } + }); + hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag }); + }, function (e) { + // Something went wrong while parsing. Trigger event with success false. + logger["b" /* logger */].log('Failed to parse VTT cue: ' + e); + hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag }); + }); + }; + + TimelineController.prototype.onFragDecrypted = function onFragDecrypted(data) { + var decryptedData = data.payload, + frag = data.frag; + + if (frag.type === 'subtitle') { + if (typeof this.initPTS === 'undefined') { + this.unparsedVttFrags.push(data); + return; + } + + this._parseVTTs(frag, decryptedData); + } + }; + + TimelineController.prototype.onFragParsingUserdata = function onFragParsingUserdata(data) { + // push all of the CEA-708 messages into the interpreter + // immediately. It will create the proper timestamps based on our PTS value + if (this.enabled && this.config.enableCEA708Captions) { + for (var i = 0; i < data.samples.length; i++) { + var ccdatas = this.extractCea608Data(data.samples[i].bytes); + this.cea608Parser.addData(data.samples[i].pts, ccdatas); + } + } + }; + + TimelineController.prototype.extractCea608Data = function extractCea608Data(byteArray) { + var count = byteArray[0] & 31; + var position = 2; + var tmpByte, ccbyte1, ccbyte2, ccValid, ccType; + var actualCCBytes = []; + + for (var j = 0; j < count; j++) { + tmpByte = byteArray[position++]; + ccbyte1 = 0x7F & byteArray[position++]; + ccbyte2 = 0x7F & byteArray[position++]; + ccValid = (4 & tmpByte) !== 0; + ccType = 3 & tmpByte; + + if (ccbyte1 === 0 && ccbyte2 === 0) { + continue; + } + + if (ccValid) { + if (ccType === 0) // || ccType === 1 + { + actualCCBytes.push(ccbyte1); + actualCCBytes.push(ccbyte2); + } + } + } + return actualCCBytes; + }; + + return TimelineController; +}(event_handler); + +/* harmony default export */ var timeline_controller = (timeline_controller_TimelineController); +// CONCATENATED MODULE: ./src/controller/subtitle-track-controller.js +var subtitle_track_controller__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; }; }(); + +function subtitle_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function subtitle_track_controller__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; } + +function subtitle_track_controller__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; } + +/* + * subtitle track controller +*/ + + + + + +function filterSubtitleTracks(textTrackList) { + var tracks = []; + for (var i = 0; i < textTrackList.length; i++) { + if (textTrackList[i].kind === 'subtitles') { + tracks.push(textTrackList[i]); + } + } + return tracks; +} + +var subtitle_track_controller_SubtitleTrackController = function (_EventHandler) { + subtitle_track_controller__inherits(SubtitleTrackController, _EventHandler); + + function SubtitleTrackController(hls) { + subtitle_track_controller__classCallCheck(this, SubtitleTrackController); + + var _this = subtitle_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].SUBTITLE_TRACK_LOADED)); + + _this.tracks = []; + _this.trackId = -1; + _this.media = undefined; + _this.subtitleDisplay = false; + return _this; + } + + SubtitleTrackController.prototype._onTextTracksChanged = function _onTextTracksChanged() { + // Media is undefined when switching streams via loadSource() + if (!this.media) { + return; + } + + var trackId = -1; + var tracks = filterSubtitleTracks(this.media.textTracks); + for (var id = 0; id < tracks.length; id++) { + if (tracks[id].mode === 'showing') { + trackId = id; + } + } + + // Setting current subtitleTrack will invoke code. + this.subtitleTrack = trackId; + }; + + SubtitleTrackController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + }; + + // Listen for subtitle track change, then extract the current track ID. + + + SubtitleTrackController.prototype.onMediaAttached = function onMediaAttached(data) { + var _this2 = this; + + this.media = data.media; + if (!this.media) { + return; + } + + if (this.queuedDefaultTrack !== undefined) { + this.subtitleTrack = this.queuedDefaultTrack; + delete this.queuedDefaultTrack; + } + + this.trackChangeListener = this._onTextTracksChanged.bind(this); + + this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks); + if (this.useTextTrackPolling) { + this.subtitlePollingInterval = setInterval(function () { + _this2.trackChangeListener(); + }, 500); + } else { + this.media.textTracks.addEventListener('change', this.trackChangeListener); + } + }; + + SubtitleTrackController.prototype.onMediaDetaching = function onMediaDetaching() { + if (!this.media) { + return; + } + if (this.useTextTrackPolling) { + clearInterval(this.subtitlePollingInterval); + } else { + this.media.textTracks.removeEventListener('change', this.trackChangeListener); + } + + this.media = undefined; + }; + + // Reset subtitle tracks on manifest loading + + + SubtitleTrackController.prototype.onManifestLoading = function onManifestLoading() { + this.tracks = []; + this.trackId = -1; + }; + + // Fired whenever a new manifest is loaded. + + + SubtitleTrackController.prototype.onManifestLoaded = function onManifestLoaded(data) { + var _this3 = this; + + var tracks = data.subtitles || []; + this.tracks = tracks; + this.trackId = -1; + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks }); + + // loop through available subtitle tracks and autoselect default if needed + // TODO: improve selection logic to handle forced, etc + tracks.forEach(function (track) { + if (track.default) { + // setting this.subtitleTrack will trigger internal logic + // if media has not been attached yet, it will fail + // we keep a reference to the default track id + // and we'll set subtitleTrack when onMediaAttached is triggered + if (_this3.media) { + _this3.subtitleTrack = track.id; + } else { + _this3.queuedDefaultTrack = track.id; + } + } + }); + }; + + // Trigger subtitle track playlist reload. + + + SubtitleTrackController.prototype.onTick = function onTick() { + var trackId = this.trackId; + var subtitleTrack = this.tracks[trackId]; + if (!subtitleTrack) { + return; + } + + var details = subtitleTrack.details; + // check if we need to load playlist for this subtitle Track + if (details === undefined || details.live === true) { + // track not retrieved yet, or live playlist we need to (re)load it + logger["b" /* logger */].log('(re)loading playlist for subtitle track ' + trackId); + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: trackId }); + } + }; + + SubtitleTrackController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(data) { + var _this4 = this; + + if (data.id < this.tracks.length) { + logger["b" /* logger */].log('subtitle track ' + data.id + ' loaded'); + this.tracks[data.id].details = data.details; + // check if current playlist is a live playlist + if (data.details.live && !this.timer) { + // if live playlist we will have to reload it periodically + // set reload period to playlist target duration + this.timer = setInterval(function () { + _this4.onTick(); + }, 1000 * data.details.targetduration, this); + } + if (!data.details.live && this.timer) { + // playlist is not live and timer is armed : stopping it + clearInterval(this.timer); + this.timer = null; + } + } + }; + + /** get alternate subtitle tracks list from playlist **/ + + + SubtitleTrackController.prototype.setSubtitleTrackInternal = function setSubtitleTrackInternal(newId) { + // check if level idx is valid + if (newId < -1 || newId >= this.tracks.length) { + return; + } + + // stopping live reloading timer if any + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + + var textTracks = filterSubtitleTracks(this.media.textTracks); + + // hide currently enabled subtitle track + if (this.trackId !== -1 && this.subtitleDisplay) { + textTracks[this.trackId].mode = 'hidden'; + } + + this.trackId = newId; + logger["b" /* logger */].log('switching to subtitle track ' + newId); + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_SWITCH, { id: newId }); + + if (newId === -1) { + return; + } + + var subtitleTrack = this.tracks[newId]; + if (this.subtitleDisplay) { + textTracks[newId].mode = 'showing'; + } + + // check if we need to load playlist for this subtitle Track + var details = subtitleTrack.details; + if (details === undefined || details.live === true) { + // track not retrieved yet, or live playlist we need to (re)load it + logger["b" /* logger */].log('(re)loading playlist for subtitle track ' + newId); + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId }); + } + }; + + subtitle_track_controller__createClass(SubtitleTrackController, [{ + key: 'subtitleTracks', + get: function get() { + return this.tracks; + } + + /** get index of the selected subtitle track (index in subtitle track lists) **/ + + }, { + key: 'subtitleTrack', + get: function get() { + return this.trackId; + } + + /** select a subtitle track, based on its index in subtitle track lists**/ + , + set: function set(subtitleTrackId) { + if (this.trackId !== subtitleTrackId) { + // || this.tracks[subtitleTrackId].details === undefined) { + this.setSubtitleTrackInternal(subtitleTrackId); + } + } + }]); + + return SubtitleTrackController; +}(event_handler); + +/* harmony default export */ var subtitle_track_controller = (subtitle_track_controller_SubtitleTrackController); +// EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules +var decrypter = __webpack_require__(4); + +// CONCATENATED MODULE: ./src/controller/subtitle-stream-controller.js +function subtitle_stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function subtitle_stream_controller__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; } + +function subtitle_stream_controller__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; } + +/* + * Subtitle Stream Controller +*/ + + + + + + +var subtitle_stream_controller_State = { + STOPPED: 'STOPPED', + IDLE: 'IDLE', + KEY_LOADING: 'KEY_LOADING', + FRAG_LOADING: 'FRAG_LOADING' +}; + +var subtitle_stream_controller_SubtitleStreamController = function (_EventHandler) { + subtitle_stream_controller__inherits(SubtitleStreamController, _EventHandler); + + function SubtitleStreamController(hls) { + subtitle_stream_controller__classCallCheck(this, SubtitleStreamController); + + var _this = subtitle_stream_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].ERROR, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].SUBTITLE_TRACKS_UPDATED, events["a" /* default */].SUBTITLE_TRACK_SWITCH, events["a" /* default */].SUBTITLE_TRACK_LOADED, events["a" /* default */].SUBTITLE_FRAG_PROCESSED)); + + _this.config = hls.config; + _this.vttFragSNsProcessed = {}; + _this.vttFragQueues = undefined; + _this.currentlyProcessing = null; + _this.state = subtitle_stream_controller_State.STOPPED; + _this.currentTrackId = -1; + _this.ticks = 0; + _this.decrypter = new decrypter["a" /* default */](hls.observer, hls.config); + return _this; + } + + SubtitleStreamController.prototype.destroy = function destroy() { + event_handler.prototype.destroy.call(this); + this.state = subtitle_stream_controller_State.STOPPED; + }; + + // Remove all queued items and create a new, empty queue for each track. + + + SubtitleStreamController.prototype.clearVttFragQueues = function clearVttFragQueues() { + var _this2 = this; + + this.vttFragQueues = {}; + this.tracks.forEach(function (track) { + _this2.vttFragQueues[track.id] = []; + }); + }; + + // If no frag is being processed and queue isn't empty, initiate processing of next frag in line. + + + SubtitleStreamController.prototype.nextFrag = function nextFrag() { + if (this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) { + var frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift(); + this.fragCurrent = frag; + this.hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag }); + this.state = subtitle_stream_controller_State.FRAG_LOADING; + } + }; + + // When fragment has finished processing, add sn to list of completed if successful. + + + SubtitleStreamController.prototype.onSubtitleFragProcessed = function onSubtitleFragProcessed(data) { + if (data.success) { + this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn); + } + this.currentlyProcessing = null; + this.state = subtitle_stream_controller_State.IDLE; + this.nextFrag(); + }; + + SubtitleStreamController.prototype.onMediaAttached = function onMediaAttached() { + this.state = subtitle_stream_controller_State.IDLE; + }; + + // If something goes wrong, procede to next frag, if we were processing one. + + + SubtitleStreamController.prototype.onError = function onError(data) { + var frag = data.frag; + // don't handle frag error not related to subtitle fragment + if (frag && frag.type !== 'subtitle') { + return; + } + if (this.currentlyProcessing) { + this.currentlyProcessing = null; + this.nextFrag(); + } + }; + + SubtitleStreamController.prototype.tick = function tick() { + var _this3 = this; + + this.ticks++; + if (this.ticks === 1) { + this.doTick(); + if (this.ticks > 1) { + setTimeout(function () { + _this3.tick(); + }, 1); + } + this.ticks = 0; + } + }; + + SubtitleStreamController.prototype.doTick = function doTick() { + var _this4 = this; + + switch (this.state) { + case subtitle_stream_controller_State.IDLE: + var tracks = this.tracks; + var trackId = this.currentTrackId; + + var processedFragSNs = this.vttFragSNsProcessed[trackId], + fragQueue = this.vttFragQueues[trackId], + currentFragSN = !!this.currentlyProcessing ? this.currentlyProcessing.sn : -1; + + var alreadyProcessed = function alreadyProcessed(frag) { + return processedFragSNs.indexOf(frag.sn) > -1; + }; + + var alreadyInQueue = function alreadyInQueue(frag) { + return fragQueue.some(function (fragInQueue) { + return fragInQueue.sn === frag.sn; + }); + }; + + // exit if tracks don't exist + if (!tracks) { + break; + } + var trackDetails; + + if (trackId < tracks.length) { + trackDetails = tracks[trackId].details; + } + + if (typeof trackDetails === 'undefined') { + break; + } + + // Add all fragments that haven't been, aren't currently being and aren't waiting to be processed, to queue. + trackDetails.fragments.forEach(function (frag) { + if (!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) { + // Load key if subtitles are encrypted + if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) { + logger["b" /* logger */].log('Loading key for ' + frag.sn); + _this4.state = subtitle_stream_controller_State.KEY_LOADING; + _this4.hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag }); + } else { + // Frags don't know their subtitle track ID, so let's just add that... + frag.trackId = trackId; + fragQueue.push(frag); + _this4.nextFrag(); + } + } + }); + } + }; + + // Got all new subtitle tracks. + + + SubtitleStreamController.prototype.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(data) { + var _this5 = this; + + logger["b" /* logger */].log('subtitle tracks updated'); + this.tracks = data.subtitleTracks; + this.clearVttFragQueues(); + this.vttFragSNsProcessed = {}; + this.tracks.forEach(function (track) { + _this5.vttFragSNsProcessed[track.id] = []; + }); + }; + + SubtitleStreamController.prototype.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(data) { + this.currentTrackId = data.id; + this.clearVttFragQueues(); + }; + + // Got a new set of subtitle fragments. + + + SubtitleStreamController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded() { + this.tick(); + }; + + SubtitleStreamController.prototype.onKeyLoaded = function onKeyLoaded() { + if (this.state === subtitle_stream_controller_State.KEY_LOADING) { + this.state = subtitle_stream_controller_State.IDLE; + this.tick(); + } + }; + + SubtitleStreamController.prototype.onFragLoaded = function onFragLoaded(data) { + var fragCurrent = this.fragCurrent, + decryptData = data.frag.decryptdata; + var fragLoaded = data.frag, + hls = this.hls; + if (this.state === subtitle_stream_controller_State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) { + // check to see if the payload needs to be decrypted + if (data.payload.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.method === 'AES-128') { + var startTime; + try { + startTime = performance.now(); + } catch (error) { + startTime = Date.now(); + } + // decrypt the subtitles + this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) { + var endTime; + try { + endTime = performance.now(); + } catch (error) { + endTime = Date.now(); + } + hls.trigger(events["a" /* default */].FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } }); + }); + } + } + }; + + return SubtitleStreamController; +}(event_handler); + +/* harmony default export */ var subtitle_stream_controller = (subtitle_stream_controller_SubtitleStreamController); +// CONCATENATED MODULE: ./src/config.js +/** + * HLS config + */ + + + + + + +//import FetchLoader from './utils/fetch-loader'; + + + + + + + + + +var hlsDefaultConfig = { + autoStartLoad: true, // used by stream-controller + startPosition: -1, // used by stream-controller + defaultAudioCodec: undefined, // used by stream-controller + debug: false, // used by logger + capLevelOnFPSDrop: false, // used by fps-controller + capLevelToPlayerSize: false, // used by cap-level-controller + initialLiveManifestSize: 1, // used by stream-controller + maxBufferLength: 30, // used by stream-controller + maxBufferSize: 60 * 1000 * 1000, // used by stream-controller + maxBufferHole: 0.5, // used by stream-controller + maxSeekHole: 2, // used by stream-controller + lowBufferWatchdogPeriod: 0.5, // used by stream-controller + highBufferWatchdogPeriod: 3, // used by stream-controller + nudgeOffset: 0.1, // used by stream-controller + nudgeMaxRetry: 3, // used by stream-controller + maxFragLookUpTolerance: 0.25, // used by stream-controller + liveSyncDurationCount: 3, // used by stream-controller + liveMaxLatencyDurationCount: Infinity, // used by stream-controller + liveSyncDuration: undefined, // used by stream-controller + liveMaxLatencyDuration: undefined, // used by stream-controller + maxMaxBufferLength: 600, // used by stream-controller + enableWorker: true, // used by demuxer + enableSoftwareAES: true, // used by decrypter + manifestLoadingTimeOut: 10000, // used by playlist-loader + manifestLoadingMaxRetry: 1, // used by playlist-loader + manifestLoadingRetryDelay: 1000, // used by playlist-loader + manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader + startLevel: undefined, // used by level-controller + levelLoadingTimeOut: 10000, // used by playlist-loader + levelLoadingMaxRetry: 4, // used by playlist-loader + levelLoadingRetryDelay: 1000, // used by playlist-loader + levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader + fragLoadingTimeOut: 20000, // used by fragment-loader + fragLoadingMaxRetry: 6, // used by fragment-loader + fragLoadingRetryDelay: 1000, // used by fragment-loader + fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader + fragLoadingLoopThreshold: 3, // used by stream-controller + startFragPrefetch: false, // used by stream-controller + fpsDroppedMonitoringPeriod: 5000, // used by fps-controller + fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller + appendErrorMaxRetry: 3, // used by buffer-controller + loader: xhr_loader, + //loader: FetchLoader, + fLoader: undefined, + pLoader: undefined, + xhrSetup: undefined, + fetchSetup: undefined, + abrController: abr_controller, + bufferController: buffer_controller, + capLevelController: cap_level_controller, + fpsController: fps_controller, + stretchShortVideoTrack: false, // used by mp4-remuxer + maxAudioFramesDrift: 1, // used by mp4-remuxer + forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer + abrEwmaFastLive: 3, // used by abr-controller + abrEwmaSlowLive: 9, // used by abr-controller + abrEwmaFastVoD: 3, // used by abr-controller + abrEwmaSlowVoD: 9, // used by abr-controller + abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller + abrBandWidthFactor: 0.95, // used by abr-controller + abrBandWidthUpFactor: 0.7, // used by abr-controller + abrMaxWithRealBitrate: false, // used by abr-controller + maxStarvationDelay: 4, // used by abr-controller + maxLoadingDelay: 4, // used by abr-controller + minAutoBitrate: 0 // used by hls +}; + +if (true) { + hlsDefaultConfig.subtitleStreamController = subtitle_stream_controller; + hlsDefaultConfig.subtitleTrackController = subtitle_track_controller; + hlsDefaultConfig.timelineController = timeline_controller; + hlsDefaultConfig.cueHandler = cues_namespaceObject; + hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller + hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller + hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller + hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller + hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller + hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller +} + +if (true) { + hlsDefaultConfig.audioStreamController = audio_stream_controller; + hlsDefaultConfig.audioTrackController = audio_track_controller; +} +// CONCATENATED MODULE: ./src/hls.js +var hls__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; }; }(); + +function hls__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * HLS interface + */ + + + + + + + + + + + + + + + + +var hls_Hls = function () { + Hls.isSupported = function isSupported() { + var mediaSource = getMediaSource(); + var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer; + var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); + + // if SourceBuffer is exposed ensure its API is valid + // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible + var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function'; + return isTypeSupported && sourceBufferValidAPI; + }; + + hls__createClass(Hls, null, [{ + key: 'version', + get: function get() { + return "0.8.7"; + } + }, { + key: 'Events', + get: function get() { + return events["a" /* default */]; + } + }, { + key: 'ErrorTypes', + get: function get() { + return errors["b" /* ErrorTypes */]; + } + }, { + key: 'ErrorDetails', + get: function get() { + return errors["a" /* ErrorDetails */]; + } + }, { + key: 'DefaultConfig', + get: function get() { + if (!Hls.defaultConfig) { + return hlsDefaultConfig; + } + return Hls.defaultConfig; + }, + set: function set(defaultConfig) { + Hls.defaultConfig = defaultConfig; + } + }]); + + function Hls() { + var _this = this; + + var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + hls__classCallCheck(this, Hls); + + var defaultConfig = Hls.DefaultConfig; + + if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) { + throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration'); + } + + for (var prop in defaultConfig) { + if (prop in config) { + continue; + } + config[prop] = defaultConfig[prop]; + } + + if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) { + throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"'); + } + + if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) { + throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"'); + } + + Object(logger["a" /* enableLogs */])(config.debug); + this.config = config; + this._autoLevelCapping = -1; + // observer setup + var observer = this.observer = new events_default.a(); + observer.trigger = function trigger(event) { + for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + data[_key - 1] = arguments[_key]; + } + + observer.emit.apply(observer, [event, event].concat(data)); + }; + + observer.off = function off(event) { + for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + data[_key2 - 1] = arguments[_key2]; + } + + observer.removeListener.apply(observer, [event].concat(data)); + }; + this.on = observer.on.bind(observer); + this.off = observer.off.bind(observer); + this.trigger = observer.trigger.bind(observer); + + // core controllers and network loaders + var abrController = this.abrController = new config.abrController(this); + var bufferController = new config.bufferController(this); + var capLevelController = new config.capLevelController(this); + var fpsController = new config.fpsController(this); + var playListLoader = new playlist_loader(this); + var fragmentLoader = new fragment_loader(this); + var keyLoader = new key_loader(this); + var id3TrackController = new id3_track_controller(this); + + // network controllers + var levelController = this.levelController = new level_controller(this); + var streamController = this.streamController = new stream_controller(this); + var networkControllers = [levelController, streamController]; + + // optional audio stream controller + var Controller = config.audioStreamController; + if (Controller) { + networkControllers.push(new Controller(this)); + } + this.networkControllers = networkControllers; + + var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController]; + + // optional audio track and subtitle controller + Controller = config.audioTrackController; + if (Controller) { + var audioTrackController = new Controller(this); + this.audioTrackController = audioTrackController; + coreComponents.push(audioTrackController); + } + + Controller = config.subtitleTrackController; + if (Controller) { + var subtitleTrackController = new Controller(this); + this.subtitleTrackController = subtitleTrackController; + coreComponents.push(subtitleTrackController); + } + + // optional subtitle controller + [config.subtitleStreamController, config.timelineController].forEach(function (Controller) { + if (Controller) { + coreComponents.push(new Controller(_this)); + } + }); + this.coreComponents = coreComponents; + } + + Hls.prototype.destroy = function destroy() { + logger["b" /* logger */].log('destroy'); + this.trigger(events["a" /* default */].DESTROYING); + this.detachMedia(); + this.coreComponents.concat(this.networkControllers).forEach(function (component) { + component.destroy(); + }); + this.url = null; + this.observer.removeAllListeners(); + this._autoLevelCapping = -1; + }; + + Hls.prototype.attachMedia = function attachMedia(media) { + logger["b" /* logger */].log('attachMedia'); + this.media = media; + this.trigger(events["a" /* default */].MEDIA_ATTACHING, { media: media }); + }; + + Hls.prototype.detachMedia = function detachMedia() { + logger["b" /* logger */].log('detachMedia'); + this.trigger(events["a" /* default */].MEDIA_DETACHING); + this.media = null; + }; + + Hls.prototype.loadSource = function loadSource(url) { + url = url_toolkit_default.a.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true }); + logger["b" /* logger */].log('loadSource:' + url); + this.url = url; + // when attaching to a source URL, trigger a playlist load + this.trigger(events["a" /* default */].MANIFEST_LOADING, { url: url }); + }; + + Hls.prototype.startLoad = function startLoad() { + var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1; + + logger["b" /* logger */].log('startLoad(' + startPosition + ')'); + this.networkControllers.forEach(function (controller) { + controller.startLoad(startPosition); + }); + }; + + Hls.prototype.stopLoad = function stopLoad() { + logger["b" /* logger */].log('stopLoad'); + this.networkControllers.forEach(function (controller) { + controller.stopLoad(); + }); + }; + + Hls.prototype.swapAudioCodec = function swapAudioCodec() { + logger["b" /* logger */].log('swapAudioCodec'); + this.streamController.swapAudioCodec(); + }; + + Hls.prototype.recoverMediaError = function recoverMediaError() { + logger["b" /* logger */].log('recoverMediaError'); + var media = this.media; + this.detachMedia(); + this.attachMedia(media); + }; + + /** Return all quality levels **/ + + + hls__createClass(Hls, [{ + key: 'levels', + get: function get() { + return this.levelController.levels; + } + + /** Return current playback quality level **/ + + }, { + key: 'currentLevel', + get: function get() { + return this.streamController.currentLevel; + } + + /* set quality level immediately (-1 for automatic level selection) */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set currentLevel:' + newLevel); + this.loadLevel = newLevel; + this.streamController.immediateLevelSwitch(); + } + + /** Return next playback quality level (quality level of next fragment) **/ + + }, { + key: 'nextLevel', + get: function get() { + return this.streamController.nextLevel; + } + + /* set quality level for next fragment (-1 for automatic level selection) */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set nextLevel:' + newLevel); + this.levelController.manualLevel = newLevel; + this.streamController.nextLevelSwitch(); + } + + /** Return the quality level of current/last loaded fragment **/ + + }, { + key: 'loadLevel', + get: function get() { + return this.levelController.level; + } + + /* set quality level for current/next loaded fragment (-1 for automatic level selection) */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set loadLevel:' + newLevel); + this.levelController.manualLevel = newLevel; + } + + /** Return the quality level of next loaded fragment **/ + + }, { + key: 'nextLoadLevel', + get: function get() { + return this.levelController.nextLoadLevel; + } + + /** set quality level of next loaded fragment **/ + , + set: function set(level) { + this.levelController.nextLoadLevel = level; + } + + /** Return first level (index of first level referenced in manifest) + **/ + + }, { + key: 'firstLevel', + get: function get() { + return Math.max(this.levelController.firstLevel, this.minAutoLevel); + } + + /** set first level (index of first level referenced in manifest) + **/ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set firstLevel:' + newLevel); + this.levelController.firstLevel = newLevel; + } + + /** Return start level (level of first fragment that will be played back) + if not overrided by user, first level appearing in manifest will be used as start level + if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) + **/ + + }, { + key: 'startLevel', + get: function get() { + return this.levelController.startLevel; + } + + /** set start level (level of first fragment that will be played back) + if not overrided by user, first level appearing in manifest will be used as start level + if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) + **/ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set startLevel:' + newLevel); + var hls = this; + // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel + if (newLevel !== -1) { + newLevel = Math.max(newLevel, hls.minAutoLevel); + } + hls.levelController.startLevel = newLevel; + } + + /** Return the capping/max level value that could be used by automatic level selection algorithm **/ + + }, { + key: 'autoLevelCapping', + get: function get() { + return this._autoLevelCapping; + } + + /** set the capping/max level value that could be used by automatic level selection algorithm **/ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set autoLevelCapping:' + newLevel); + this._autoLevelCapping = newLevel; + } + + /* check if we are in automatic level selection mode */ + + }, { + key: 'autoLevelEnabled', + get: function get() { + return this.levelController.manualLevel === -1; + } + + /* return manual level */ + + }, { + key: 'manualLevel', + get: function get() { + return this.levelController.manualLevel; + } + + /* return min level selectable in auto mode according to config.minAutoBitrate */ + + }, { + key: 'minAutoLevel', + get: function get() { + var hls = this, + levels = hls.levels, + minAutoBitrate = hls.config.minAutoBitrate, + len = levels ? levels.length : 0; + for (var i = 0; i < len; i++) { + var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate; + if (levelNextBitrate > minAutoBitrate) { + return i; + } + } + return 0; + } + + /* return max level selectable in auto mode according to autoLevelCapping */ + + }, { + key: 'maxAutoLevel', + get: function get() { + var hls = this; + var levels = hls.levels; + var autoLevelCapping = hls.autoLevelCapping; + var maxAutoLevel = void 0; + if (autoLevelCapping === -1 && levels && levels.length) { + maxAutoLevel = levels.length - 1; + } else { + maxAutoLevel = autoLevelCapping; + } + return maxAutoLevel; + } + + // return next auto level + + }, { + key: 'nextAutoLevel', + get: function get() { + var hls = this; + // ensure next auto level is between min and max auto level + return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel); + } + + // this setter is used to force next auto level + // this is useful to force a switch down in auto mode : in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example) + // forced value is valid for one fragment. upon succesful frag loading at forced level, this value will be resetted to -1 by ABR controller + , + set: function set(nextLevel) { + var hls = this; + hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel); + } + + /** get alternate audio tracks list from playlist **/ + + }, { + key: 'audioTracks', + get: function get() { + var audioTrackController = this.audioTrackController; + return audioTrackController ? audioTrackController.audioTracks : []; + } + + /** get index of the selected audio track (index in audio track lists) **/ + + }, { + key: 'audioTrack', + get: function get() { + var audioTrackController = this.audioTrackController; + return audioTrackController ? audioTrackController.audioTrack : -1; + } + + /** select an audio track, based on its index in audio track lists**/ + , + set: function set(audioTrackId) { + var audioTrackController = this.audioTrackController; + if (audioTrackController) { + audioTrackController.audioTrack = audioTrackId; + } + } + }, { + key: 'liveSyncPosition', + get: function get() { + return this.streamController.liveSyncPosition; + } + + /** get alternate subtitle tracks list from playlist **/ + + }, { + key: 'subtitleTracks', + get: function get() { + var subtitleTrackController = this.subtitleTrackController; + return subtitleTrackController ? subtitleTrackController.subtitleTracks : []; + } + + /** get index of the selected subtitle track (index in subtitle track lists) **/ + + }, { + key: 'subtitleTrack', + get: function get() { + var subtitleTrackController = this.subtitleTrackController; + return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1; + } + + /** select an subtitle track, based on its index in subtitle track lists**/ + , + set: function set(subtitleTrackId) { + var subtitleTrackController = this.subtitleTrackController; + if (subtitleTrackController) { + subtitleTrackController.subtitleTrack = subtitleTrackId; + } + } + }, { + key: 'subtitleDisplay', + get: function get() { + var subtitleTrackController = this.subtitleTrackController; + return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false; + }, + set: function set(value) { + var subtitleTrackController = this.subtitleTrackController; + if (subtitleTrackController) { + subtitleTrackController.subtitleDisplay = value; + } + } + }]); + + return Hls; +}(); + +/* harmony default export */ var src_hls = __webpack_exports__["default"] = (hls_Hls); + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +function webpackBootstrapFunc (modules) { +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.l = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; + +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; + +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; + +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; + +/******/ // on error function for async loading +/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; + + var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE) + return f.default || f // try to call default if defined to also support babel esmodule exports +} + +// http://stackoverflow.com/a/2593661/130442 +function quoteRegExp (str) { + return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') +} + +function getModuleDependencies (module) { + var retval = [] + var fnString = module.toString() + var wrapperSignature = fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/) + if (!wrapperSignature) return retval + + var webpackRequireName = wrapperSignature[1] + var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + '\\((\/\\*.*?\\*\/)?\s?.*?([\\.|\\-|\\w|\/|@]+).*?\\)', 'g') // additional chars when output.pathinfo is true + var match + while ((match = re.exec(fnString))) { + retval.push(match[3]) + } + return retval +} + +function getRequiredModules (sources, moduleId) { + var modulesQueue = [moduleId] + var requiredModules = [] + var seenModules = {} + + while (modulesQueue.length) { + var moduleToCheck = modulesQueue.pop() + if (seenModules[moduleToCheck] || !sources[moduleToCheck]) continue + seenModules[moduleToCheck] = true + requiredModules.push(moduleToCheck) + var newModules = getModuleDependencies(sources[moduleToCheck]) + modulesQueue = modulesQueue.concat(newModules) + } + + return requiredModules +} + +module.exports = function (moduleId, options) { + options = options || {} + var sources = __webpack_require__.m + + var requiredModules = options.all ? Object.keys(sources) : getRequiredModules(sources, moduleId) + var src = '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[id].toString() }).join(',') + '})(self);' + + var blob = new window.Blob([src], { type: 'text/javascript' }) + if (options.bare) { return blob } + + var URL = window.URL || window.webkitURL || window.mozURL || window.msURL + + var workerUrl = URL.createObjectURL(blob) + var worker = new window.Worker(workerUrl) + worker.objectURL = workerUrl + + return worker +} + + +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_events__); +/* demuxer web worker. + * - listen to worker message, and trigger DemuxerInline upon reception of Fragments. + * - 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. + */ + + + + + + +var DemuxerWorker = function DemuxerWorker(self) { + // observer setup + var observer = new __WEBPACK_IMPORTED_MODULE_3_events___default.a(); + observer.trigger = function trigger(event) { + for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + data[_key - 1] = arguments[_key]; + } + + observer.emit.apply(observer, [event, event].concat(data)); + }; + + observer.off = function off(event) { + for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + data[_key2 - 1] = arguments[_key2]; + } + + observer.removeListener.apply(observer, [event].concat(data)); + }; + + var forwardMessage = function forwardMessage(ev, data) { + self.postMessage({ event: ev, data: data }); + }; + + self.addEventListener('message', function (ev) { + var data = ev.data; + //console.log('demuxer cmd:' + data.cmd); + switch (data.cmd) { + case 'init': + var config = JSON.parse(data.config); + self.demuxer = new __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__["a" /* default */](observer, data.typeSupported, config, data.vendor); + try { + Object(__WEBPACK_IMPORTED_MODULE_2__utils_logger__["a" /* enableLogs */])(config.debug === true); + } catch (err) { + console.warn('demuxerWorker: unable to enable logs'); + } + // signal end of worker init + forwardMessage('init', null); + break; + case 'demux': + self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS); + break; + default: + break; + } + }); + + // forward events to main thread + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_DECRYPTED, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSED, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].ERROR, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_METADATA, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_USERDATA, forwardMessage); + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].INIT_PTS_FOUND, forwardMessage); + + // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy) + observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_DATA, function (ev, data) { + var transferable = []; + var message = { event: ev, data: data }; + if (data.data1) { + message.data1 = data.data1.buffer; + transferable.push(data.data1.buffer); + delete data.data1; + } + if (data.data2) { + message.data2 = data.data2.buffer; + transferable.push(data.data2.buffer); + delete data.data2; + } + self.postMessage(message, transferable); + }); +}; + +/* harmony default export */ __webpack_exports__["default"] = (DemuxerWorker); + +/***/ }) +/******/ ])["default"]; +}); +//# sourceMappingURL=hls.js.map \ No newline at end of file diff --git a/lib/hls.js/hls.js.map b/lib/hls.js/hls.js.map new file mode 100644 index 00000000..91cdb82b --- /dev/null +++ b/lib/hls.js/hls.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap cb2b7ace4e98a4df4dfc","webpack:///./src/utils/logger.js","webpack:///./src/events.js","webpack:///./src/errors.js","webpack:///./src/demux/id3.js","webpack:///./src/crypt/aes-crypto.js","webpack:///./src/crypt/fast-aes-key.js","webpack:///./src/crypt/aes-decryptor.js","webpack:///./src/crypt/decrypter.js","webpack:///./node_modules/events/events.js","webpack:///./node_modules/url-toolkit/src/url-toolkit.js","webpack:///./src/demux/adts.js","webpack:///./src/demux/aacdemuxer.js","webpack:///./src/demux/mp4demuxer.js","webpack:///./src/demux/mpegaudio.js","webpack:///./src/demux/exp-golomb.js","webpack:///./src/demux/sample-aes.js","webpack:///./src/demux/tsdemuxer.js","webpack:///./src/demux/mp3demuxer.js","webpack:///./src/helper/aac.js","webpack:///./src/remux/mp4-generator.js","webpack:///./src/remux/mp4-remuxer.js","webpack:///./src/remux/passthrough-remuxer.js","webpack:///./src/demux/demuxer-inline.js","webpack:///./src/event-handler.js","webpack:///./src/utils/attr-list.js","webpack:///./src/utils/codecs.js","webpack:///./src/loader/playlist-loader.js","webpack:///./src/loader/fragment-loader.js","webpack:///./src/loader/key-loader.js","webpack:///./src/utils/binary-search.js","webpack:///./src/helper/buffer-helper.js","webpack:///./src/helper/mediasource-helper.js","webpack:///./src/demux/demuxer.js","webpack:///./src/helper/level-helper.js","webpack:///./src/utils/timeRanges.js","webpack:///./src/utils/discontinuities.js","webpack:///./src/controller/stream-controller.js","webpack:///./src/controller/level-controller.js","webpack:///./src/controller/id3-track-controller.js","webpack:///./src/utils/ewma.js","webpack:///./src/utils/ewma-bandwidth-estimator.js","webpack:///./src/controller/abr-controller.js","webpack:///./src/controller/buffer-controller.js","webpack:///./src/controller/cap-level-controller.js","webpack:///./src/controller/fps-controller.js","webpack:///./src/utils/xhr-loader.js","webpack:///./src/controller/audio-track-controller.js","webpack:///./src/controller/audio-stream-controller.js","webpack:///./src/utils/vttcue.js","webpack:///./src/utils/vttparser.js","webpack:///./src/utils/cues.js","webpack:///./src/utils/cea-608-parser.js","webpack:///./src/utils/output-filter.js","webpack:///./src/utils/webvtt-parser.js","webpack:///./src/controller/timeline-controller.js","webpack:///./src/controller/subtitle-track-controller.js","webpack:///./src/controller/subtitle-stream-controller.js","webpack:///./src/config.js","webpack:///./src/hls.js","webpack:///./node_modules/webworkify-webpack/index.js","webpack:///./src/demux/demuxer-worker.js"],"names":["noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","formatMsg","type","msg","consolePrintFn","func","self","console","args","apply","exportLoggerFunctions","debugConfig","functions","forEach","bind","enableLogs","e","logger","MEDIA_ATTACHING","MEDIA_ATTACHED","MEDIA_DETACHING","MEDIA_DETACHED","BUFFER_RESET","BUFFER_CODECS","BUFFER_CREATED","BUFFER_APPENDING","BUFFER_APPENDED","BUFFER_EOS","BUFFER_FLUSHING","BUFFER_FLUSHED","MANIFEST_LOADING","MANIFEST_LOADED","MANIFEST_PARSED","LEVEL_SWITCH","LEVEL_SWITCHING","LEVEL_SWITCHED","LEVEL_LOADING","LEVEL_LOADED","LEVEL_UPDATED","LEVEL_PTS_UPDATED","AUDIO_TRACKS_UPDATED","AUDIO_TRACK_SWITCH","AUDIO_TRACK_SWITCHING","AUDIO_TRACK_SWITCHED","AUDIO_TRACK_LOADING","AUDIO_TRACK_LOADED","SUBTITLE_TRACKS_UPDATED","SUBTITLE_TRACK_SWITCH","SUBTITLE_TRACK_LOADING","SUBTITLE_TRACK_LOADED","SUBTITLE_FRAG_PROCESSED","INIT_PTS_FOUND","FRAG_LOADING","FRAG_LOAD_PROGRESS","FRAG_LOAD_EMERGENCY_ABORTED","FRAG_LOADED","FRAG_DECRYPTED","FRAG_PARSING_INIT_SEGMENT","FRAG_PARSING_USERDATA","FRAG_PARSING_METADATA","FRAG_PARSING_DATA","FRAG_PARSED","FRAG_BUFFERED","FRAG_CHANGED","FPS_DROP","FPS_DROP_LEVEL_CAPPING","ERROR","DESTROYING","KEY_LOADING","KEY_LOADED","STREAM_STATE_TRANSITION","ErrorTypes","NETWORK_ERROR","MEDIA_ERROR","MUX_ERROR","OTHER_ERROR","ErrorDetails","MANIFEST_LOAD_ERROR","MANIFEST_LOAD_TIMEOUT","MANIFEST_PARSING_ERROR","MANIFEST_INCOMPATIBLE_CODECS_ERROR","LEVEL_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","LEVEL_SWITCH_ERROR","AUDIO_TRACK_LOAD_ERROR","AUDIO_TRACK_LOAD_TIMEOUT","FRAG_LOAD_ERROR","FRAG_LOOP_LOADING_ERROR","FRAG_LOAD_TIMEOUT","FRAG_DECRYPT_ERROR","FRAG_PARSING_ERROR","REMUX_ALLOC_ERROR","KEY_LOAD_ERROR","KEY_LOAD_TIMEOUT","BUFFER_ADD_CODEC_ERROR","BUFFER_APPEND_ERROR","BUFFER_APPENDING_ERROR","BUFFER_STALLED_ERROR","BUFFER_FULL_ERROR","BUFFER_SEEK_OVER_HOLE","BUFFER_NUDGE_ON_STALL","INTERNAL_EXCEPTION","ID3","isHeader","data","offset","length","isFooter","getID3Data","front","size","_readSize","subarray","undefined","getTimeStamp","frames","getID3Frames","i","frame","isTimeStampFrame","_readTimeStamp","key","_getFrameData","String","fromCharCode","id3Data","end","frameData","_decodeFrame","push","_decodePrivFrame","_decodeTextFrame","_decodeURLFrame","timeStampFrame","byteLength","Uint8Array","pts33Bit","timestamp","Math","round","owner","_utf8ArrayToStr","privateData","buffer","index","description","value","text","url","array","len","c","char2","char3","out","utf8ArrayToStr","AESCrypto","subtle","iv","aesIV","decrypt","name","FastAESKey","expandKey","importKey","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","DataView","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","d","x","xi","sx","x2","x4","x8","t","keyBuffer","sameKey","keySize","Error","ksRows","ksRow","invKsRow","keySchedule","invKeySchedule","sbox","prev","networkToHostOrderSwap","word","inputArrayBuffer","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","swapWord","destroy","observer","config","logEnabled","browserCrypto","crypto","webkitSubtle","disableWebCrypto","isSync","enableSoftwareAES","callback","decryptor","fastAesKey","then","aesKey","catch","err","onWebCryptoError","result","message","trigger","Event","details","fatal","reason","getAudioConfig","audioCodec","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","navigator","toLowerCase","manifestCodec","adtsSampleingRates","test","Array","indexOf","samplerate","channelCount","codec","isHeaderPattern","getHeaderLength","getFullFrameLength","headerLength","frameLength","newOffset","initTrackConfig","track","getFrameDuration","parseFrameHeader","pts","frameIndex","frameDuration","stamp","appendFrame","header","aacSample","unit","dts","samples","sample","remuxer","resetInitSegment","initSegment","videoCodec","duration","_audioTrack","container","id","sequenceNumber","isAAC","inputTimeScale","resetTimeStamp","probe","append","timeOffset","contiguous","accurateTimeOffset","id3Samples","ADTS","remux","UINT32_MAX","pow","initPTS","initData","MP4Demuxer","parseInitSegment","tracks","audio","video","audiovideo","findBox","start","min","bin2str","readUint32","val","writeUint32","path","results","subresults","endbox","slice","concat","traks","tkhd","trak","version","trackId","mdhd","timescale","hdlr","hdlrType","codecBox","codecType","getStartDTS","fragment","trafs","baseTimes","map","traf","tfhd","scale","baseTime","tfdt","isFinite","offsetStartDTS","baseMediaDecodeTime","max","upper","floor","lower","startDTS","MpegAudio","BitratesMap","SamplingRateMap","parseHeader","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","padding","bytesAvailable","bitsAvailable","loadWord","position","workingBytes","availableBytes","set","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","readUByte","readUShort","readUInt","skipScalingList","lastScale","nextScale","j","deltaScale","readSPS","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","profileIdc","profileCompat","levelIdc","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","scalingListCount","chromaFormatIdc","picOrderCntType","pixelRatio","aspectRatioIdc","width","ceil","height","readSliceType","decryptdata","discardEPB","decrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","sync","curUnit","encryptedBuffer","byteOffset","localthis","decryptedData","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","units","RemuxerTrackIdConfig","id3","typeSupported","sampleAes","setDecryptData","method","syncOffset","TSDemuxer","_syncOffset","scanwindow","createTrack","pid","dropped","pmtParsed","_pmtId","_avcTrack","_id3Track","_txtTrack","aacOverFlow","aacLastPTS","avcSample","_duration","stt","atf","pes","unknownPIDs","avcTrack","audioTrack","id3Track","avcId","audioId","id3Id","pmtId","avcData","pesData","audioData","parsePAT","_parsePAT","parsePMT","_parsePMT","parsePES","_parsePES","parseAVCPES","_parseAVCPES","parseAACPES","_parseAACPES","parseMPEGPES","_parseMPEGPES","parseID3PES","_parseID3PES","parsedPIDs","mpeg","mp3","avc","decryptAndRemux","videoTrack","textTrack","decryptAndRemuxAvc","_initPTS","_initDTS","mpegSupported","isSampleAes","sectionLength","tableEnd","programInfoLength","stream","frag","pesFlags","pesPrefix","pesLen","pesHdrLen","pesPts","pesDts","payloadStartOffset","newData","splice","dataLen","pushAccesUnit","nbSamples","forceKeyFrameOnDiscontinuity","sps","last","_parseAVCNALu","expGolombDecoder","spsfound","createAVCSample","audFound","sliceType","payloadType","payloadSize","endOfCaptions","b","countryCode","providerCode","userStructure","userDataType","firstByte","secondByte","totalCCs","byteArray","_insertSampleInOrder","bytes","codecarray","codecstring","h","toString","pps","arr","pos","_getLastNalUnit","lastUnit","overflow","state","naluState","lastState","unitType","lastUnitStart","lastUnitType","tmp","EPBPositions","newLength","sourceIndex","shift","startOffset","newPTS","abs","AAC","getSilentFrame","MP4","init","types","avc1","avcC","btrt","dinf","dref","esds","ftyp","mdat","mdia","mfhd","minf","moof","moov","mp4a","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsd","stsz","stts","trun","trex","vmhd","smhd","hasOwnProperty","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","payload","prototype","call","arguments","upperWordDuration","lowerWordDuration","sn","boxes","flags","dependsOn","isDependedOn","hasRedundancy","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","arraylen","cts","isLeading","paddingValue","isNonSync","degradPrio","movie","MAX_SILENT_FRAME_DURATION","vendor","isSafari","match","ISGenerated","defaultTimeStamp","generateIS","nbAudioSamples","nbVideoSamples","audioTimeOffset","videoTimeOffset","audiovideoDeltaDts","remuxAudio","audioTrackLength","endPTS","startPTS","remuxVideo","videoData","remuxEmptyAudio","remuxID3","remuxText","audioSamples","videoSamples","computePTSDTS","initDTS","Infinity","metadata","Object","keys","timeScale","mp4SampleDuration","firstPTS","firstDTS","nextDTS","lastPTS","lastDTS","inputSamples","outputSamples","ptsNormalize","_PTSNormalize","nextAvcDts","sort","a","deltadts","deltapts","PTSDTSshift","reduce","curr","delta","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","setUint32","avcSampleUnits","mp4SampleLength","compositionTimeOffset","unitData","unitDataLen","lastFrameDuration","stretchShortVideoTrack","maxBufferHole","maxSeekHole","gapTolerance","deltaToFrameEnd","nextAudioPts","data1","data2","endDTS","nb","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","mp4Sample","fillFrame","maxAudioFramesDrift","nextPts","toFixed","missing","newStamp","audioSample","numMissingFrames","unitLen","lastSampleDuration","sampleDuration","silentFrame","reference","rawData","streamType","demuxer","discontinuity","trackSwitch","defaultInitPTS","startTime","performance","now","Date","endTime","stats","tstart","tdecrypt","pushDecrypted","muxConfig","demux","mux","hls","onEvent","events","handledEvents","useGenericHandler","registerListeners","unregisterListeners","isEventHandler","event","on","off","onEventGeneric","eventToFunction","funcName","replace","constructor","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","parseAttrList","attr","decimalInteger","attrName","intValue","parseInt","Number","MAX_SAFE_INTEGER","hexadecimalInteger","stringValue","hexadecimalIntegerAsNumber","decimalFloatingPoint","parseFloat","enumeratedString","decimalResolution","res","exec","input","lastIndex","quote","lastIndexOf","sampleEntryCodesISO","isCodecType","typeCodes","isCodecSupportedInMp4","MediaSource","isTypeSupported","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","LEVEL_PLAYLIST_REGEX_FAST","RegExp","source","join","LEVEL_PLAYLIST_REGEX_SLOW","_uri","reluri","URLToolkit","buildAbsoluteURL","baseuri","alwaysNormalize","_url","_byteRange","_decryptdata","tagList","createInitializationVector","segmentNumber","uint8View","fragmentDecryptdataFromLevelkey","levelkey","uri","cloneObj","obj","JSON","parse","stringify","relurl","baseurl","_programDateTime","rawProgramDateTime","byteRange","rawByteRange","params","split","lastByteRangeEndOffset","findGroup","groups","mediaGroupId","matchingGroup","group","loaders","loaderName","loader","EventHandler","onManifestLoading","load","onLevelLoading","level","onAudioTrackLoading","onSubtitleTrackLoading","context","loaderContext","abort","retry","timeout","retryDelay","maxRetryDelay","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingMaxRetry","levelLoadingTimeOut","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","pLoader","responseType","loaderConfig","loaderCallbacks","maxRetry","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","resolve","baseUrl","parseMasterPlaylist","string","levels","setCodecs","codecs","filtered","filter","preferred","unknownCodecs","resolution","bitrate","NAME","CODECS","avc1toavcoti","parseMasterPlaylistMedia","audioGroups","medias","media","TYPE","groupId","default","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","URI","lang","LANGUAGE","groupCodec","avcdata","substr","parseLevelPlaylist","currentSN","totalduration","fragments","live","startSN","cc","prevFrag","title","isNaN","byteRangeEndOffset","programDateTime","value1","value2","toUpperCase","targetduration","decryptparams","keyAttrs","decryptmethod","decrypturi","decryptiv","startParams","startAttrs","startTimeOffset","mapAttrs","BYTERANGE","pop","averagetargetduration","endSN","startCC","endCC","response","networkDetails","tload","isLevel","levelId","levelDetails","audioTracks","tparsed","l","AUDIO","subtitles","embeddedAudioFound","unshift","onFragLoading","loaded","fLoader","progressData","byteRangeStartOffset","rangeStart","rangeEnd","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","decryptkey","decrypturl","onKeyLoading","fragLoadingMaxRetry","fragLoadingRetryDelay","BinarySearch","search","list","comparisonFunction","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","BufferHelper","isBuffered","buffered","bufferInfo","maxHoleDuration","vbuffered","bufferedInfo","nextStart","buffered2","bufferLen","bufferStart","bufferEnd","bufferStartNext","diff","buf2len","buf2end","getMediaSource","window","WebKitMediaSource","emit","removeListener","forwardMessage","ev","mp4","enableWorker","Worker","w","work","onwmsg","onWorkerMessage","addEventListener","onerror","filename","lineno","postMessage","cmd","URL","revokeObjectURL","objectURL","removeEventListener","terminate","removeAllListeners","lastFrag","nextSN","ArrayBuffer","updatePTS","fromIdx","toIdx","fragFrom","fragTo","fragToPTS","updateFragPTSDTS","maxStartPTS","deltaPTS","drift","fragIdx","PTSKnown","mergeDetails","oldDetails","newDetails","oldfragments","newfragments","ccOffset","PTSFrag","oldFrag","newFrag","backtracked","sliding","TimeRanges","r","findFirstFragWithCC","firstFrag","currentFrag","findFragWithCC","CC","candidate","shouldAlignOnDiscontinuities","lastLevel","shouldAlign","findDiscontinuousReferenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","adjustPts","alignDiscontinuities","referenceFrag","lastPDT","newPDT","State","STOPPED","IDLE","FRAG_LOADING_WAITING_RETRY","WAITING_LEVEL","PARSING","PARSED","ENDED","audioCodecSwap","ticks","_state","ontick","tick","stopLoad","timer","clearInterval","startLoad","startPosition","lastCurrentTime","setInterval","fragLoadError","startFragRequested","startLevel","bitrateTest","nextLoadLevel","loadedmetadata","nextLoadPosition","forceStartLoad","fragCurrent","fragPrevious","doTick","setTimeout","_doTickIdle","retryDate","seeking","_checkBuffer","_checkFragmentChanged","levelLastLoaded","startFragPrefetch","currentTime","levelInfo","levelBitrate","maxBufLen","maxBufferSize","maxBufferLength","maxMaxBufferLength","mediaBuffer","altAudio","_fetchPayloadOrEos","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","_loadFragmentOrKey","maxLatency","liveMaxLatencyDuration","liveMaxLatencyDurationCount","maxFragLookUpTolerance","liveSyncPosition","computeLivePosition","readyState","targetSN","fragNext","foundFrag","fragmentWithinToleranceTest","candidateLookupTolerance","curSNIdx","sameLevel","nextFrag","loadCounter","fragLoadIdx","maxThreshold","fragLoadingLoopThreshold","loadIdx","autoLevel","autoLevelEnabled","getBufferedFrag","_bufferedFrags","followingBufferedFrag","fragPlayingCurrent","playbackRate","fragPlaying","fragPlayingLevel","immediateLevelSwitch","immediateSwitch","previouslyPaused","paused","pause","flushMainBuffer","POSITIVE_INFINITY","immediateLevelSwitchEnd","play","nextLevelSwitch","fetchdelay","nextBufferedFrag","nextLevelId","nextLevel","fragLastKbps","endOffset","flushScope","onMediaAttached","onvseeking","onMediaSeeking","onvseeked","onMediaSeeked","onvended","onMediaEnded","autoStartLoad","onMediaDetaching","ended","tolerance","fragStartOffset","fragEndOffset","stalled","onManifestParsed","aac","heaac","audioCodecSwitch","onLevelLoaded","newLevelId","curLevel","LevelHelper","onKeyLoaded","onFragLoaded","fragLoaded","currentLevel","tbuffered","defaultAudioCodec","lastAudioCodec","pendingBuffering","appended","mediaSeeking","initSegmentData","onFragParsingInitSegment","fragNew","trackName","ua","levelCodec","parent","content","onFragParsingData","onFragParsed","_checkAppendedParsed","onAudioTrackSwitching","onAudioTrackSwitched","videoBuffer","onBufferCreated","mediaTrack","alternate","onBufferAppended","pending","bufferedFrags","total","tfirst","mediaBuffered","delay","_reduceMaxBufferLength","levelRetry","minLength","startPositionBuffered","firstbufferedPosition","startNotBufferedButClose","expectedPlaying","jumpThreshold","playheadMoving","stallReported","nudgeRetry","tnow","stalledDuration","lowBufferWatchdogPeriod","nextBufferStart","nudgeOffset","hole","highBufferWatchdogPeriod","nudgeMaxRetry","targetTime","onFragLoadEmergencyAborted","onBufferFlushed","swapAudioCodec","targetLatency","liveSyncDuration","liveSyncDurationCount","nextState","previousState","_liveSyncPosition","_manualLevel","cleanTimer","clearTimeout","_levels","canload","levelRetryCount","loadError","onManifestLoaded","bitrateStart","levelSet","levelFromSet","videoCodecFound","audioCodecFound","chromeOrFirefox","fragmentError","urlId","_firstLevel","firstLevel","setLevelInternal","newLevel","_level","levelProperties","levelError","levelIndex","redundantLevels","nextAutoLevel","reloadInterval","trequest","_startLevel","configStartLevel","onFragParsingMetadata","addTextTrack","mode","Cue","WebKitDataCue","VTTCue","TextTrackCue","cue","addCue","EWMA","halfLife","alpha_","exp","estimate_","totalWeight_","weight","adjAlpha","getTotalWeight","getEstimate","zeroFactor","slow","fast","defaultEstimate","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","durationMs","numBytes","bandwidth","canEstimate","lastLoadedFragLevel","_nextAutoLevel","_bwEstimator","onCheck","_abandonRulesCheck","clearTimer","isLive","ewmaFast","ewmaSlow","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","v","minAutoLevel","aborted","requestDelay","loadRate","bw","realBitrate","expectedLen","fragLoadedDelay","bufferStarvationDelay","fragLevelNextLoadedDelay","levelNextBitrate","abrMaxWithRealBitrate","loadedBytes","loadedDuration","onFragBuffered","fragLoadingProcessingMs","bwEstimate","bitrateTestDelay","_findBestLevel","currentFragDuration","currentBw","maxAutoLevel","maxFetchDuration","bwFactor","bwUpFactor","avgDuration","adjustedbw","fetchDuration","forcedAutoLevel","bwEstimator","nextABRAutoLevel","_nextABRAutoLevel","avgbw","bestLevel","abrBandWidthFactor","abrBandWidthUpFactor","maxStarvationDelay","maxLoadingDelay","_msDuration","_levelDuration","onsbue","onSBUpdateEnd","onsbe","onSBUpdateError","pendingTracks","onLevelPtsUpdated","audioBuffer","sourceBuffer","timestampOffset","updating","audioTimestampOffset","audioExpected","videoExpected","sourceBufferNb","onMediaAttaching","ms","mediaSource","onmso","onMediaSourceOpen","onmse","onMediaSourceEnded","onmsc","onMediaSourceClose","src","createObjectURL","endOfStream","removeAttribute","flushRange","segments","checkPendingTracks","pendingTracksNb","createSourceBuffers","doAppending","_needsFlush","doFlush","_needsEos","checkEos","appending","counter","segment","updateMediaElementDuration","onBufferReset","sb","removeSourceBuffer","onBufferCodecs","mimeType","addSourceBuffer","onBufferAppending","onBufferAppendFail","onBufferEos","dataType","sbobj","onBufferFlushing","flushBufferCounter","onLevelUpdated","levelDuration","range","flushBuffer","appendBuffer","appendError","code","appendErrorMaxRetry","typeIn","bufStart","bufEnd","flushStart","flushEnd","remove","capLevelToPlayerSize","restrictedLevels","autoLevelCapping","onFpsDropLevelCapping","CapLevelController","isLevelAllowed","droppedLevel","HTMLVideoElement","getMaxLevel","detectPlayerSize","levelsLength","streamController","capLevelIndex","validLevels","getMaxLevelByMediaSize","mediaWidth","mediaHeight","atGreatestBandiwdth","maxLevelIndex","clientWidth","offsetWidth","contentScaleFactor","clientHeight","offsetHeight","devicePixelRatio","isVideoPlaybackQualityAvailable","capLevelOnFPSDrop","getVideoPlaybackQuality","checkFPSInterval","fpsDroppedMonitoringPeriod","checkFPS","decodedFrames","droppedFrames","lastTime","currentPeriod","currentDropped","lastDroppedFrames","currentDecoded","lastDecodedFrames","droppedFPS","totalDroppedFrames","fpsDroppedMonitoringThreshold","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","xhrSetup","requestTimeout","retryTimeout","callbacks","loadInternal","xhr","XMLHttpRequest","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","updateTrack","defaultFound","onAudioTrackLoaded","setAudioTrackInternal","newId","eventObj","audioTrackId","STARTING","PAUSED","WAITING_TRACK","WAITING_INIT_PTS","waitingFragment","videoTrackCC","onInitPtsFound","demuxerId","trackDetails","mainBufferInfo","audioSwitch","nextBuffered","isSeeking","waitingFrag","waitingFragCC","onAudioTracksUpdated","appendObj","pendingData","appendOnBufferFlush","autoKeyword","directionSetting","lr","rl","alignSetting","middle","left","right","findDirectionSetting","dir","findAlignSetting","align","extend","cobj","p","isIE8","baseObj","document","createElement","enumerable","hasBeenReset","_id","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","defineProperty","get","TypeError","setting","SyntaxError","displayState","getCueAsHTML","WebVTT","convertCueToDOMTree","StringDecoder","decode","decodeURIComponent","encodeURIComponent","VTTParser","decoder","regionList","parseTimeStamp","computeSeconds","m","s","f","Settings","values","create","k","dflt","defaultKey","has","alt","n","integer","percent","parseOptions","keyValueDelim","groupDelim","kv","defaults","center","parseCue","oInput","consumeTimeStamp","ts","consumeCueSettings","settings","region","vals","vals0","vertical","line","lineAlign","snapToLines","skipWhitespace","fixLineBreaks","collectNextLine","alreadyCollectedLine","hasSubstring","oncue","flush","onflush","newCue","captionScreen","row","indenting","indent","rows","isEmpty","chars","uchar","cueStartTime","trim","specialCea608CharsCodes","getCharForByte","byte","charCode","NR_ROWS","NR_COLS","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","verboseFilter","time","verboseLevel","setTime","newTime","severity","minLevel","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","reset","setStyles","styles","attribs","style","isDefault","equals","other","copy","newPenState","StyledUnicodeChar","penState","setChar","setPenState","newChar","Row","currPenState","equal","empty","setCursor","absPos","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","currChar","CaptionScreen","currRow","nrRollUpRows","setPen","setPAC","pacData","newRow","topRowIndex","lastOutputScreen","prevLineTime","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","getDisplayText","topRow","asOneRow","displayText","rowNr","rowText","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","currRollUpRow","writeScreen","lastCueEndTime","getHandler","setHandler","newHandler","setMode","newMode","insertChars","screen","outputDataUpdate","ccRCL","ccBS","ccAOF","ccAON","ccDER","ccRU","ccFON","ccRDC","ccTR","ccRTD","ccEDM","ccCR","ccENM","ccEOC","ccTO","nrCols","ccMIDROW","colorIndex","colors","dispatch","dispatchCue","cueSplitAtTime","Cea608Parser","field","out1","out2","outputs","channels","currChNr","lastCmdA","lastCmdB","bufferedData","dataCounters","addData","byteList","cmdFound","charsFound","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","channel","cond1","cond2","case1","case2","interpretPAC","pacIndex","channelNr","charCodes","charCode1","oneCode","hexCodes","OutputFilter","timelineController","addCues","createCaptionsTrack","startsWith","inputString","searchString","cueString2millis","timeString","secs","mins","hours","hash","calculateOffset","vttCCs","presentationTime","currCC","prevCC","new","presentationOffset","WebVTTParser","vttByteArray","syncPTS","callBack","errorCallBack","re","vttLines","cueTime","mpegTs","localTime","cues","parsingError","inHeader","parser","cueOffset","onparsingerror","clearCurrentCues","removeCue","reuseVttTextTrack","inUseTrack","manifestTrack","label","textTrack1","textTrack2","intersection","x1","y1","y2","enabled","Cues","cueHandler","textTracks","unparsedVttFrags","cueRanges","enableCEA708Captions","channel1","channel2","cea608Parser","ranges","merged","cueRange","overlap","getExistingTrack","propName","sendAddTrackEvent","createEvent","initEvent","dispatchEvent","trackVar","existingTrack","createTextTrack","captionsTextTrack1LanguageCode","kind","_cleanTracks","lastSn","enableWebVTT","inUseTracks","onLevelSwitching","closedCaptions","decryptData","_parseVTTs","success","currentTrack","getCueById","textTrackCue","onFragDecrypted","onFragParsingUserdata","ccdatas","extractCea608Data","tmpByte","ccbyte1","ccbyte2","ccValid","ccType","actualCCBytes","filterSubtitleTracks","textTrackList","subtitleDisplay","_onTextTracksChanged","subtitleTrack","queuedDefaultTrack","trackChangeListener","useTextTrackPolling","subtitlePollingInterval","subtitleTracks","onTick","onSubtitleTrackLoaded","setSubtitleTrackInternal","subtitleTrackId","vttFragSNsProcessed","vttFragQueues","currentlyProcessing","currentTrackId","clearVttFragQueues","onSubtitleFragProcessed","processedFragSNs","fragQueue","currentFragSN","alreadyProcessed","alreadyInQueue","some","fragInQueue","onSubtitleTracksUpdated","onSubtitleTrackSwitch","hlsDefaultConfig","fetchSetup","abrController","bufferController","capLevelController","fpsController","minAutoBitrate","subtitleStreamController","subtitleTrackController","captionsTextTrack1Label","captionsTextTrack2Label","captionsTextTrack2LanguageCode","audioStreamController","audioTrackController","isSupported","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","Hls","defaultConfig","DefaultConfig","prop","_autoLevelCapping","playListLoader","fragmentLoader","keyLoader","id3TrackController","levelController","networkControllers","Controller","coreComponents","detachMedia","component","attachMedia","loadSource","location","href","controller","recoverMediaError","loadLevel","manualLevel","DemuxerWorker","transferable"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;AAEA;AACA;;;;;;;;;;;;AC7DA,SAASA,IAAT,GAAgB,CAAE;;AAElB,IAAMC,aAAa;AACjBC,SAAOF,IADU;AAEjBG,SAAOH,IAFU;AAGjBI,OAAKJ,IAHY;AAIjBK,QAAML,IAJW;AAKjBM,QAAMN,IALW;AAMjBO,SAAOP;AANU,CAAnB;;AASA,IAAIQ,iBAAiBP,UAArB;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASQ,SAAT,CAAmBC,IAAnB,EAAyBC,GAAzB,EAA8B;AAC5BA,QAAM,MAAOD,IAAP,GAAc,MAAd,GAAuBC,GAA7B;AACA,SAAOA,GAAP;AACD;;AAED,SAASC,cAAT,CAAwBF,IAAxB,EAA8B;AAC5B,MAAMG,OAAOC,KAAKC,OAAL,CAAaL,IAAb,CAA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,EAAwBqC,EAAxB,EAA4BoF,QAA5B;AACD,KALD,MAMK;AACHjO,MAAA,wBAAAA,CAAOlB,KAAP,yBAAmCyP,IAAIG,OAAvC;AACA,WAAKlB,QAAL,CAAcmB,OAAd,CAAsBC,MAAM3L,KAA5B,EAAmC,EAAChE,MAAO,4BAAAqE,CAAWE,WAAnB,EAAgCqL,SAAU,8BAAAlL,CAAaa,kBAAvD,EAA2EsK,OAAQ,IAAnF,EAAyFC,QAASR,IAAIG,OAAtG,EAAnC;AACD;AACF,G;;sBAEDnB,O,sBAAU;AACR,QAAIW,YAAY,KAAKA,SAArB;AACA,QAAIA,SAAJ,EAAe;AACbA,gBAAUX,OAAV;AACA,WAAKW,SAAL,GAAiBlI,SAAjB;AACD;AACF,G;;;;;AAGH,yEAAe,mBAAf,E;;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,eAAe,SAAS;AACxB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,GAAG;AACH,oBAAoB,SAAS;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;;;;;;AC7SA;;AAEA;AACA,iB;AACA;;AAEA,6BAA6B,mBAAmB,eAAe;AAC/D,oCAAoC;AACpC;AACA;;AAEA,oBAAoB;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA,WAAW;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AACA/wB,WAAS+hB,EAAT,CAAY,wDAAA3gB,CAAMjM,iBAAlB,EAAqC,UAAS67B,EAAT,EAAaj5B,IAAb,EAAmB;AACtD,QAAI+0D,eAAe,EAAnB;AACA,QAAI5rD,UAAU,EAAC4gB,OAAOkP,EAAR,EAAYj5B,MAAKA,IAAjB,EAAd;AACA,QAAIA,KAAK+mB,KAAT,EAAgB;AACd5d,cAAQ4d,KAAR,GAAgB/mB,KAAK+mB,KAAL,CAAWxkB,MAA3B;AACAwyD,mBAAatzD,IAAb,CAAkBzB,KAAK+mB,KAAL,CAAWxkB,MAA7B;AACA,aAAOvC,KAAK+mB,KAAZ;AACD;AACD,QAAI/mB,KAAKgnB,KAAT,EAAgB;AACd7d,cAAQ6d,KAAR,GAAgBhnB,KAAKgnB,KAAL,CAAWzkB,MAA3B;AACAwyD,mBAAatzD,IAAb,CAAkBzB,KAAKgnB,KAAL,CAAWzkB,MAA7B;AACA,aAAOvC,KAAKgnB,KAAZ;AACD;AACDltB,SAAK+/B,WAAL,CAAiB1wB,OAAjB,EAAyB4rD,YAAzB;AACD,GAdD;AAeD,CA/DD;;AAiEA,+DAAeD,aAAf,E","file":"hls.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Hls\"] = factory();\n\telse\n\t\troot[\"Hls\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/dist/\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 8);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap cb2b7ace4e98a4df4dfc","function noop() {}\n\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nlet exportedLogger = fakeLogger;\n\n/*globals self: false */\n\n//let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction formatMsg(type, msg) {\n msg = '[' + type + '] > ' + msg;\n return msg;\n}\n\nfunction consolePrintFn(type) {\n const func = self.console[type];\n if (func) {\n return function(...args) {\n if(args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n func.apply(self.console, args);\n };\n }\n return noop;\n}\n\nfunction exportLoggerFunctions(debugConfig, ...functions) {\n functions.forEach(function(type) {\n exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);\n });\n}\n\nexport var enableLogs = function(debugConfig) {\n if (debugConfig === true || typeof debugConfig === 'object') {\n exportLoggerFunctions(debugConfig,\n // Remove out from list here to hard-disable a log-level\n //'trace',\n 'debug',\n 'log',\n 'info',\n 'warn',\n 'error'\n );\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n exportedLogger.log();\n } catch (e) {\n exportedLogger = fakeLogger;\n }\n }\n else {\n exportedLogger = fakeLogger;\n }\n};\n\nexport var logger = exportedLogger;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/logger.js","export default {\n // fired before MediaSource is attaching to media element - data: { media }\n MEDIA_ATTACHING: 'hlsMediaAttaching',\n // fired when MediaSource has been succesfully attached to media element - data: { }\n MEDIA_ATTACHED: 'hlsMediaAttached',\n // fired before detaching MediaSource from media element - data: { }\n MEDIA_DETACHING: 'hlsMediaDetaching',\n // fired when MediaSource has been detached from media element - data: { }\n MEDIA_DETACHED: 'hlsMediaDetached',\n // fired when we buffer is going to be reset - data: { }\n BUFFER_RESET: 'hlsBufferReset',\n // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n BUFFER_CODECS: 'hlsBufferCodecs',\n // fired when sourcebuffers have been created - data: { tracks : tracks }\n BUFFER_CREATED: 'hlsBufferCreated',\n // fired when we append a segment to the buffer - data: { segment: segment object }\n BUFFER_APPENDING: 'hlsBufferAppending',\n // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}\n BUFFER_APPENDED: 'hlsBufferAppended',\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }\n BUFFER_EOS: 'hlsBufferEos',\n // fired when the media buffer should be flushed - data { startOffset, endOffset }\n BUFFER_FLUSHING: 'hlsBufferFlushing',\n // fired when the media buffer has been flushed - data: { }\n BUFFER_FLUSHED: 'hlsBufferFlushed',\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n MANIFEST_LOADING: 'hlsManifestLoading',\n // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}\n MANIFEST_LOADED: 'hlsManifestLoaded',\n // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}\n MANIFEST_PARSED: 'hlsManifestParsed',\n // fired when a level switch is requested - data: { level : id of new level } // deprecated in favor LEVEL_SWITCHING\n LEVEL_SWITCH: 'hlsLevelSwitch',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCHING: 'hlsLevelSwitching',\n // fired when a level switch is effective - data: { level : id of new level }\n LEVEL_SWITCHED: 'hlsLevelSwitched',\n // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}\n LEVEL_LOADING: 'hlsLevelLoading',\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }\n LEVEL_LOADED: 'hlsLevelLoaded',\n // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }\n LEVEL_UPDATED: 'hlsLevelUpdated',\n // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }\n LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',\n // fired when an audio track switch occurs - data: { id : audio track id } // deprecated in favor AUDIO_TRACK_SWITCHING\n AUDIO_TRACK_SWITCH: 'hlsAudioTrackSwitch',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }\n AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }\n SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }\n INIT_PTS_FOUND: 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING: 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }\n FRAG_LOADED: 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED: 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }\n FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n FRAG_PARSING_DATA: 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED: 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }\n FRAG_BUFFERED: 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED: 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP: 'hlsFpsDrop',\n //triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }\n FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n ERROR: 'hlsError',\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n DESTROYING: 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING: 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }\n KEY_LOADED: 'hlsKeyLoaded',\n // fired upon stream controller state transitions - data: { previousState, nextState }\n STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/events.js","export const ErrorTypes = {\n // Identifier for a network error (loading error / timeout ...)\n NETWORK_ERROR: 'networkError',\n // Identifier for a media Error (video/parsing/mediasource error)\n MEDIA_ERROR: 'mediaError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\nexport const ErrorDetails = {\n // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_ERROR: 'manifestLoadError',\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n MANIFEST_PARSING_ERROR: 'manifestParsingError',\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_ERROR: 'levelLoadError',\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n LEVEL_SWITCH_ERROR: 'levelSwitchError',\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n FRAG_LOAD_ERROR: 'fragLoadError',\n // Identifier for fragment loop loading error - data: { frag : fragment object}\n FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',\n // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }\n FRAG_DECRYPT_ERROR: 'fragDecryptError',\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n FRAG_PARSING_ERROR: 'fragParsingError',\n // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }\n REMUX_ALLOC_ERROR : 'remuxAllocError',\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n KEY_LOAD_ERROR: 'keyLoadError',\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }\n BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',\n // Identifier for a buffer append error - data: append error description\n BUFFER_APPEND_ERROR: 'bufferAppendError',\n // Identifier for a buffer appending error event - data: appending error description\n BUFFER_APPENDING_ERROR: 'bufferAppendingError',\n // Identifier for a buffer stalled error event\n BUFFER_STALLED_ERROR: 'bufferStalledError',\n // Identifier for a buffer full event\n BUFFER_FULL_ERROR: 'bufferFullError',\n // Identifier for a buffer seek over hole event\n BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n BUFFER_NUDGE_ON_STALL : 'bufferNudgeOnStall',\n // Identifier for an internal exception happening inside hls.js while handling an event\n INTERNAL_EXCEPTION: 'internalException'\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/errors.js","/**\n * ID3 parser\n */\n class ID3 {\n /**\n * Returns true if an ID3 header can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 header is found\n */\n static isHeader(data, offset) {\n /*\n * http://id3.org/id3v2.3.0\n * [0] = 'I'\n * [1] = 'D'\n * [2] = '3'\n * [3,4] = {Version}\n * [5] = {Flags}\n * [6-9] = {ID3 Size}\n *\n * An ID3v2 tag can be detected with the following pattern:\n * $49 44 33 yy yy xx zz zz zz zz\n * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n */\n if (offset + 10 <= data.length) {\n //look for 'ID3' identifier\n if (data[offset] === 0x49 && data[offset+1] === 0x44 && data[offset+2] === 0x33) {\n //check version is within range\n if (data[offset+3] < 0xFF && data[offset+4] < 0xFF) {\n //check size is within range\n if (data[offset+6] < 0x80 && data[offset+7] < 0x80 && data[offset+8] < 0x80 && data[offset+9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns true if an ID3 footer can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 footer is found\n */\n static isFooter(data, offset) {\n /*\n * The footer is a copy of the header, but with a different identifier\n */\n if (offset + 10 <= data.length) {\n //look for '3DI' identifier\n if (data[offset] === 0x33 && data[offset+1] === 0x44 && data[offset+2] === 0x49) {\n //check version is within range\n if (data[offset+3] < 0xFF && data[offset+4] < 0xFF) {\n //check size is within range\n if (data[offset+6] < 0x80 && data[offset+7] < 0x80 && data[offset+8] < 0x80 && data[offset+9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {Uint8Array} - The block of data containing any ID3 tags found\n */\n static getID3Data(data, offset) {\n const front = offset;\n let length = 0;\n\n while (ID3.isHeader(data, offset)) {\n //ID3 header is 10 bytes\n length += 10;\n\n const size = ID3._readSize(data, offset + 6);\n length += size;\n\n if (ID3.isFooter(data, offset + 10)) {\n //ID3 footer is 10 bytes\n length += 10;\n }\n\n offset += length;\n }\n\n if (length > 0) {\n return data.subarray(front, front + length);\n }\n\n return undefined;\n }\n\n static _readSize(data, offset) {\n let size = 0;\n size = ((data[offset] & 0x7f) << 21);\n size |= ((data[offset+1] & 0x7f) << 14);\n size |= ((data[offset+2] & 0x7f) << 7);\n size |= (data[offset+3] & 0x7f);\n return size;\n }\n\n /**\n * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n * @param {Uint8Array} data - Block of data containing one or more ID3 tags\n * @return {number} - The timestamp\n */\n static getTimeStamp(data) {\n const frames = ID3.getID3Frames(data);\n for(let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n if (ID3.isTimeStampFrame(frame)) {\n return ID3._readTimeStamp(frame);\n }\n }\n\n return undefined;\n }\n\n /**\n * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n * @param {ID3 frame} frame\n */\n static isTimeStampFrame(frame) {\n return (frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp');\n }\n\n static _getFrameData(data) {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n const type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n const size = ID3._readSize(data, 4);\n\n //skip frame id, size, and flags\n let offset = 10;\n\n return { type, size, data: data.subarray(offset, offset + size) };\n }\n\n /**\n * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags\n * @return {ID3 frame[]} - Array of ID3 frame objects\n */\n static getID3Frames(id3Data) {\n let offset = 0;\n const frames = [];\n\n while (ID3.isHeader(id3Data, offset)) {\n const size = ID3._readSize(id3Data, offset + 6);\n //skip past ID3 header\n offset += 10;\n const end = offset + size;\n //loop through frames in the ID3 tag\n while (offset + 8 < end) {\n const frameData = ID3._getFrameData(id3Data.subarray(offset));\n const frame = ID3._decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\n //skip frame header and frame data\n offset += frameData.size + 10;\n }\n\n if (ID3.isFooter(id3Data, offset)) {\n offset += 10;\n }\n }\n\n return frames;\n }\n\n static _decodeFrame(frame) {\n if (frame.type === 'PRIV') {\n return ID3._decodePrivFrame(frame);\n } else if (frame.type[0] === 'T') {\n return ID3._decodeTextFrame(frame);\n } else if (frame.type[0] === 'W') {\n return ID3._decodeURLFrame(frame);\n }\n\n return undefined;\n }\n\n static _readTimeStamp(timeStampFrame) {\n if (timeStampFrame.data.byteLength === 8) {\n const data = new Uint8Array(timeStampFrame.data);\n // timestamp is 33 bit expressed as a big-endian eight-octet number,\n // with the upper 31 bits set to zero.\n const pts33Bit = data[3] & 0x1;\n let timestamp = (data[4] << 23) +\n (data[5] << 15) +\n (data[6] << 7) +\n data[7];\n timestamp /= 45;\n\n if (pts33Bit) {\n timestamp += 47721858.84; // 2^32 / 90\n }\n\n return Math.round(timestamp);\n }\n\n return undefined;\n }\n\n static _decodePrivFrame(frame) {\n /*\n Format: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n const owner = ID3._utf8ArrayToStr(frame.data);\n const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n }\n\n static _decodeTextFrame(frame) {\n if (frame.size < 2) {\n return undefined;\n }\n\n if (frame.type === 'TXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{Value}\n */\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Value}\n */\n const text = ID3._utf8ArrayToStr(frame.data.subarray(1));\n return { key: frame.type, data: text };\n }\n }\n\n static _decodeURLFrame(frame) {\n if (frame.type === 'WXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{URL}\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0-?] = {URL}\n */\n const url = ID3._utf8ArrayToStr(frame.data);\n return { key: frame.type, data: url };\n }\n }\n\n // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n /* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\n static _utf8ArrayToStr(array) {\n\n const len = array.length;\n let c;\n let char2;\n let char3;\n let out = '';\n let i = 0;\n while (i < len) {\n c = array[i++];\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\n if (c === 0x00 || c === 0x03) {\n continue;\n }\n switch (c >> 4) {\n case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:\n // 0xxxxxxx\n out += String.fromCharCode(c);\n break;\n case 12: case 13:\n // 110x xxxx 10xx xxxx\n char2 = array[i++];\n out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));\n break;\n case 14:\n // 1110 xxxx 10xx xxxx 10xx xxxx\n char2 = array[i++];\n char3 = array[i++];\n out += String.fromCharCode(((c & 0x0F) << 12) |\n ((char2 & 0x3F) << 6) |\n ((char3 & 0x3F) << 0));\n break;\n default:\n }\n }\n return out;\n }\n}\n\nconst utf8ArrayToStr = ID3._utf8ArrayToStr;\n\nexport default ID3;\n\nexport { utf8ArrayToStr };\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/id3.js","export default class AESCrypto {\n constructor(subtle,iv) {\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n decrypt(data, key) {\n return this.subtle.decrypt({name: 'AES-CBC', iv: this.aesIV}, key, data);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/crypt/aes-crypto.js","class FastAESKey {\n constructor(subtle,key) {\n this.subtle = subtle;\n this.key = key;\n }\n\n expandKey() {\n return this.subtle.importKey('raw', this.key, {name: 'AES-CBC'}, false, ['encrypt', 'decrypt']);\n }\n}\n\nexport default FastAESKey;\n\n\n\n// WEBPACK FOOTER //\n// ./src/crypt/fast-aes-key.js","class AESDecryptor {\n constructor() {\n // Static after running initTable\n this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\n this.subMix = [new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)];\n this.invSubMix = [new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)];\n this.sBox = new Uint32Array(256);\n this.invSBox = new Uint32Array(256);\n\n // Changes during runtime\n this.key = new Uint32Array(0);\n\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_(arrayBuffer) {\n let view = new DataView(arrayBuffer);\n let newArray = new Uint32Array(4);\n for (let i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n return newArray;\n }\n\n initTable() {\n let sBox = this.sBox;\n let invSBox = this.invSBox;\n let subMix = this.subMix;\n let subMix0 = subMix[0];\n let subMix1 = subMix[1];\n let subMix2 = subMix[2];\n let subMix3 = subMix[3];\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n }\n\n for (i = 0; i < 256; i++) {\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n let x2 = d[x];\n let x4 = d[x2];\n let x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n subMix0[x] = (t << 24) | (t >>> 8);\n subMix1[x] = (t << 16) | (t >>> 16);\n subMix2[x] = (t << 8) | (t >>> 24);\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n invSubMix0[sx] = (t << 24) | (t >>> 8);\n invSubMix1[sx] = (t << 16) | (t >>> 16);\n invSubMix2[sx] = (t << 8) | (t >>> 24);\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n\n expandKey(keyBuffer) {\n // convert keyBuffer to Uint32Array\n let key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n\n while (offset < key.length && sameKey) {\n sameKey = (key[offset] === this.key[offset]);\n offset++;\n }\n\n if (sameKey) {\n return;\n }\n\n this.key = key;\n let keySize = this.keySize = key.length;\n\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n\n let ksRows = this.ksRows = (keySize + 6 + 1) * 4;\n let ksRow;\n let invKsRow;\n\n let keySchedule = this.keySchedule = new Uint32Array(ksRows);\n let invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);\n let sbox = this.sBox;\n let rcon = this.rcon;\n\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let prev;\n let t;\n\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n\n if (ksRow % keySize === 0) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n }\n\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[(t >>> 16) & 0xff]] ^ invSubMix2[sbox[(t >>> 8) & 0xff]] ^ invSubMix3[sbox[t & 0xff]];\n }\n\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap(word) {\n return (word << 24) | ((word & 0xff00) << 8) | ((word & 0xff0000) >> 8) | (word >>> 24);\n }\n\n decrypt(inputArrayBuffer, offset, aesIV) {\n let nRounds = this.keySize + 6;\n let invKeySchedule = this.invKeySchedule;\n let invSBOX = this.invSBox;\n\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n\n let inputInt32 = new Int32Array(inputArrayBuffer);\n let outputInt32 = new Int32Array(inputInt32.length);\n\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n\n var ksRow, i;\n let swapWord = this.networkToHostOrderSwap;\n\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(inputInt32[offset + 3]);\n\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[(s1 >> 16) & 0xff] ^ invSubMix2[(s2 >> 8) & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];\n t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[(s2 >> 16) & 0xff] ^ invSubMix2[(s3 >> 8) & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];\n t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[(s3 >> 16) & 0xff] ^ invSubMix2[(s0 >> 8) & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];\n t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[(s0 >> 16) & 0xff] ^ invSubMix2[(s1 >> 8) & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 = ((invSBOX[s0 >>> 24] << 24) ^ (invSBOX[(s1 >> 16) & 0xff] << 16) ^ (invSBOX[(s2 >> 8) & 0xff] << 8) ^ invSBOX[s3 & 0xff]) ^ invKeySchedule[ksRow];\n t1 = ((invSBOX[s1 >>> 24] << 24) ^ (invSBOX[(s2 >> 16) & 0xff] << 16) ^ (invSBOX[(s3 >> 8) & 0xff] << 8) ^ invSBOX[s0 & 0xff]) ^ invKeySchedule[ksRow + 1];\n t2 = ((invSBOX[s2 >>> 24] << 24) ^ (invSBOX[(s3 >> 16) & 0xff] << 16) ^ (invSBOX[(s0 >> 8) & 0xff] << 8) ^ invSBOX[s1 & 0xff]) ^ invKeySchedule[ksRow + 2];\n t3 = ((invSBOX[s3 >>> 24] << 24) ^ (invSBOX[(s0 >> 16) & 0xff] << 16) ^ (invSBOX[(s1 >> 8) & 0xff] << 8) ^ invSBOX[s2 & 0xff]) ^ invKeySchedule[ksRow + 3];\n ksRow = ksRow + 3;\n\n // Write\n outputInt32[offset] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n\n offset = offset + 4;\n }\n\n return outputInt32.buffer;\n }\n\n destroy() {\n this.key = undefined;\n this.keySize = undefined;\n this.ksRows = undefined;\n\n this.sBox = undefined;\n this.invSBox = undefined;\n this.subMix = undefined;\n this.invSubMix = undefined;\n this.keySchedule = undefined;\n this.invKeySchedule = undefined;\n\n this.rcon = undefined;\n }\n}\n\nexport default AESDecryptor;\n\n\n\n// WEBPACK FOOTER //\n// ./src/crypt/aes-decryptor.js","import AESCrypto from './aes-crypto';\nimport FastAESKey from './fast-aes-key';\nimport AESDecryptor from './aes-decryptor';\n\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\n\n/*globals self: false */\n\nclass Decrypter {\n constructor(observer,config) {\n this.observer = observer;\n this.config = config;\n this.logEnabled = true;\n try {\n const browserCrypto = crypto ? crypto : self.crypto;\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n } catch (e) {}\n this.disableWebCrypto = !this.subtle;\n }\n\n isSync() {\n return (this.disableWebCrypto && this.config.enableSoftwareAES);\n }\n\n decrypt(data, key, iv, callback) {\n if (this.disableWebCrypto && this.config.enableSoftwareAES) {\n if (this.logEnabled) {\n logger.log('JS AES decrypt');\n this.logEnabled = false;\n }\n let decryptor = this.decryptor;\n if (!decryptor) {\n this.decryptor = decryptor = new AESDecryptor();\n }\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv));\n }\n else {\n if (this.logEnabled) {\n logger.log('WebCrypto AES decrypt');\n this.logEnabled = false;\n }\n const subtle = this.subtle;\n if (this.key !== key) {\n this.key = key;\n this.fastAesKey = new FastAESKey(subtle,key);\n }\n\n this.fastAesKey.expandKey().\n then((aesKey) => {\n // decrypt using web crypto\n let crypto = new AESCrypto(subtle,iv);\n crypto.decrypt(data, aesKey).\n catch ((err) => {\n this.onWebCryptoError(err, data, key, iv, callback);\n }).\n then((result) => {\n callback(result);\n });\n }).\n catch ((err) => {\n this.onWebCryptoError(err, data, key, iv, callback);\n });\n }\n }\n\n onWebCryptoError(err, data, key, iv, callback) {\n if (this.config.enableSoftwareAES) {\n logger.log('WebCrypto Error, disable WebCrypto API');\n this.disableWebCrypto = true;\n this.logEnabled = true;\n this.decrypt(data, key, iv, callback);\n }\n else {\n logger.error(`decrypting error : ${err.message}`);\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MEDIA_ERROR, details : ErrorDetails.FRAG_DECRYPT_ERROR, fatal : true, reason : err.message});\n }\n }\n\n destroy() {\n let decryptor = this.decryptor;\n if (decryptor) {\n decryptor.destroy();\n this.decryptor = undefined;\n }\n }\n}\n\nexport default Decrypter;\n\n\n\n// WEBPACK FOOTER //\n// ./src/crypt/decrypter.js","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/events/events.js\n// module id = 5\n// module chunks = 0","// see https://tools.ietf.org/html/rfc1808\r\n\r\n/* jshint ignore:start */\r\n(function(root) { \r\n/* jshint ignore:end */\r\n\r\n var URL_REGEX = /^((?:[^\\/;?#]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\r\n var FIRST_SEGMENT_REGEX = /^([^\\/;?#]*)(.*)$/;\r\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\r\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/).*?(?=\\/)/g;\r\n\r\n var URLToolkit = { // jshint ignore:line\r\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\r\n // E.g\r\n // With opts.alwaysNormalize = false (default, spec compliant)\r\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\r\n // With opts.alwaysNormalize = true (default, not spec compliant)\r\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\r\n buildAbsoluteURL: function(baseURL, relativeURL, opts) {\r\n opts = opts || {};\r\n // remove any remaining space and CRLF\r\n baseURL = baseURL.trim();\r\n relativeURL = relativeURL.trim();\r\n if (!relativeURL) {\r\n // 2a) If the embedded URL is entirely empty, it inherits the\r\n // entire base URL (i.e., is set equal to the base URL)\r\n // and we are done.\r\n if (!opts.alwaysNormalize) {\r\n return baseURL;\r\n }\r\n var basePartsForNormalise = this.parseURL(baseURL);\r\n if (!baseParts) {\r\n throw new Error('Error trying to parse base URL.');\r\n }\r\n basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);\r\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\r\n }\r\n var relativeParts = this.parseURL(relativeURL);\r\n if (!relativeParts) {\r\n throw new Error('Error trying to parse relative URL.');\r\n }\r\n if (relativeParts.scheme) {\r\n // 2b) If the embedded URL starts with a scheme name, it is\r\n // interpreted as an absolute URL and we are done.\r\n if (!opts.alwaysNormalize) {\r\n return relativeURL;\r\n }\r\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\r\n return URLToolkit.buildURLFromParts(relativeParts);\r\n }\r\n var baseParts = this.parseURL(baseURL);\r\n if (!baseParts) {\r\n throw new Error('Error trying to parse base URL.');\r\n }\r\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\r\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\r\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\r\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\r\n baseParts.netLoc = pathParts[1];\r\n baseParts.path = pathParts[2];\r\n }\r\n if (baseParts.netLoc && !baseParts.path) {\r\n baseParts.path = '/';\r\n }\r\n var builtParts = {\r\n // 2c) Otherwise, the embedded URL inherits the scheme of\r\n // the base URL.\r\n scheme: baseParts.scheme,\r\n netLoc: relativeParts.netLoc,\r\n path: null,\r\n params: relativeParts.params,\r\n query: relativeParts.query,\r\n fragment: relativeParts.fragment\r\n };\r\n if (!relativeParts.netLoc) {\r\n // 3) If the embedded URL's <net_loc> is non-empty, we skip to\r\n // Step 7. Otherwise, the embedded URL inherits the <net_loc>\r\n // (if any) of the base URL.\r\n builtParts.netLoc = baseParts.netLoc;\r\n // 4) If the embedded URL path is preceded by a slash \"/\", the\r\n // path is not relative and we skip to Step 7.\r\n if (relativeParts.path[0] !== '/') {\r\n if (!relativeParts.path) {\r\n // 5) If the embedded URL path is empty (and not preceded by a\r\n // slash), then the embedded URL inherits the base URL path\r\n builtParts.path = baseParts.path;\r\n // 5a) if the embedded URL's <params> is non-empty, we skip to\r\n // step 7; otherwise, it inherits the <params> of the base\r\n // URL (if any) and\r\n if (!relativeParts.params) {\r\n builtParts.params = baseParts.params;\r\n // 5b) if the embedded URL's <query> is non-empty, we skip to\r\n // step 7; otherwise, it inherits the <query> of the base\r\n // URL (if any) and we skip to step 7.\r\n if (!relativeParts.query) {\r\n builtParts.query = baseParts.query;\r\n }\r\n }\r\n } else {\r\n // 6) The last segment of the base URL's path (anything\r\n // following the rightmost slash \"/\", or the entire path if no\r\n // slash is present) is removed and the embedded URL's path is\r\n // appended in its place.\r\n var baseURLPath = baseParts.path;\r\n var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;\r\n builtParts.path = URLToolkit.normalizePath(newPath);\r\n }\r\n }\r\n }\r\n if (builtParts.path === null) {\r\n builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;\r\n }\r\n return URLToolkit.buildURLFromParts(builtParts);\r\n },\r\n parseURL: function(url) {\r\n var parts = URL_REGEX.exec(url);\r\n if (!parts) {\r\n return null;\r\n }\r\n return {\r\n scheme: parts[1] || '',\r\n netLoc: parts[2] || '',\r\n path: parts[3] || '',\r\n params: parts[4] || '',\r\n query: parts[5] || '',\r\n fragment: parts[6] || ''\r\n };\r\n },\r\n normalizePath: function(path) {\r\n // The following operations are\r\n // then applied, in order, to the new path:\r\n // 6a) All occurrences of \"./\", where \".\" is a complete path\r\n // segment, are removed.\r\n // 6b) If the path ends with \".\" as a complete path segment,\r\n // that \".\" is removed.\r\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\r\n // 6c) All occurrences of \"<segment>/../\", where <segment> is a\r\n // complete path segment not equal to \"..\", are removed.\r\n // Removal of these path segments is performed iteratively,\r\n // removing the leftmost matching pattern on each iteration,\r\n // until no matching pattern remains.\r\n // 6d) If the path ends with \"<segment>/..\", where <segment> is a\r\n // complete path segment not equal to \"..\", that\r\n // \"<segment>/..\" is removed.\r\n while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line\r\n return path.split('').reverse().join('');\r\n },\r\n buildURLFromParts: function(parts) {\r\n return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;\r\n }\r\n };\r\n\r\n/* jshint ignore:start */\r\n if(typeof exports === 'object' && typeof module === 'object')\r\n module.exports = URLToolkit;\r\n else if(typeof define === 'function' && define.amd)\r\n define([], function() { return URLToolkit; });\r\n else if(typeof exports === 'object')\r\n exports[\"URLToolkit\"] = URLToolkit;\r\n else\r\n root[\"URLToolkit\"] = URLToolkit;\r\n})(this);\r\n/* jshint ignore:end */\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/url-toolkit/src/url-toolkit.js\n// module id = 6\n// module chunks = 0","/**\n * ADTS parser helper\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nexport function getAudioConfig(observer, data, offset, audioCodec) {\n var adtsObjectType, // :int\n adtsSampleingIndex, // :int\n adtsExtensionSampleingIndex, // :int\n adtsChanelConfig, // :int\n config,\n userAgent = navigator.userAgent.toLowerCase(),\n manifestCodec = audioCodec,\n adtsSampleingRates = [\n 96000, 88200,\n 64000, 48000,\n 44100, 32000,\n 24000, 22050,\n 16000, 12000,\n 11025, 8000,\n 7350];\n // byte 2\n adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;\n adtsSampleingIndex = ((data[offset + 2] & 0x3C) >>> 2);\n if (adtsSampleingIndex > adtsSampleingRates.length - 1) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: `invalid ADTS sampling index:${adtsSampleingIndex}` });\n return;\n }\n adtsChanelConfig = ((data[offset + 2] & 0x01) << 2);\n // byte 3\n adtsChanelConfig |= ((data[offset + 3] & 0xC0) >>> 6);\n logger.log(`manifest codec:${audioCodec},ADTS data:type:${adtsObjectType},sampleingIndex:${adtsSampleingIndex}[${adtsSampleingRates[adtsSampleingIndex]}Hz],channelConfig:${adtsChanelConfig}`);\n // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox/i.test(userAgent)) {\n if (adtsSampleingIndex >= 6) {\n adtsObjectType = 5;\n config = new Array(4);\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSampleingIndex = adtsSampleingIndex - 3;\n } else {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n }\n // Android : always use AAC\n } else if (userAgent.indexOf('android') !== -1) {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n } else {\n /* for other browsers (Chrome/Vivaldi/Opera ...)\n always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n */\n adtsObjectType = 5;\n config = new Array(4);\n // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n if ((audioCodec && ((audioCodec.indexOf('mp4a.40.29') !== -1) ||\n (audioCodec.indexOf('mp4a.40.5') !== -1))) ||\n (!audioCodec && adtsSampleingIndex >= 6)) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSampleingIndex = adtsSampleingIndex - 3;\n } else {\n // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.\n if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && ((adtsSampleingIndex >= 6 && adtsChanelConfig === 1) ||\n /vivaldi/i.test(userAgent)) ||\n (!audioCodec && adtsChanelConfig === 1)) {\n adtsObjectType = 2;\n config = new Array(2);\n }\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n }\n }\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n config[0] = adtsObjectType << 3;\n // samplingFrequencyIndex\n config[0] |= (adtsSampleingIndex & 0x0E) >> 1;\n config[1] |= (adtsSampleingIndex & 0x01) << 7;\n // channelConfiguration\n config[1] |= adtsChanelConfig << 3;\n if (adtsObjectType === 5) {\n // adtsExtensionSampleingIndex\n config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;\n config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;\n // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n config[2] |= 2 << 2;\n config[3] = 0;\n }\n return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: ('mp4a.40.' + adtsObjectType), manifestCodec: manifestCodec };\n}\n\nexport function isHeaderPattern(data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nexport function getHeaderLength(data, offset) {\n return (!!(data[offset + 1] & 0x01) ? 7 : 9);\n}\n\nexport function getFullFrameLength(data, offset) {\n return ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xE0) >>> 5);\n}\n\nexport function isHeader(data, offset) {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n return true;\n }\n return false;\n}\n\nexport function probe(data, offset) {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n // ADTS header Length\n let headerLength = getHeaderLength(data, offset);\n // ADTS frame Length\n let frameLength = headerLength;\n if (offset + 5 < data.length) {\n frameLength = getFullFrameLength(data, offset);\n }\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n}\n\nexport function initTrackConfig(track, observer, data, offset, audioCodec) {\n if (!track.samplerate) {\n var config = getAudioConfig(observer, data, offset, audioCodec);\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(`parsed codec:${track.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n }\n}\n\nexport function getFrameDuration(samplerate) {\n return 1024 * 90000 / samplerate;\n}\n\nexport function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {\n var headerLength, frameLength, stamp;\n var length = data.length;\n\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n headerLength = getHeaderLength(data, offset);\n // retrieve frame size\n frameLength = getFullFrameLength(data, offset);\n frameLength -= headerLength;\n\n if ((frameLength > 0) && ((offset + headerLength + frameLength) <= length)) {\n stamp = pts + frameIndex * frameDuration;\n //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n return { headerLength, frameLength, stamp };\n }\n\n return undefined;\n}\n\nexport function appendFrame(track, data, offset, pts, frameIndex) {\n var frameDuration = getFrameDuration(track.samplerate);\n var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n var stamp = header.stamp;\n var headerLength = header.headerLength;\n var frameLength = header.frameLength;\n\n //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n var aacSample = {\n unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),\n pts: stamp,\n dts: stamp\n };\n\n track.samples.push(aacSample);\n track.len += frameLength;\n\n return {sample: aacSample, length: frameLength + headerLength};\n }\n\n return undefined;\n}\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/adts.js","/**\n * AAC demuxer\n */\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport ID3 from '../demux/id3';\n\nclass AACDemuxer {\n\n constructor(observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment(initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp() {\n }\n\n static probe(data) {\n if (!data) {\n return false;\n }\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\n\n for (let length = data.length; offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append(data, timeOffset, contiguous, accurateTimeOffset) {\n let track = this._audioTrack;\n let id3Data = ID3.getID3Data(data, 0) || [];\n let timestamp = ID3.getTimeStamp(id3Data);\n let pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n let frameIndex = 0;\n let stamp = pts;\n let length = data.length;\n let offset = id3Data.length;\n\n let id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];\n\n while (offset < length - 1) {\n if (ADTS.isHeader(data, offset) && (offset + 5) < length) {\n ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);\n var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n logger.log('Unable to parse AAC frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n //nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy() {\n }\n\n}\n\nexport default AACDemuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/aacdemuxer.js","/**\n * MP4 demuxer\n */\nimport {logger} from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\n class MP4Demuxer {\n\n constructor(observer, remuxer) {\n this.observer = observer;\n this.remuxer = remuxer;\n }\n\n resetTimeStamp(initPTS) {\n this.initPTS = initPTS;\n }\n\n resetInitSegment(initSegment,audioCodec,videoCodec, duration) {\n //jshint unused:false\n if (initSegment && initSegment.byteLength) {\n const initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);\n\n // default audio codec if nothing specified\n // TODO : extract that from initsegment\n if (audioCodec == null) {\n audioCodec = 'mp4a.40.5';\n }\n if (videoCodec == null) {\n videoCodec = 'avc1.42e01e';\n\n }\n var tracks = {};\n if(initData.audio && initData.video) {\n tracks.audiovideo = { container : 'video/mp4', codec : audioCodec + ',' + videoCodec, initSegment : duration ? initSegment : null };\n } else {\n if (initData.audio) {\n tracks.audio = { container : 'audio/mp4', codec : audioCodec, initSegment : duration ? initSegment : null };\n }\n if (initData.video) {\n tracks.video = { container : 'video/mp4', codec : videoCodec, initSegment : duration ? initSegment : null };\n }\n }\n this.observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT,{ tracks : tracks });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\n if (videoCodec) {\n this.videoCodec = videoCodec;\n }\n }\n }\n\n static probe(data) {\n // ensure we find a moof box in the first 16 kB\n return MP4Demuxer.findBox( { data : data, start : 0, end : Math.min(data.length, 16384) } ,['moof']).length > 0;\n }\n\n\n static bin2str(buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint32(buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 24 |\n buffer[offset + 1] << 16 |\n buffer[offset + 2] << 8 |\n buffer[offset + 3];\n return val < 0 ? 4294967296 + val : val;\n }\n\n static writeUint32(buffer, offset, value) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n buffer[offset] = value >> 24;\n buffer[offset+1] = (value >> 16) & 0xff;\n buffer[offset+2] = (value >> 8) & 0xff;\n buffer[offset+3] = value & 0xff;\n }\n\n\n // Find the data for a box specified by its path\n static findBox(data,path) {\n var results = [],\n i, size, type, end, subresults, start, endbox;\n\n if (data.data) {\n start = data.start;\n end = data.end;\n data = data.data;\n } else {\n start = 0;\n end = data.byteLength;\n }\n\n if (!path.length) {\n // short-circuit the search for empty paths\n return null;\n }\n\n for (i = start; i < end;) {\n size = MP4Demuxer.readUint32(data, i);\n type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));\n endbox = size > 1 ? i + size : end;\n\n if (type === path[0]) {\n\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push({ data : data, start : i + 8, end : endbox});\n } else {\n // recursively search for the next box along the path\n subresults = MP4Demuxer.findBox({ data : data, start : i +8, end : endbox }, path.slice(1));\n if (subresults.length) {\n results = results.concat(subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n }\n\n\n\n/**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param init {Uint8Array} the bytes of the init segment\n * @return {object} a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n static parseInitSegment(initSegment) {\n var result = [];\n var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);\n\n traks.forEach(trak => {\n const tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd.data[tkhd.start];\n let index = version === 0 ? 12 : 20;\n let trackId = MP4Demuxer.readUint32(tkhd, index);\n\n const mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd.data[mdhd.start];\n index = version === 0 ? 12 : 20;\n const timescale = MP4Demuxer.readUint32(mdhd, index);\n\n const hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start+8, hdlr.start+12));\n let type = { 'soun' : 'audio', 'vide' : 'video'}[hdlrType];\n if (type) {\n // extract codec info. TODO : parse codec details to be able to build MIME type\n let codecBox = MP4Demuxer.findBox( trak, ['mdia','minf','stbl','stsd']);\n if (codecBox.length) {\n codecBox = codecBox[0];\n let codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start+12, codecBox.start+16));\n logger.log(`MP4Demuxer:${type}:${codecType} found`);\n }\n result[trackId] = { timescale : timescale , type : type};\n result[type] = { timescale : timescale , id : trackId};\n }\n }\n }\n }\n });\n return result;\n }\n\n\n/**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param timescale {object} a hash of track ids to timescale values.\n * @return {number} the earliest base media decode start time for the\n * fragment, in seconds\n */\nstatic getStartDTS(initData, fragment) {\n var trafs, baseTimes, result;\n\n // we need info from two childrend of each track fragment box\n trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);\n\n // determine the start times for each track\n baseTimes = [].concat.apply([], trafs.map(function(traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function(tfhd) {\n var id, scale, baseTime;\n\n // get the track id from the tfhd\n id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n scale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function(tfdt) {\n var version, result;\n\n version = tfdt.data[tfdt.start];\n result = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n\n result += MP4Demuxer.readUint32(tfdt, 8);\n }\n return result;\n })[0];\n // convert base time to seconds\n return baseTime / scale;\n });\n }));\n\n // return the minimum\n result = Math.min.apply(null, baseTimes);\n return isFinite(result) ? result : 0;\n}\n\n\n\n\nstatic offsetStartDTS(initData,fragment,timeOffset) {\n MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function(traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function(tfhd) {\n // get the track id from the tfhd\n var id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n var timescale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n MP4Demuxer.findBox(traf, ['tfdt']).map(function(tfdt) {\n var version = tfdt.data[tfdt.start];\n var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 0) {\n MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset*timescale);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);\n baseMediaDecodeTime -= timeOffset*timescale;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime,0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n MP4Demuxer.writeUint32(tfdt, 4, upper);\n MP4Demuxer.writeUint32(tfdt, 8, lower);\n }\n });\n });\n });\n}\n\n // feed incoming data to the front of the parsing pipeline\n append(data, timeOffset,contiguous,accurateTimeOffset) {\n let initData = this.initData;\n if(!initData) {\n this.resetInitSegment(data,this.audioCodec,this.videoCodec);\n initData = this.initData;\n }\n let startDTS, initPTS = this.initPTS;\n if (initPTS === undefined) {\n let startDTS = MP4Demuxer.getStartDTS(initData,data);\n this.initPTS = initPTS = startDTS - timeOffset;\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS});\n }\n MP4Demuxer.offsetStartDTS(initData,data,initPTS);\n startDTS = MP4Demuxer.getStartDTS(initData,data);\n this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous,accurateTimeOffset,data);\n }\n\n destroy() {\n }\n\n}\n\nexport default MP4Demuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/mp4demuxer.js","/**\n * MPEG parser helper\n */\n\nconst MpegAudio = {\n\n BitratesMap: [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,\n 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,\n 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,\n 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,\n 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],\n\n SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],\n\n appendFrame: function (track, data, offset, pts, frameIndex) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return undefined;\n }\n\n var header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n var frameDuration = 1152 * 90000 / header.sampleRate;\n var stamp = pts + frameIndex * frameDuration;\n var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n track.len += header.frameLength;\n\n return { sample, length: header.frameLength };\n }\n\n return undefined;\n },\n\n parseHeader: function (data, offset) {\n var headerB = (data[offset + 1] >> 3) & 3;\n var headerC = (data[offset + 1] >> 1) & 3;\n var headerE = (data[offset + 2] >> 4) & 15;\n var headerF = (data[offset + 2] >> 2) & 3;\n var headerG = !!(data[offset + 2] & 2);\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n var columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n var padding = headerG ? 1 : 0;\n var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n var frameLength = headerC === 3 ?\n ((headerB === 3 ? 12 : 6) * bitRate / sampleRate + padding) << 2 :\n ((headerB === 3 ? 144 : 72) * bitRate / sampleRate + padding) | 0;\n\n return { sampleRate, channelCount, frameLength };\n }\n\n return undefined;\n },\n\n isHeaderPattern: function (data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n },\n\n isHeader: function (data, offset) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n return true;\n }\n return false;\n },\n\n probe: function (data, offset) {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n // MPEG header Length\n let headerLength = 4;\n // MPEG frame Length\n let header = this.parseHeader(data, offset);\n let frameLength = headerLength;\n if (header && header.frameLength) {\n frameLength = header.frameLength;\n }\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n }\n};\n\nexport default MpegAudio;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/mpegaudio.js","/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n*/\n\nimport {logger} from '../utils/logger';\n\nclass ExpGolomb {\n\n constructor(data) {\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord() {\n var\n data = this.data,\n bytesAvailable = this.bytesAvailable,\n position = data.byteLength - bytesAvailable,\n workingBytes = new Uint8Array(4),\n availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits(count) {\n var skipBytes; // :int\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= (skipBytes >> 3);\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits(size) {\n var\n bits = Math.min(this.bitsAvailable, size), // :uint\n valu = this.word >>> (32 - bits); // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return valu << bits | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ() {\n var leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if (0 !== (this.word & (0x80000000 >>> leadingZeroCount))) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG() {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG() {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG() {\n var clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG() {\n var valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean() {\n return 1 === this.readBits(1);\n }\n\n // ():int\n readUByte() {\n return this.readBits(8);\n }\n\n // ():int\n readUShort() {\n return this.readBits(16);\n }\n // ():int\n readUInt() {\n return this.readBits(32);\n }\n\n /**\n * Advance the ExpGolomb decoder past a scaling list. The scaling\n * list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count {number} the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList(count) {\n var\n lastScale = 8,\n nextScale = 8,\n j,\n deltaScale;\n for (j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = this.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = (nextScale === 0) ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @param data {Uint8Array} the bytes of a sequence parameter set\n * @return {object} an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS() {\n var\n frameCropLeftOffset = 0,\n frameCropRightOffset = 0,\n frameCropTopOffset = 0,\n frameCropBottomOffset = 0,\n profileIdc,profileCompat,levelIdc,\n numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,\n picHeightInMapUnitsMinus1,\n frameMbsOnlyFlag,\n scalingListCount,\n i,\n readUByte = this.readUByte.bind(this),\n readBits = this.readBits.bind(this),\n readUEG = this.readUEG.bind(this),\n readBoolean = this.readBoolean.bind(this),\n skipBits = this.skipBits.bind(this),\n skipEG = this.skipEG.bind(this),\n skipUEG = this.skipUEG.bind(this),\n skipScalingList = this.skipScalingList.bind(this);\n\n readUByte();\n profileIdc = readUByte(); // profile_idc\n profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n levelIdc = readUByte(); //level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (profileIdc === 100 ||\n profileIdc === 110 ||\n profileIdc === 122 ||\n profileIdc === 244 ||\n profileIdc === 44 ||\n profileIdc === 83 ||\n profileIdc === 86 ||\n profileIdc === 118 ||\n profileIdc === 128) {\n var chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1); // separate_colour_plane_flag\n }\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) { // seq_scaling_matrix_present_flag\n scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) { // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16);\n } else {\n skipScalingList(64);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n var picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); //log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for(i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG(); // offset_for_ref_frame[ i ]\n }\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n picWidthInMbsMinus1 = readUEG();\n picHeightInMapUnitsMinus1 = readUEG();\n frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1); // mb_adaptive_frame_field_flag\n }\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) { // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n let pixelRatio = [1,1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1: pixelRatio = [1,1]; break;\n case 2: pixelRatio = [12,11]; break;\n case 3: pixelRatio = [10,11]; break;\n case 4: pixelRatio = [16,11]; break;\n case 5: pixelRatio = [40,33]; break;\n case 6: pixelRatio = [24,11]; break;\n case 7: pixelRatio = [20,11]; break;\n case 8: pixelRatio = [32,11]; break;\n case 9: pixelRatio = [80,33]; break;\n case 10: pixelRatio = [18,11]; break;\n case 11: pixelRatio = [15,11]; break;\n case 12: pixelRatio = [64,33]; break;\n case 13: pixelRatio = [160,99]; break;\n case 14: pixelRatio = [4,3]; break;\n case 15: pixelRatio = [3,2]; break;\n case 16: pixelRatio = [2,1]; break;\n case 255: {\n pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2)),\n height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - ((frameMbsOnlyFlag? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)),\n pixelRatio : pixelRatio\n };\n }\n\n readSliceType() {\n // skip NALu type\n this.readUByte();\n // discard first_mb_in_slice\n this.readUEG();\n // return slice_type\n return this.readUEG();\n }\n}\n\nexport default ExpGolomb;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/exp-golomb.js","/**\n * SAMPLE-AES decrypter\n*/\n\n import Decrypter from '../crypt/decrypter';\n\n class SampleAesDecrypter {\n\n constructor(observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config);\n }\n\n decryptBuffer(encryptedData, callback) {\n this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n decryptAacSample(samples, sampleIndex, callback, sync) {\n let curUnit = samples[sampleIndex].unit;\n let encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);\n let encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length);\n\n let localthis = this;\n this.decryptBuffer(encryptedBuffer, function (decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n curUnit.set(decryptedData, 16);\n\n if (!sync) {\n localthis.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples(samples, sampleIndex, callback) {\n for (;; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAacSample(samples, sampleIndex, callback, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData(decodedData) {\n let encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n let encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (let inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {\n encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n return encryptedData;\n }\n\n getAvcDecryptedUnit(decodedData, decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (let outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {\n decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n return decodedData;\n }\n\n decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {\n let decodedData = this.discardEPB(curUnit.data);\n let encryptedData = this.getAvcEncryptedData(decodedData);\n let localthis = this;\n\n this.decryptBuffer(encryptedData.buffer, function (decryptedData) {\n curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);\n\n if (!sync) {\n localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n });\n }\n\n decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {\n for (;; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n let curUnits = samples[sampleIndex].units;\n for (;; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n let curUnit = curUnits[unitIndex];\n if (curUnit.length <= 48 || (curUnit.type !== 1 && curUnit.type !== 5)) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n }\n }\n\n export default SampleAesDecrypter;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/sample-aes.js","/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n*/\n\n import * as ADTS from './adts';\n import MpegAudio from './mpegaudio';\n import Event from '../events';\n import ExpGolomb from './exp-golomb';\n import SampleAesDecrypter from './sample-aes';\n// import Hex from '../utils/hex';\n import {logger} from '../utils/logger';\n import {ErrorTypes, ErrorDetails} from '../errors';\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nconst RemuxerTrackIdConfig = {\n video: 0,\n audio: 1,\n id3: 2,\n text: 3\n};\n\nclass TSDemuxer {\n\n constructor(observer, remuxer, config, typeSupported) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.remuxer = remuxer;\n this.sampleAes = null;\n }\n\n setDecryptData(decryptdata) {\n if ((decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'SAMPLE-AES')) {\n this.sampleAes = new SampleAesDecrypter(this.observer, this.config, decryptdata, this.discardEPB);\n } else {\n this.sampleAes = null;\n }\n }\n\n static probe(data) {\n const syncOffset = TSDemuxer._syncOffset(data);\n if (syncOffset < 0) {\n return false;\n } else {\n if (syncOffset) {\n logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}, junk ahead ?`);\n }\n return true;\n }\n }\n\n static _syncOffset(data) {\n // scan 1000 first bytes\n const scanwindow = Math.min(1000,data.length - 3*188);\n let i = 0;\n while(i < scanwindow) {\n // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47\n if (data[i] === 0x47 && data[i+188] === 0x47 && data[i+2*188] === 0x47) {\n return i;\n } else {\n i++;\n }\n }\n return -1;\n }\n\n /**\n * Creates a track model internal to demuxer used to drive remuxing input\n *\n * @param {string} type 'audio' | 'video' | 'id3' | 'text'\n * @param {number} duration\n * @return {object} TSDemuxer's internal track model\n */\n static createTrack(type, duration) {\n return {\n container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined, \n type, \n id: RemuxerTrackIdConfig[type],\n pid : -1,\n inputTimeScale : 90000,\n sequenceNumber: 0,\n samples : [],\n len : 0,\n dropped : type === 'video' ? 0 : undefined,\n isAAC: type === 'audio' ? true : undefined,\n duration: type === 'audio' ? duration : undefined\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start) \n * Resets all internal track instances of the demuxer.\n *\n * @override Implements generic demuxing/remuxing interface (see DemuxerInline)\n * @param {object} initSegment\n * @param {string} audioCodec\n * @param {string} videoCodec\n * @param {number} duration (in TS timescale = 90kHz)\n */\n resetInitSegment(initSegment, audioCodec, videoCodec, duration) {\n this.pmtParsed = false;\n this._pmtId = -1;\n\n this._avcTrack = TSDemuxer.createTrack('video', duration);\n this._audioTrack = TSDemuxer.createTrack('audio', duration);\n this._id3Track = TSDemuxer.createTrack('id3', duration);\n this._txtTrack = TSDemuxer.createTrack('text', duration);\n\n // flush any partial content\n this.aacOverFlow = null;\n this.aacLastPTS = null;\n this.avcSample = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = duration;\n }\n\n /**\n * \n * @override\n */\n resetTimeStamp() {}\n\n // feed incoming data to the front of the parsing pipeline\n append(data, timeOffset, contiguous,accurateTimeOffset) {\n var start, len = data.length, stt, pid, atf, offset,pes,\n unknownPIDs = false;\n this.contiguous = contiguous;\n var pmtParsed = this.pmtParsed,\n avcTrack = this._avcTrack,\n audioTrack = this._audioTrack,\n id3Track = this._id3Track,\n avcId = avcTrack.pid,\n audioId = audioTrack.pid,\n id3Id = id3Track.pid,\n pmtId = this._pmtId,\n avcData = avcTrack.pesData,\n audioData = audioTrack.pesData,\n id3Data = id3Track.pesData,\n parsePAT = this._parsePAT,\n parsePMT = this._parsePMT,\n parsePES = this._parsePES,\n parseAVCPES = this._parseAVCPES.bind(this),\n parseAACPES = this._parseAACPES.bind(this),\n parseMPEGPES = this._parseMPEGPES.bind(this),\n parseID3PES = this._parseID3PES.bind(this);\n\n const syncOffset = TSDemuxer._syncOffset(data);\n\n // don't parse last TS packet if incomplete\n len -= (len + syncOffset) % 188;\n\n // loop through TS packets\n for (start = syncOffset; start < len; start += 188) {\n if (data[start] === 0x47) {\n stt = !!(data[start + 1] & 0x40);\n // pid is a 13-bit field starting at the last bit of TS[1]\n pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];\n atf = (data[start + 3] & 0x30) >> 4;\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === (start + 188)) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch(pid) {\n case avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData))) {\n parseAVCPES(pes,false);\n }\n avcData = {data: [], size: 0};\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData))) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n }\n audioData = {data: [], size: 0};\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + 188));\n audioData.size += start + 188 - offset;\n }\n break;\n case id3Id:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data))) {\n parseID3PES(pes);\n }\n id3Data = {data: [], size: 0};\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + 188));\n id3Data.size += start + 188 - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\n let parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n avcId = parsedPIDs.avc;\n if (avcId > 0) {\n avcTrack.pid = avcId;\n }\n audioId = parsedPIDs.audio;\n if (audioId > 0) {\n audioTrack.pid = audioId;\n audioTrack.isAAC = parsedPIDs.isAAC;\n }\n id3Id = parsedPIDs.id3;\n if (id3Id > 0) {\n id3Track.pid = id3Id;\n }\n if (unknownPIDs && !pmtParsed) {\n logger.log('reparse from beginning');\n unknownPIDs = false;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = syncOffset-188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n case 17:\n case 0x1fff:\n break;\n default:\n unknownPIDs = true;\n break;\n }\n } else {\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47'});\n }\n }\n // try to parse last PES packets\n if (avcData && (pes = parsePES(avcData))) {\n parseAVCPES(pes,true);\n avcTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n avcTrack.pesData = avcData;\n }\n\n if (audioData && (pes = parsePES(audioData))) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n audioTrack.pesData = null;\n } else {\n if (audioData && audioData.size) {\n logger.log('last AAC PES packet truncated,might overlap between fragments');\n }\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data))) {\n parseID3PES(pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n\n if (this.sampleAes == null) {\n this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n } else {\n this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (audioTrack.samples && audioTrack.isAAC) {\n let localthis = this;\n this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function() {\n localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (videoTrack.samples) {\n let localthis = this;\n this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {\n localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n destroy() {\n this._initPTS = this._initDTS = undefined;\n this._duration = 0;\n }\n\n _parsePAT(data, offset) {\n // skip the PSI header and parse the first PMT entry\n return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];\n //logger.log('PMT PID:' + this._pmtId);\n }\n\n _parsePMT(data, offset, mpegSupported, isSampleAes) {\n var sectionLength, tableEnd, programInfoLength, pid, result = { audio : -1, avc : -1, id3 : -1, isAAC : true};\n sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];\n tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];\n switch(data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n /* falls through */\n\n // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n case 0x0f:\n //logger.log('AAC PID:' + pid);\n if (result.audio === -1) {\n result.audio = pid;\n }\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n //logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n /* falls through */\n\n // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n case 0x1b:\n //logger.log('AVC PID:' + pid);\n if (result.avc === -1) {\n result.avc = pid;\n }\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n //logger.log('MPEG PID:' + pid);\n if (!mpegSupported) {\n logger.log('MPEG audio found, not supported in this browser for now');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.isAAC = false;\n }\n break;\n\n case 0x24:\n logger.warn('HEVC stream type found, not supported for now');\n break;\n\n default:\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;\n }\n return result;\n }\n\n _parsePES(stream) {\n var i = 0, frag, pesFlags, pesPrefix, pesLen, pesHdrLen, pesData, pesPts, pesDts, payloadStartOffset, data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while(data[0].length < 19 && data.length > 1) {\n let newData = new Uint8Array(data[0].length + data[1].length);\n newData.set(data[0]);\n newData.set(data[1], data[0].length);\n data[0] = newData;\n data.splice(1,1);\n }\n //retrieve PTS/DTS from first fragment\n frag = data[0];\n pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n pesFlags = frag[7];\n if (pesFlags & 0xC0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts = (frag[9] & 0x0E) * 536870912 +// 1 << 29\n (frag[10] & 0xFF) * 4194304 +// 1 << 22\n (frag[11] & 0xFE) * 16384 +// 1 << 14\n (frag[12] & 0xFF) * 128 +// 1 << 7\n (frag[13] & 0xFE) / 2;\n // check if greater than 2^32 -1\n if (pesPts > 4294967295) {\n // decrement 2^33\n pesPts -= 8589934592;\n }\n if (pesFlags & 0x40) {\n pesDts = (frag[14] & 0x0E ) * 536870912 +// 1 << 29\n (frag[15] & 0xFF ) * 4194304 +// 1 << 22\n (frag[16] & 0xFE ) * 16384 +// 1 << 14\n (frag[17] & 0xFF ) * 128 +// 1 << 7\n (frag[18] & 0xFE ) / 2;\n // check if greater than 2^32 -1\n if (pesDts > 4294967295) {\n // decrement 2^33\n pesDts -= 8589934592;\n }\n if (pesPts - pesDts > 60*90000) {\n logger.warn(`${Math.round((pesPts - pesDts)/90000)}s delta between PTS and DTS, align them`);\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n payloadStartOffset = pesHdrLen + 9;\n\n stream.size -= payloadStartOffset;\n //reassemble PES packet\n pesData = new Uint8Array(stream.size);\n for( let j = 0, dataLen = data.length; j < dataLen ; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset-=len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len-=payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i+=len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen+3;\n }\n return {data: pesData, pts: pesPts, dts: pesDts, len: pesLen};\n } else {\n return null;\n }\n }\n\n pushAccesUnit(avcSample,avcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n const samples = avcTrack.samples;\n const nbSamples = samples.length;\n // only push AVC sample if starting with a keyframe is not mandatory OR\n // if keyframe already found in this fragment OR\n // keyframe found in last fragment (track.sps) AND\n // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous\n if (!this.config.forceKeyFrameOnDiscontinuity ||\n avcSample.key === true ||\n (avcTrack.sps && (nbSamples || this.contiguous))) {\n avcSample.id = nbSamples;\n samples.push(avcSample);\n } else {\n // dropped samples, track it\n avcTrack.dropped++;\n }\n }\n if(avcSample.debug.length) {\n logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n }\n\n _parseAVCPES(pes,last) {\n //logger.log('parse new PES');\n var track = this._avcTrack,\n units = this._parseAVCNALu(pes.data),\n debug = false,\n expGolombDecoder,\n avcSample = this.avcSample,\n push,\n spsfound = false,\n i,\n pushAccesUnit = this.pushAccesUnit.bind(this),\n createAVCSample = function(key,pts,dts,debug) {\n return { key : key, pts : pts, dts : dts, units : [], debug : debug};\n };\n //free pes.data to save up some memory\n pes.data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (avcSample && units.length && !track.audFound) {\n pushAccesUnit(avcSample,track);\n avcSample = this.avcSample = createAVCSample(false,pes.pts,pes.dts,'');\n }\n\n units.forEach(unit => {\n switch(unit.type) {\n //NDR\n case 1:\n push = true;\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(true,pes.pts,pes.dts,'');\n }\n if(debug) {\n avcSample.debug += 'NDR ';\n }\n avcSample.frame = true;\n let data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n let sliceType = new ExpGolomb(data).readSliceType();\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n //if (sliceType === 2 || sliceType === 7) {\n if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {\n avcSample.key = true;\n }\n }\n break;\n //IDR\n case 5:\n push = true;\n // handle PES not starting with AUD\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(true,pes.pts,pes.dts,'');\n }\n if(debug) {\n avcSample.debug += 'IDR ';\n }\n avcSample.key = true;\n avcSample.frame = true;\n break;\n //SEI\n case 6:\n push = true;\n if(debug && avcSample) {\n avcSample.debug += 'SEI ';\n }\n expGolombDecoder = new ExpGolomb(this.discardEPB(unit.data));\n\n // skip frameType\n expGolombDecoder.readUByte();\n\n var payloadType = 0;\n var payloadSize = 0;\n var endOfCaptions = false;\n var b = 0;\n\n while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {\n payloadType = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadType += b;\n } while (b === 0xFF);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadSize += b;\n } while (b === 0xFF);\n\n // TODO: there can be more than one payload in an SEI packet...\n // TODO: need to read type and size in a while loop to get them all\n if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {\n\n endOfCaptions = true;\n\n var countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n var providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n var userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n var userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n var firstByte = expGolombDecoder.readUByte();\n var secondByte = expGolombDecoder.readUByte();\n\n var totalCCs = 31 & firstByte;\n var byteArray = [firstByte, secondByte];\n\n for (i = 0; i < totalCCs; i++) {\n // 3 bytes per CC\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n }\n\n this._insertSampleInOrder(this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });\n }\n }\n }\n }\n }\n else if (payloadSize < expGolombDecoder.bytesAvailable)\n {\n for (i = 0; i<payloadSize; i++)\n {\n expGolombDecoder.readUByte();\n }\n }\n }\n break;\n //SPS\n case 7:\n push = true;\n spsfound = true;\n if(debug && avcSample) {\n avcSample.debug += 'SPS ';\n }\n if(!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n var config = expGolombDecoder.readSPS();\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [unit.data];\n track.duration = this._duration;\n var codecarray = unit.data.subarray(1, 4);\n var codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n var h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n codecstring += h;\n }\n track.codec = codecstring;\n }\n break;\n //PPS\n case 8:\n push = true;\n if(debug && avcSample) {\n avcSample.debug += 'PPS ';\n }\n if (!track.pps) {\n track.pps = [unit.data];\n }\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample,track);\n }\n avcSample = this.avcSample = createAVCSample(false,pes.pts,pes.dts,debug ? 'AUD ': '');\n break;\n // Filler Data\n case 12:\n push = false;\n break;\n default:\n push = false;\n if (avcSample) {\n avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n break;\n }\n if(avcSample && push) {\n let units = avcSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n pushAccesUnit(avcSample,track);\n this.avcSample = null;\n }\n }\n\n _insertSampleInOrder(arr, data) {\n var len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len-1].pts)\n {\n arr.push(data);\n }\n else {\n for (var pos = len - 1; pos >= 0; pos--) {\n if (data.pts < arr[pos].pts) {\n arr.splice(pos, 0, data);\n break;\n }\n }\n }\n }\n else {\n arr.push(data);\n }\n }\n\n _getLastNalUnit() {\n let avcSample = this.avcSample, lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n let track = this._avcTrack, samples = track.samples;\n avcSample = samples[samples.length-1];\n }\n if (avcSample) {\n let units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n _parseAVCNALu(array) {\n var i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n var units = [], unit, unitType, lastUnitStart = -1, lastUnitType;\n //logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if(!value) {\n state = 3;\n } else if (value === 1) {\n if (lastUnitStart >=0) {\n unit = {data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType};\n //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n if(lastState && (i <= 4 - lastState)) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(0,lastUnit.data.byteLength - lastState);\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n overflow = i - state - 1;\n if (overflow > 0) {\n //logger.log('first NALU found with overflow:' + overflow);\n let tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n tmp.set(lastUnit.data, 0);\n tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n //logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >=0 && state >=0) {\n unit = {data: array.subarray(lastUnitStart, len), type: lastUnitType, state : state};\n units.push(unit);\n //logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n let tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n tmp.set(lastUnit.data, 0);\n tmp.set(array, lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n track.naluState = state;\n return units;\n }\n\n /**\n * remove Emulation Prevention bytes from a RBSP\n */\n discardEPB(data) {\n var length = data.byteLength,\n EPBPositions = [],\n i = 1,\n newLength, newData;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 &&\n data[i + 1] === 0 &&\n data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n newLength = length - EPBPositions.length;\n newData = new Uint8Array(newLength);\n var sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n }\n\n _parseAACPES(pes) {\n var track = this._audioTrack,\n data = pes.data,\n pts = pes.pts,\n startOffset = 0,\n aacOverFlow = this.aacOverFlow,\n aacLastPTS = this.aacLastPTS,\n frameDuration, frameIndex, offset, stamp, len;\n if (aacOverFlow) {\n var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);\n tmp.set(aacOverFlow, 0);\n tmp.set(data, aacOverFlow.byteLength);\n //logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);\n data = tmp;\n }\n // look for ADTS header (0xFFFx)\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset) {\n var reason, fatal;\n if (offset < len - 1) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n fatal = false;\n } else {\n reason = 'no ADTS header found in AAC PES';\n fatal = true;\n }\n logger.warn(`parsing error:${reason}`);\n this.observer.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason});\n if (fatal) {\n return;\n }\n }\n\n ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);\n frameIndex = 0;\n frameDuration = ADTS.getFrameDuration(track.samplerate);\n\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n if(aacOverFlow && aacLastPTS) {\n var newPTS = aacLastPTS+frameDuration;\n if(Math.abs(newPTS-pts) > 1) {\n logger.log(`AAC: align PTS for overlapping frames by ${Math.round((newPTS-pts)/90)}`);\n pts=newPTS;\n }\n }\n\n //scan for aac samples\n while (offset < len) {\n if (ADTS.isHeader(data, offset) && (offset + 5) < len) {\n var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n //logger.log(`${Math.round(frame.sample.pts)} : AAC`);\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n //logger.log('Unable to parse AAC frame');\n break;\n }\n } else {\n //nothing found, keep looking\n offset++;\n }\n }\n\n if (offset < len) {\n aacOverFlow = data.subarray(offset, len);\n //logger.log(`AAC: overflow detected:${len-offset}`);\n } else {\n aacOverFlow = null;\n }\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES(pes) {\n var data = pes.data;\n var length = data.length;\n var frameIndex = 0;\n var offset = 0;\n var pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n var frame = MpegAudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n //logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n //nothing found, keep looking\n offset++;\n }\n }\n }\n\n _parseID3PES(pes) {\n this._id3Track.samples.push(pes);\n }\n}\n\nexport default TSDemuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/tsdemuxer.js","/**\n * MP3 demuxer\n */\nimport ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport MpegAudio from './mpegaudio';\n\nclass MP3Demuxer {\n\n constructor(observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment(initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp() {\n }\n\n static probe(data) {\n // check if data contains ID3 timestamp and MPEG sync word\n var offset, length;\n let id3Data = ID3.getID3Data(data, 0);\n if (id3Data && ID3.getTimeStamp(id3Data) !== undefined) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append(data, timeOffset, contiguous, accurateTimeOffset) {\n let id3Data = ID3.getID3Data(data, 0);\n let pts = 90 * ID3.getTimeStamp(id3Data);\n var offset = id3Data.length;\n var length = data.length;\n var frameIndex = 0, stamp = 0;\n var track = this._audioTrack;\n\n let id3Samples = [{ pts: pts, dts: pts, data: id3Data }];\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n var frame = MpegAudio.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n //logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n //nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy() {\n }\n}\n\nexport default MP3Demuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/mp3demuxer.js","/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame(codec,channelCount) {\n switch(codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);\n } else if (channelCount === 3) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);\n } else if (channelCount === 4) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);\n } else if (channelCount === 5) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);\n } else if (channelCount === 6) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);\n }\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1,0x40,0x22,0x80,0xa3,0x4e,0xe6,0x80,0xba,0x8,0x0,0x0,0x0,0x1c,0x6,0xf1,0xc1,0xa,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5e]);\n } else if (channelCount === 2) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1,0x40,0x22,0x80,0xa3,0x5e,0xe6,0x80,0xba,0x8,0x0,0x0,0x0,0x0,0x95,0x0,0x6,0xf1,0xa1,0xa,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5e]);\n } else if (channelCount === 3) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1,0x40,0x22,0x80,0xa3,0x5e,0xe6,0x80,0xba,0x8,0x0,0x0,0x0,0x0,0x95,0x0,0x6,0xf1,0xa1,0xa,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5e]);\n }\n break;\n }\n return null;\n }\n}\n\nexport default AAC;\n\n\n\n// WEBPACK FOOTER //\n// ./src/helper/aac.js","/**\n * Generate MP4 Box\n*/\n\n//import Hex from '../utils/hex';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4 {\n static init() {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: []\n };\n\n var i;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3)\n ];\n }\n }\n\n var videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x56, 0x69, 0x64, 0x65,\n 0x6f, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n ]);\n\n var audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x53, 0x6f, 0x75, 0x6e,\n 0x64, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n 'video': videoHdlr,\n 'audio': audioHdlr\n };\n\n var dref = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01, // entry_count\n 0x00, 0x00, 0x00, 0x0c, // entry_size\n 0x75, 0x72, 0x6c, 0x20, // 'url' type\n 0x00, // version 0\n 0x00, 0x00, 0x01 // entry_flags\n ]);\n\n var stco = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00 // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // sample_size\n 0x00, 0x00, 0x00, 0x00, // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x01, // flags\n 0x00, 0x00, // graphicsmode\n 0x00, 0x00,\n 0x00, 0x00,\n 0x00, 0x00 // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, // balance\n 0x00, 0x00 // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01]);// entry_count\n\n var majorBrand = new Uint8Array([105,115,111,109]); // isom\n var avc1Brand = new Uint8Array([97,118,99,49]); // avc1\n var minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box(type) {\n var\n payload = Array.prototype.slice.call(arguments, 1),\n size = 8,\n i = payload.length,\n len = i,\n result;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.mdhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x55, 0xc4, // 'und' language (undetermined)\n 0x00, 0x00\n ]));\n }\n\n static mdia(track) {\n return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));\n }\n\n static mfhd(sequenceNumber) {\n return MP4.box(MP4.types.mfhd, new Uint8Array([\n 0x00,\n 0x00, 0x00, 0x00, // flags\n (sequenceNumber >> 24),\n (sequenceNumber >> 16) & 0xFF,\n (sequenceNumber >> 8) & 0xFF,\n sequenceNumber & 0xFF, // sequence_number\n ]));\n }\n\n static minf(track) {\n if (track.type === 'audio') {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));\n } else {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));\n }\n }\n\n static moof(sn, baseMediaDecodeTime, track) {\n return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track,baseMediaDecodeTime));\n }\n/**\n * @param tracks... (optional) {array} the tracks associated with this movie\n */\n static moov(tracks) {\n var\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));\n }\n\n static mvex(tracks) {\n var\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));\n }\n\n static mvhd(timescale,duration) {\n duration*=timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n var\n bytes = new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x00, 0x01, 0x00, 0x00, // 1.0 rate\n 0x01, 0x00, // 1.0 volume\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0xff, 0xff, 0xff, 0xff // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp(track) {\n var\n samples = track.samples || [],\n bytes = new Uint8Array(4 + samples.length),\n flags,\n i;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] = (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n (flags.hasRedundancy);\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl(track) {\n return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));\n }\n\n static avc1(track) {\n var sps = [], pps = [], i, data, len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xFF);\n sps.push((len & 0xFF));\n sps = sps.concat(Array.prototype.slice.call(data)); // SPS\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xFF);\n pps.push((len & 0xFF));\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n var avcc = MP4.box(MP4.types.avcC, new Uint8Array([\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets\n ].concat(sps).concat([\n track.pps.length // numOfPictureParameterSets\n ]).concat(pps))), // \"PPS\"\n width = track.width,\n height = track.height,\n hSpacing = track.pixelRatio[0],\n vSpacing = track.pixelRatio[1];\n //console.log('avcc:' + Hex.hexDump(avcc));\n return MP4.box(MP4.types.avc1, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, // pre_defined\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n (width >> 8) & 0xFF,\n width & 0xff, // width\n (height >> 8) & 0xFF,\n height & 0xff, // height\n 0x00, 0x48, 0x00, 0x00, // horizresolution\n 0x00, 0x48, 0x00, 0x00, // vertresolution\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // frame_count\n 0x12,\n 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js\n 0x79, 0x6D, 0x6F, 0x74,\n 0x69, 0x6F, 0x6E, 0x2F,\n 0x68, 0x6C, 0x73, 0x2E,\n 0x6A, 0x73, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, // compressorname\n 0x00, 0x18, // depth = 24\n 0x11, 0x11]), // pre_defined = -1\n avcc,\n MP4.box(MP4.types.btrt, new Uint8Array([\n 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB\n 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate\n 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate\n MP4.box(MP4.types.pasp, new Uint8Array([\n (hSpacing >> 24), // hSpacing\n (hSpacing >> 16) & 0xFF,\n (hSpacing >> 8) & 0xFF,\n hSpacing & 0xFF,\n (vSpacing >> 24), // vSpacing\n (vSpacing >> 16) & 0xFF,\n (vSpacing >> 8) & 0xFF,\n vSpacing & 0xFF]))\n );\n }\n\n static esds(track) {\n var configlen = track.config.length;\n return new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17+configlen, // length\n 0x00, 0x01, //es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f+configlen, // length\n 0x40, //codec : mpeg4_audio\n 0x15, // stream_type\n 0x00, 0x00, 0x00, // buffer_size\n 0x00, 0x00, 0x00, 0x00, // maxBitrate\n 0x00, 0x00, 0x00, 0x00, // avgBitrate\n\n 0x05 // descriptor_type\n ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static mp4a(track) {\n var samplerate = track.samplerate;\n return MP4.box(MP4.types.mp4a, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]),\n MP4.box(MP4.types.esds, MP4.esds(track)));\n }\n\n static mp3(track) {\n var samplerate = track.samplerate;\n return MP4.box(MP4.types['.mp3'], new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]));\n }\n\n static stsd(track) {\n if (track.type === 'audio') {\n if (!track.isAAC && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd(track) {\n var id = track.id,\n duration = track.duration*track.timescale,\n width = track.width,\n height = track.height,\n upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),\n lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.tkhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x07, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (id >> 24) & 0xFF,\n (id >> 16) & 0xFF,\n (id >> 8) & 0xFF,\n id & 0xFF, // track_ID\n 0x00, 0x00, 0x00, 0x00, // reserved\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, // layer\n 0x00, 0x00, // alternate_group\n 0x00, 0x00, // non-audio track volume\n 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n (width >> 8) & 0xFF,\n width & 0xFF,\n 0x00, 0x00, // width\n (height >> 8) & 0xFF,\n height & 0xFF,\n 0x00, 0x00 // height\n ]));\n }\n\n static traf(track,baseMediaDecodeTime) {\n var sampleDependencyTable = MP4.sdtp(track),\n id = track.id,\n upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),\n lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n return MP4.box(MP4.types.traf,\n MP4.box(MP4.types.tfhd, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF) // track_ID\n ])),\n MP4.box(MP4.types.tfdt, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n (upperWordBaseMediaDecodeTime >>24),\n (upperWordBaseMediaDecodeTime >> 16) & 0XFF,\n (upperWordBaseMediaDecodeTime >> 8) & 0XFF,\n (upperWordBaseMediaDecodeTime & 0xFF),\n (lowerWordBaseMediaDecodeTime >>24),\n (lowerWordBaseMediaDecodeTime >> 16) & 0XFF,\n (lowerWordBaseMediaDecodeTime >> 8) & 0XFF,\n (lowerWordBaseMediaDecodeTime & 0xFF)\n ])),\n MP4.trun(track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8), // mdat header\n sampleDependencyTable);\n }\n\n /**\n * Generate a track box.\n * @param track {object} a track definition\n * @return {Uint8Array} the track box\n */\n static trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex(track) {\n var id = track.id;\n return MP4.box(MP4.types.trex, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF), // track_ID\n 0x00, 0x00, 0x00, 0x01, // default_sample_description_index\n 0x00, 0x00, 0x00, 0x00, // default_sample_duration\n 0x00, 0x00, 0x00, 0x00, // default_sample_size\n 0x00, 0x01, 0x00, 0x01 // default_sample_flags\n ]));\n }\n\n static trun(track, offset) {\n var samples= track.samples || [],\n len = samples.length,\n arraylen = 12 + (16 * len),\n array = new Uint8Array(arraylen),\n i,sample,duration,size,flags,cts;\n offset += 8 + arraylen;\n array.set([\n 0x00, // version 0\n 0x00, 0x0f, 0x01, // flags\n (len >>> 24) & 0xFF,\n (len >>> 16) & 0xFF,\n (len >>> 8) & 0xFF,\n len & 0xFF, // sample_count\n (offset >>> 24) & 0xFF,\n (offset >>> 16) & 0xFF,\n (offset >>> 8) & 0xFF,\n offset & 0xFF // data_offset\n ],0);\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set([\n (duration >>> 24) & 0xFF,\n (duration >>> 16) & 0xFF,\n (duration >>> 8) & 0xFF,\n duration & 0xFF, // sample_duration\n (size >>> 24) & 0xFF,\n (size >>> 16) & 0xFF,\n (size >>> 8) & 0xFF,\n size & 0xFF, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & 0xF0 << 8,\n flags.degradPrio & 0x0F, // sample_flags\n (cts >>> 24) & 0xFF,\n (cts >>> 16) & 0xFF,\n (cts >>> 8) & 0xFF,\n cts & 0xFF // sample_composition_time_offset\n ],12+16*i);\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n var movie = MP4.moov(tracks), result;\n result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n result.set(MP4.FTYP);\n result.set(movie, MP4.FTYP.byteLength);\n return result;\n }\n}\n\nexport default MP4;\n\n\n\n// WEBPACK FOOTER //\n// ./src/remux/mp4-generator.js"," /**\n * fMP4 remuxer\n*/\n\n\nimport AAC from '../helper/aac';\nimport Event from '../events';\nimport {logger} from '../utils/logger';\nimport MP4 from '../remux/mp4-generator';\nimport {ErrorTypes, ErrorDetails} from '../errors';\n\n// 10 seconds\nconst MAX_SILENT_FRAME_DURATION = 10 * 1000;\n\nclass MP4Remuxer {\n constructor(observer, config, typeSupported, vendor) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n const userAgent = navigator.userAgent;\n this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');\n this.ISGenerated = false;\n }\n\n destroy() {\n }\n\n resetTimeStamp(defaultTimeStamp) {\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetInitSegment() {\n this.ISGenerated = false;\n }\n\n remux(audioTrack,videoTrack,id3Track,textTrack,timeOffset, contiguous,accurateTimeOffset) {\n // generate Init Segment if needed\n if (!this.ISGenerated) {\n this.generateIS(audioTrack,videoTrack,timeOffset);\n }\n\n if (this.ISGenerated) {\n const nbAudioSamples = audioTrack.samples.length;\n const nbVideoSamples = videoTrack.samples.length;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n if (nbAudioSamples && nbVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n let audiovideoDeltaDts = (audioTrack.samples[0].dts - videoTrack.samples[0].dts)/videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0,audiovideoDeltaDts);\n videoTimeOffset += Math.max(0,-audiovideoDeltaDts);\n }\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is\n // calculated in remuxAudio.\n //logger.log('nb AAC samples:' + audioTrack.samples.length);\n if (nbAudioSamples) {\n // if initSegment was generated without video samples, regenerate it again\n if (!audioTrack.timescale) {\n logger.warn('regenerate InitSegment as audio detected');\n this.generateIS(audioTrack,videoTrack,timeOffset);\n }\n let audioData = this.remuxAudio(audioTrack,audioTimeOffset,contiguous,accurateTimeOffset);\n //logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let audioTrackLength;\n if (audioData) {\n audioTrackLength = audioData.endPTS - audioData.startPTS;\n }\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.timescale) {\n logger.warn('regenerate InitSegment as video detected');\n this.generateIS(audioTrack,videoTrack,timeOffset);\n }\n this.remuxVideo(videoTrack,videoTimeOffset,contiguous,audioTrackLength, accurateTimeOffset);\n }\n } else {\n let videoData;\n //logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n videoData = this.remuxVideo(videoTrack,videoTimeOffset,contiguous, accurateTimeOffset);\n }\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n //logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track,timeOffset);\n }\n //logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack,timeOffset);\n }\n //notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED);\n }\n\n generateIS(audioTrack,videoTrack,timeOffset) {\n var observer = this.observer,\n audioSamples = audioTrack.samples,\n videoSamples = videoTrack.samples,\n typeSupported = this.typeSupported,\n container = 'audio/mp4',\n tracks = {},\n data = { tracks : tracks },\n computePTSDTS = (this._initPTS === undefined),\n initPTS, initDTS;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n logger.log (`audio sampling rate : ${audioTrack.samplerate}`);\n if (!audioTrack.isAAC) {\n if (typeSupported.mpeg) { // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) { // Firefox\n audioTrack.codec = 'mp3';\n }\n }\n tracks.audio = {\n container : container,\n codec : audioTrack.codec,\n initSegment : !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : MP4.initSegment([audioTrack]),\n metadata : {\n channelCount : audioTrack.channelCount\n }\n };\n if (computePTSDTS) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n const inputTimeScale = videoTrack.inputTimeScale;\n videoTrack.timescale = inputTimeScale;\n tracks.video = {\n container : 'video/mp4',\n codec : videoTrack.codec,\n initSegment : MP4.initSegment([videoTrack]),\n metadata : {\n width : videoTrack.width,\n height : videoTrack.height\n }\n };\n if (computePTSDTS) {\n initPTS = Math.min(initPTS,videoSamples[0].pts - inputTimeScale * timeOffset);\n initDTS = Math.min(initDTS,videoSamples[0].dts - inputTimeScale * timeOffset);\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS});\n }\n }\n\n if(Object.keys(tracks).length) {\n observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT,data);\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = initPTS;\n this._initDTS = initDTS;\n }\n } else {\n observer.trigger(Event.ERROR, {type : ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found'});\n }\n }\n\n remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {\n var offset = 8,\n timeScale = track.timescale,\n mp4SampleDuration,\n mdat, moof,\n firstPTS, firstDTS,\n nextDTS,\n lastPTS, lastDTS,\n inputSamples = track.samples,\n outputSamples = [],\n nbSamples = inputSamples.length,\n ptsNormalize = this._PTSNormalize,\n initDTS = this._initDTS;\n\n // for (let i = 0; i < track.samples.length; i++) {\n // let avcSample = track.samples[i];\n // let units = avcSample.units;\n // let unitsString = '';\n // for (let j = 0; j < units.length ; j++) {\n // unitsString += units[j].type + ',';\n // if (units[j].data.length < 500) {\n // unitsString += Hex.hexDump(units[j].data);\n // }\n // }\n // logger.log(avcSample.pts + '/' + avcSample.dts + ',' + unitsString + avcSample.units.length);\n // }\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n let nextAvcDts = this.nextAvcDts;\n\n const isSafari = this.isSafari;\n\n // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive\n if (isSafari) {\n // also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 200 ms PTS gaps (timeScale/5)\n contiguous |= (inputSamples.length && nextAvcDts &&\n ((accurateTimeOffset && Math.abs(timeOffset-nextAvcDts/timeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts-nextAvcDts-initDTS)) < timeScale/5)\n );\n }\n\n if (!contiguous) {\n // if not contiguous, let's use target timeOffset\n nextAvcDts = timeOffset*timeScale;\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n inputSamples.forEach(function(sample) {\n sample.pts = ptsNormalize(sample.pts-initDTS, nextAvcDts);\n sample.dts = ptsNormalize(sample.dts-initDTS, nextAvcDts);\n });\n\n // sort video samples by DTS then PTS then demux id order\n inputSamples.sort(function(a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts ? deltadts : deltapts ? deltapts : (a.id - b.id);\n });\n\n // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)\n let PTSDTSshift = inputSamples.reduce( (prev, curr) => Math.max(Math.min(prev,curr.pts-curr.dts),-18000),0);\n if (PTSDTSshift < 0) {\n logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${Math.round(PTSDTSshift/90)} ms to overcome this issue`);\n for (let i = 0; i < inputSamples.length; i++) {\n inputSamples[i].dts += PTSDTSshift;\n }\n }\n\n // compute first DTS and last DTS, normalize them against reference value\n let sample = inputSamples[0];\n firstDTS = Math.max(sample.dts,0);\n firstPTS = Math.max(sample.pts,0);\n\n // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)\n let delta = Math.round((firstDTS - nextAvcDts) / 90);\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n if (delta) {\n if (delta > 1) {\n logger.log(`AVC:${delta} ms hole between fragments detected,filling it`);\n } else if (delta < -1) {\n logger.log(`AVC:${(-delta)} ms overlapping between fragments detected`);\n }\n // remove hole/gap : set DTS to next expected DTS\n firstDTS = nextAvcDts;\n inputSamples[0].dts = firstDTS;\n // offset PTS as well, ensure that PTS is smaller or equal than new DTS\n firstPTS = Math.max(firstPTS - delta, nextAvcDts);\n inputSamples[0].pts = firstPTS;\n logger.log(`Video/PTS/DTS adjusted: ${Math.round(firstPTS/90)}/${Math.round(firstDTS/90)},delta:${delta} ms`);\n }\n }\n nextDTS = firstDTS;\n\n // compute lastPTS/lastDTS\n sample = inputSamples[inputSamples.length-1];\n lastDTS = Math.max(sample.dts,0);\n lastPTS = Math.max(sample.pts,0,lastDTS);\n\n // on Safari let's signal the same sample duration for all samples\n // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n if (isSafari) {\n mp4SampleDuration = Math.round((lastDTS-firstDTS)/(inputSamples.length-1));\n }\n\n let nbNalu = 0, naluLen = 0;\n for (let i = 0 ; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n let sample = inputSamples[i], units = sample.units, nbUnits = units.length, sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // normalize PTS/DTS\n if (isSafari) {\n // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples\n sample.dts = firstDTS + i*mp4SampleDuration;\n } else {\n // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts,firstDTS);\n }\n // ensure that computed value is greater or equal than sample DTS\n sample.pts = Math.max(sample.pts , sample.dts);\n }\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n let mdatSize = naluLen + (4 * nbNalu) + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch(err) {\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes : mdatSize, reason: `fail allocating video mdat ${mdatSize}`});\n return;\n }\n let view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n for (let i = 0 ; i < nbSamples; i++) {\n let avcSample = inputSamples[i],\n avcSampleUnits = avcSample.units,\n mp4SampleLength = 0,\n compositionTimeOffset;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for(let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits ; j++) {\n let unit = avcSampleUnits[j],\n unitData = unit.data,\n unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n if(!isSafari) {\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i+1].dts - avcSample.dts;\n } else {\n let config = this.config,\n lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i-1 : i].dts;\n if (config.stretchShortVideoTrack) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than the minimum of maxBufferHole and\n // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n let maxBufferHole = config.maxBufferHole,\n maxSeekHole = config.maxSeekHole,\n gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * timeScale),\n deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\n logger.log(`It is approximately ${deltaToFrameEnd/90} ms to the next segment; using duration ${mp4SampleDuration/90} ms for the last video frame.`);\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n } else {\n compositionTimeOffset = Math.max(0,mp4SampleDuration*Math.round((avcSample.pts - avcSample.dts)/mp4SampleDuration));\n }\n\n\n //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');\n outputSamples.push({\n size: mp4SampleLength,\n // constant duration\n duration: mp4SampleDuration,\n cts: compositionTimeOffset,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn : avcSample.key ? 2 : 1,\n isNonSync : avcSample.key ? 0 : 1\n }\n });\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n this.nextAvcDts = lastDTS + mp4SampleDuration;\n let dropped = track.dropped;\n track.len = 0;\n track.nbNalu = 0;\n track.dropped = 0;\n if(outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {\n let flags = outputSamples[0].flags;\n // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n track.samples = outputSamples;\n moof = MP4.moof(track.sequenceNumber++, firstDTS , track);\n track.samples = [];\n\n let data = {\n data1: moof,\n data2: mdat,\n startPTS: firstPTS / timeScale,\n endPTS: (lastPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: this.nextAvcDts / timeScale,\n type: 'video',\n nb: outputSamples.length,\n dropped : dropped\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, data);\n return data;\n }\n\n remuxAudio(track, timeOffset, contiguous,accurateTimeOffset) {\n const inputTimeScale = track.inputTimeScale,\n mp4timeScale = track.timescale,\n scaleFactor = inputTimeScale/mp4timeScale,\n mp4SampleDuration = track.isAAC ? 1024 : 1152,\n inputSampleDuration = mp4SampleDuration * scaleFactor,\n ptsNormalize = this._PTSNormalize,\n initDTS = this._initDTS,\n rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n\n var offset,\n mp4Sample,\n fillFrame,\n mdat, moof,\n firstPTS, lastPTS,\n inputSamples = track.samples,\n outputSamples = [],\n nextAudioPts = this.nextAudioPts;\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n contiguous |= (inputSamples.length && nextAudioPts &&\n ((accurateTimeOffset && Math.abs(timeOffset-nextAudioPts/inputTimeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts-nextAudioPts-initDTS)) < 20*inputSampleDuration)\n );\n\n if (!contiguous) {\n // if fragments are not contiguous, let's use timeOffset to compute next Audio PTS\n nextAudioPts = timeOffset*inputTimeScale;\n }\n\n // compute normalized PTS\n inputSamples.forEach(function(sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, nextAudioPts);\n });\n\n // sort based on normalized PTS (this is to avoid sorting issues in case timestamp\n // reloop in the middle of our samples array)\n inputSamples.sort(function(a, b) {\n return a.pts - b.pts;\n });\n\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n // only inject/drop audio frames in case time offset is accurate\n if (accurateTimeOffset && track.isAAC) {\n const maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; ) {\n // First, let's see how far off this frame is from where we expect it to be\n var sample = inputSamples[i], delta;\n let pts = sample.pts;\n delta = pts - nextPts;\n\n //console.log(Math.round(pts) + '/' + Math.round(nextPts) + '/' + Math.round(delta));\n const duration = Math.abs(1000*delta/inputTimeScale);\n\n // If we're overlapping by more than a duration, drop this sample\n if (delta <= -maxAudioFramesDrift*inputSampleDuration) {\n logger.warn(`Dropping 1 audio frame @ ${(nextPts/inputTimeScale).toFixed(3)}s due to ${Math.round(duration)} ms overlap.`);\n inputSamples.splice(i, 1);\n track.len -= sample.unit.length;\n // Don't touch nextPtsNorm or i\n }\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n else if (delta >= maxAudioFramesDrift*inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {\n var missing = Math.round(delta / inputSampleDuration);\n logger.warn(`Injecting ${missing} audio frame @ ${(nextPts/inputTimeScale).toFixed(3)}s due to ${Math.round(1000*delta/inputTimeScale)} ms gap.`);\n for (var j = 0; j < missing; j++) {\n let newStamp = Math.max(nextPts,0);\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec,track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, {unit: fillFrame, pts: newStamp, dts: newStamp});\n track.len += fillFrame.length;\n nextPts += inputSampleDuration;\n i++;\n }\n\n // Adjust sample to next expected pts\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n } else {\n // Otherwise, just adjust pts\n if (Math.abs(delta) > (0.1 * inputSampleDuration)) {\n //logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);\n }\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n }\n }\n }\n\n\n for (let j =0 , nbSamples = inputSamples.length; j < nbSamples ; j++) {\n let audioSample = inputSamples[j];\n let unit = audioSample.unit;\n let pts = audioSample.pts;\n //logger.log(`Audio/PTS:${Math.round(pts/90)}`);\n // if not first sample\n if (lastPTS !== undefined) {\n mp4Sample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n let delta = Math.round(1000 * (pts - nextAudioPts) / inputTimeScale),\n numMissingFrames = 0;\n // if fragment are contiguous, detect hole/overlapping between fragments\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n if (contiguous && track.isAAC) {\n // log delta\n if (delta) {\n if (delta > 0 && delta < MAX_SILENT_FRAME_DURATION) {\n numMissingFrames = Math.round((pts - nextAudioPts) / inputSampleDuration);\n logger.log(`${delta} ms hole between AAC samples detected,filling it`);\n if (numMissingFrames > 0) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec,track.channelCount);\n if (!fillFrame) {\n fillFrame = unit.subarray();\n }\n track.len += numMissingFrames * fillFrame.length;\n }\n // if we have frame overlap, overlapping for more than half a frame duraion\n } else if (delta < -12) {\n // drop overlapping audio frames... browser will deal with it\n logger.log(`drop overlapping AAC sample, expected/parsed/delta:${(nextAudioPts/inputTimeScale).toFixed(3)}s/${(pts/inputTimeScale).toFixed(3)}s/${(-delta)}ms`);\n track.len -= unit.byteLength;\n continue;\n }\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n }\n // remember first PTS of our audioSamples, ensure value is positive\n firstPTS = Math.max(0, pts);\n if(track.len > 0) {\n /* concatenate the audio data and construct the mdat in place\n (need 8 more bytes to fill length and mdat type) */\n let mdatSize = rawMPEG ? track.len : track.len + 8;\n offset = rawMPEG ? 0 : 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch(err) {\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes : mdatSize, reason: `fail allocating audio mdat ${mdatSize}`});\n return;\n }\n if (!rawMPEG) {\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n for (let i = 0; i < numMissingFrames; i++) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec,track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');\n fillFrame = unit.subarray();\n }\n mdat.set(fillFrame, offset);\n offset += fillFrame.byteLength;\n mp4Sample = {\n size: fillFrame.byteLength,\n cts: 0,\n duration: 1024,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1,\n }\n };\n outputSamples.push(mp4Sample);\n }\n }\n mdat.set(unit, offset);\n let unitLen = unit.byteLength;\n offset += unitLen;\n //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');\n mp4Sample = {\n size: unitLen,\n cts: 0,\n duration: 0,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1,\n }\n };\n outputSamples.push(mp4Sample);\n lastPTS = pts;\n }\n var lastSampleDuration = 0;\n var nbSamples = outputSamples.length;\n //set last sample duration as being identical to previous sample\n if (nbSamples >= 2) {\n lastSampleDuration = outputSamples[nbSamples - 2].duration;\n mp4Sample.duration = lastSampleDuration;\n }\n if (nbSamples) {\n // next audio sample PTS should be equal to last sample PTS + duration\n this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;\n //logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));\n track.len = 0;\n track.samples = outputSamples;\n if (rawMPEG) {\n moof = new Uint8Array();\n } else {\n moof = MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);\n }\n track.samples = [];\n const start = firstPTS / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type: 'audio',\n nb: nbSamples\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, audioData);\n return audioData;\n }\n return null;\n }\n\n remuxEmptyAudio(track, timeOffset, contiguous, videoData) {\n let inputTimeScale = track.inputTimeScale,\n mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,\n scaleFactor = inputTimeScale/mp4timeScale,\n nextAudioPts = this.nextAudioPts,\n\n // sync with video's timestamp\n startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,\n endDTS = videoData.endDTS * inputTimeScale + this._initDTS,\n // one sample's duration value\n sampleDuration = 1024,\n frameDuration = scaleFactor * sampleDuration,\n\n // samples count of this segment's duration\n nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),\n\n // silent frame\n silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec,track.channelCount);\n\n logger.warn('remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');\n return;\n }\n\n let samples = [];\n for(var i = 0; i < nbSamples; i++) {\n var stamp = startDTS + i * frameDuration;\n samples.push({unit: silentFrame, pts: stamp, dts: stamp});\n track.len += silentFrame.length;\n }\n track.samples = samples;\n\n this.remuxAudio(track, timeOffset, contiguous);\n }\n\n remuxID3(track,timeOffset) {\n var length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n const initDTS = this._initDTS;\n // consume samples\n if(length) {\n for(var index = 0; index < length; index++) {\n sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = ((sample.pts - initPTS) / inputTimeScale);\n sample.dts = ((sample.dts - initDTS) / inputTimeScale);\n }\n this.observer.trigger(Event.FRAG_PARSING_METADATA, {\n samples:track.samples\n });\n }\n\n track.samples = [];\n timeOffset = timeOffset;\n }\n\n remuxText(track,timeOffset) {\n track.samples.sort(function(a, b) {\n return (a.pts-b.pts);\n });\n\n var length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if(length) {\n for(var index = 0; index < length; index++) {\n sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = ((sample.pts - initPTS) / inputTimeScale);\n }\n this.observer.trigger(Event.FRAG_PARSING_USERDATA, {\n samples:track.samples\n });\n }\n\n track.samples = [];\n timeOffset = timeOffset;\n }\n\n _PTSNormalize(value, reference) {\n var offset;\n if (reference === undefined) {\n return value;\n }\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n return value;\n }\n\n}\n\nexport default MP4Remuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/remux/mp4-remuxer.js","/**\n * passthrough remuxer\n*/\nimport Event from '../events';\n\nclass PassThroughRemuxer {\n constructor(observer) {\n this.observer = observer;\n }\n\n destroy() {\n }\n\n resetTimeStamp() {\n }\n\n resetInitSegment() {\n }\n\n remux(audioTrack,videoTrack,id3Track,textTrack,timeOffset, contiguous,accurateTimeOffset,rawData) {\n var observer = this.observer;\n var streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n if (videoTrack) {\n streamType += 'video';\n }\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n nb: 1,\n dropped : 0\n });\n //notify end of parsing\n observer.trigger(Event.FRAG_PARSED);\n }\n}\n\nexport default PassThroughRemuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/remux/passthrough-remuxer.js","/* inline demuxer.\n * probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n */\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\n\nclass DemuxerInline {\n\n constructor(observer, typeSupported, config, vendor) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n }\n\n destroy() {\n var demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n }\n\n push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {\n let decrypter = this.decrypter;\n if (decrypter == null) {\n decrypter = this.decrypter = new Decrypter(this.observer, this.config);\n }\n var localthis = this;\n // performance.now() not available on WebWorker, at least on Safari Desktop\n var startTime;\n try {\n startTime = performance.now();\n } catch (error) {\n startTime = Date.now();\n }\n decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {\n var endTime;\n try {\n endTime = performance.now();\n } catch (error) {\n endTime = Date.now();\n }\n localthis.observer.trigger(Event.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });\n localthis.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n });\n } else {\n this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n\n pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n var demuxer = this.demuxer;\n if (!demuxer ||\n // in case of continuity change, we might switch from content type (AAC container to TS container for example)\n // so let's check that current demuxer is still valid\n (discontinuity && !this.probe(data))) {\n const observer = this.observer;\n const typeSupported = this.typeSupported;\n const config = this.config;\n // probing order is TS/AAC/MP3/MP4\n const muxConfig = [\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer },\n { demux: MP4Demuxer, remux: PassThroughRemuxer }\n ];\n\n // probe for content type\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n const mux = muxConfig[i];\n const probe = mux.demux.probe;\n if (probe(data)) {\n const remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);\n demuxer = new mux.demux(observer, remuxer, config, typeSupported);\n this.probe = probe;\n break;\n }\n }\n if (!demuxer) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });\n return;\n }\n this.demuxer = demuxer;\n }\n const remuxer = this.remuxer;\n\n if (discontinuity || trackSwitch) {\n demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);\n remuxer.resetInitSegment();\n }\n if (discontinuity) {\n demuxer.resetTimeStamp(defaultInitPTS);\n remuxer.resetTimeStamp(defaultInitPTS);\n }\n if (typeof demuxer.setDecryptData === 'function') {\n demuxer.setDecryptData(decryptdata);\n }\n demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);\n }\n}\n\nexport default DemuxerInline;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/demuxer-inline.js","/*\n*\n* All objects in the event handling chain should inherit from this class\n*\n*/\n\nimport {logger} from './utils/logger';\nimport {ErrorTypes, ErrorDetails} from './errors';\nimport Event from './events';\n\nclass EventHandler {\n\n constructor(hls, ...events) {\n this.hls = hls;\n this.onEvent = this.onEvent.bind(this);\n this.handledEvents = events;\n this.useGenericHandler = true;\n\n this.registerListeners();\n }\n\n destroy() {\n this.unregisterListeners();\n }\n\n isEventHandler() {\n return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';\n }\n\n registerListeners() {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function(event) {\n if (event === 'hlsEventGeneric') {\n throw new Error('Forbidden event name: ' + event);\n }\n this.hls.on(event, this.onEvent);\n }, this);\n }\n }\n\n unregisterListeners() {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function(event) {\n this.hls.off(event, this.onEvent);\n }, this);\n }\n }\n\n /**\n * arguments: event (string), data (any)\n */\n onEvent(event, data) {\n this.onEventGeneric(event, data);\n }\n\n onEventGeneric(event, data) {\n var eventToFunction = function(event, data) {\n var funcName = 'on' + event.replace('hls', '');\n if (typeof this[funcName] !== 'function') {\n throw new Error(`Event ${event} has no generic handler in this ${this.constructor.name} class (tried ${funcName})`);\n }\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n logger.error(`internal error happened while processing ${event}:${err.message}`);\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event : event, err : err});\n }\n }\n}\n\nexport default EventHandler;\n\n\n\n// WEBPACK FOOTER //\n// ./src/event-handler.js","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/;\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g;\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n\n constructor(attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n for(var attr in attrs){\n if(attrs.hasOwnProperty(attr)) {\n this[attr] = attrs[attr];\n }\n }\n }\n\n decimalInteger(attrName) {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n return intValue;\n }\n\n hexadecimalInteger(attrName) {\n if(this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = ((stringValue.length & 1) ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber(attrName) {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n return intValue;\n }\n\n decimalFloatingPoint(attrName) {\n return parseFloat(this[attrName]);\n }\n\n enumeratedString(attrName) {\n return this[attrName];\n }\n\n decimalResolution(attrName) {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList(input) {\n var match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n var value = match[2], quote = '\"';\n\n if (value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === (value.length-1)) {\n value = value.slice(1, -1);\n }\n attrs[match[1]] = value;\n }\n return attrs;\n }\n\n}\n\nexport default AttrList;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/attr-list.js","// from http://mp4ra.org/codecs.html\nconst sampleEntryCodesISO = {\n audio: {\n 'a3ds': true,\n 'ac-3': true,\n 'ac-4': true,\n 'alac': true,\n 'alaw': true,\n 'dra1': true,\n 'dts+': true,\n 'dts-': true,\n 'dtsc': true,\n 'dtse': true,\n 'dtsh': true,\n 'ec-3': true,\n 'enca': true,\n 'g719': true,\n 'g726': true,\n 'm4ae': true,\n 'mha1': true,\n 'mha2': true,\n 'mhm1': true,\n 'mhm2': true,\n 'mlpa': true,\n 'mp4a': true,\n 'raw ': true,\n 'Opus': true,\n 'samr': true,\n 'sawb': true,\n 'sawp': true,\n 'sevc': true,\n 'sqcp': true,\n 'ssmv': true,\n 'twos': true,\n 'ulaw': true\n },\n video: {\n 'avc1': true,\n 'avc2': true,\n 'avc3': true,\n 'avc4': true,\n 'avcp': true,\n 'drac': true,\n 'dvav': true,\n 'dvhe': true,\n 'encv': true,\n 'hev1': true,\n 'hvc1': true,\n 'mjp2': true,\n 'mp4v': true,\n 'mvc1': true,\n 'mvc2': true,\n 'mvc3': true,\n 'mvc4': true,\n 'resv': true,\n 'rv60': true,\n 's263': true,\n 'svc1': true,\n 'svc2': true,\n 'vc-1': true,\n 'vp08': true,\n 'vp09': true\n }\n};\n\nfunction isCodecType(codec, type) {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nfunction isCodecSupportedInMp4(codec, type) {\n return MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/codecs.js","/**\n * Playlist Loader\n*/\n\nimport URLToolkit from 'url-toolkit';\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport AttrList from '../utils/attr-list';\nimport {logger} from '../utils/logger';\nimport {isCodecType} from '../utils/codecs';\n\n// https://regex101.com is your friend\nconst MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp([\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n /|(?!#)(\\S+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /|#.*/.source // All other non-segment oriented tags will match with all groups empty\n].join(''), 'g');\n\nconst LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\\d+))|(?:#EXT-X-(TARGETDURATION): *(\\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\\r?\\n?/;\n\nclass LevelKey {\n\n constructor() {\n this.method = null;\n this.key = null;\n this.iv = null;\n this._uri = null;\n }\n\n get uri() {\n if (!this._uri && this.reluri) {\n this._uri = URLToolkit.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });\n }\n return this._uri;\n }\n\n}\n\nclass Fragment {\n\n constructor() {\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n this.tagList = [];\n }\n\n get url() {\n if (!this._url && this.relurl) {\n this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\n return this._url;\n }\n\n set url(value) {\n this._url = value;\n }\n\n get programDateTime() {\n if (!this._programDateTime && this.rawProgramDateTime) {\n this._programDateTime = new Date(Date.parse(this.rawProgramDateTime));\n }\n return this._programDateTime;\n }\n\n get byteRange() {\n if (!this._byteRange) {\n let byteRange = this._byteRange = [];\n if (this.rawByteRange) {\n const params = this.rawByteRange.split('@', 2);\n if (params.length === 1) {\n const lastByteRangeEndOffset = this.lastByteRangeEndOffset;\n byteRange[0] = lastByteRangeEndOffset ? lastByteRangeEndOffset : 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n }\n }\n return this._byteRange;\n }\n\n get byteRangeStartOffset() {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset() {\n return this.byteRange[1];\n }\n\n get decryptdata() {\n if (!this._decryptdata) {\n this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);\n }\n return this._decryptdata;\n }\n\n /**\n * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n * @returns {Uint8Array}\n */\n createInitializationVector(segmentNumber) {\n var uint8View = new Uint8Array(16);\n\n for (var i = 12; i < 16; i++) {\n uint8View[i] = (segmentNumber >> 8 * (15 - i)) & 0xff;\n }\n\n return uint8View;\n }\n\n /**\n * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data\n * @param levelkey - a playlist's encryption info\n * @param segmentNumber - the fragment's segment number\n * @returns {*} - an object to be applied as a fragment's decryptdata\n */\n fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {\n var decryptdata = levelkey;\n\n if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {\n decryptdata = new LevelKey();\n decryptdata.method = levelkey.method;\n decryptdata.baseuri = levelkey.baseuri;\n decryptdata.reluri = levelkey.reluri;\n decryptdata.iv = this.createInitializationVector(segmentNumber);\n }\n\n return decryptdata;\n }\n\n cloneObj(obj) {\n return JSON.parse(JSON.stringify(obj));\n }\n}\n\nfunction findGroup(groups, mediaGroupId) {\n if (!groups) {\n return null;\n }\n\n let matchingGroup = null;\n\n for (let i = 0; i < groups.length; i ++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n matchingGroup = group;\n }\n }\n\n return matchingGroup;\n}\n\nclass PlaylistLoader extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.LEVEL_LOADING,\n Event.AUDIO_TRACK_LOADING,\n Event.SUBTITLE_TRACK_LOADING);\n this.loaders = {};\n }\n\n destroy() {\n for (let loaderName in this.loaders) {\n let loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n EventHandler.prototype.destroy.call(this);\n }\n\n onManifestLoading(data) {\n this.load(data.url, { type : 'manifest'});\n }\n\n onLevelLoading(data) {\n this.load(data.url, { type : 'level', level : data.level, id : data.id});\n }\n\n onAudioTrackLoading(data) {\n this.load(data.url, { type : 'audioTrack', id : data.id});\n }\n\n onSubtitleTrackLoading(data) {\n this.load(data.url, { type : 'subtitleTrack', id : data.id});\n }\n\n load(url, context) {\n let loader = this.loaders[context.type];\n if (loader) {\n let loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) {\n logger.trace(`playlist request ongoing`);\n return;\n } else {\n logger.warn(`abort previous loader for type:${context.type}`);\n loader.abort();\n }\n }\n let config = this.hls.config,\n retry,\n timeout,\n retryDelay,\n maxRetryDelay;\n if(context.type === 'manifest') {\n retry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n } else {\n retry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n logger.log(`loading playlist for ${context.type} ${context.level || context.id}`);\n }\n loader = this.loaders[context.type] = context.loader = typeof(config.pLoader) !== 'undefined' ? new config.pLoader(config) : new config.loader(config);\n context.url = url;\n context.responseType = '';\n\n let loaderConfig, loaderCallbacks;\n loaderConfig = { timeout : timeout, maxRetry : retry , retryDelay : retryDelay, maxRetryDelay : maxRetryDelay};\n loaderCallbacks = { onSuccess : this.loadsuccess.bind(this), onError :this.loaderror.bind(this), onTimeout : this.loadtimeout.bind(this)};\n loader.load(context,loaderConfig,loaderCallbacks);\n }\n\n resolve(url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n parseMasterPlaylist(string, baseurl) {\n let levels = [], result;\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n function setCodecs(codecs, level) {\n ['video', 'audio'].forEach((type) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n const preferred = filtered.filter((codec) => {\n return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;\n });\n level[`${type}Codec`] = preferred.length > 0 ? preferred[0] : filtered[0];\n\n // remove from list\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n\n level.unknownCodecs = codecs;\n }\n\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null){\n const level = {};\n\n var attrs = level.attrs = new AttrList(result[1]);\n level.url = this.resolve(result[2], baseurl);\n\n var resolution = attrs.decimalResolution('RESOLUTION');\n if(resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');\n level.name = attrs.NAME;\n\n setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);\n\n if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {\n level.videoCodec = this.avc1toavcoti(level.videoCodec);\n }\n\n levels.push(level);\n }\n return levels;\n }\n\n parseMasterPlaylistMedia(string, baseurl, type, audioGroups=[]) {\n let result;\n let medias = [];\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const media = {};\n const attrs = new AttrList(result[1]);\n if (attrs.TYPE === type) {\n media.groupId = attrs['GROUP-ID'];\n media.name = attrs.NAME;\n media.type = type;\n media.default = (attrs.DEFAULT === 'YES');\n media.autoselect = (attrs.AUTOSELECT === 'YES');\n media.forced = (attrs.FORCED === 'YES');\n if (attrs.URI) {\n media.url = this.resolve(attrs.URI, baseurl);\n }\n media.lang = attrs.LANGUAGE;\n if (!media.name) {\n media.name = media.lang;\n }\n if (audioGroups.length) {\n const groupCodec = findGroup(audioGroups, media.groupId);\n media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;\n }\n media.id = id++;\n medias.push(media);\n }\n }\n return medias;\n }\n\n avc1toavcoti(codec) {\n var result, avcdata = codec.split('.');\n if (avcdata.length > 2) {\n result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift()).toString(16);\n result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);\n } else {\n result = codec;\n }\n return result;\n }\n\n parseLevelPlaylist(string, baseurl, id, type) {\n var currentSN = 0,\n totalduration = 0,\n level = {type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0},\n levelkey = new LevelKey(),\n cc = 0,\n prevFrag = null,\n frag = new Fragment(),\n result,\n i;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n const duration = result[1];\n if (duration) { // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title ? title : null;\n frag.tagList.push(title ? [ 'INF',duration,title ] : [ 'INF',duration ]);\n } else if (result[3]) { // url\n if (!isNaN(frag.duration)) {\n const sn = currentSN++;\n frag.type = type;\n frag.start = totalduration;\n frag.levelkey = levelkey;\n frag.sn = sn;\n frag.level = id;\n frag.cc = cc;\n frag.baseurl = baseurl;\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.relurl = (' ' + result[3]).slice(1);\n\n level.fragments.push(frag);\n prevFrag = frag;\n totalduration += frag.duration;\n\n frag = new Fragment();\n }\n } else if (result[4]) { // X-BYTERANGE\n frag.rawByteRange = (' ' + result[4]).slice(1);\n if (prevFrag) {\n const lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;\n if (lastByteRangeEndOffset) {\n frag.lastByteRangeEndOffset = lastByteRangeEndOffset;\n }\n }\n } else if (result[5]) { // PROGRAM-DATE-TIME\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = (' ' + result[5]).slice(1);\n frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\n if (level.programDateTime === undefined) {\n level.programDateTime = new Date(new Date(Date.parse(result[5])) - 1000 * totalduration);\n }\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n for (i = 1; i < result.length; i++) {\n if (result[i] !== undefined) {\n break;\n }\n }\n\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const value1 = (' ' + result[i+1]).slice(1);\n const value2 = (' ' + result[i+2]).slice(1);\n\n switch (result[i]) {\n case '#':\n frag.tagList.push(value2 ? [ value1,value2 ] : [ value1 ]);\n break;\n case 'PLAYLIST-TYPE':\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'TARGETDURATION':\n level.targetduration = parseFloat(value1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case 'DIS':\n cc++;\n frag.tagList.push(['DIS']);\n break;\n case 'DISCONTINUITY-SEQ':\n cc = parseInt(value1);\n break;\n case 'KEY':\n // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4\n var decryptparams = value1;\n var keyAttrs = new AttrList(decryptparams);\n var decryptmethod = keyAttrs.enumeratedString('METHOD'),\n decrypturi = keyAttrs.URI,\n decryptiv = keyAttrs.hexadecimalInteger('IV');\n if (decryptmethod) {\n levelkey = new LevelKey();\n if ((decrypturi) && (['AES-128', 'SAMPLE-AES'].indexOf(decryptmethod) >= 0)) {\n levelkey.method = decryptmethod;\n // URI to get the key\n levelkey.baseuri = baseurl;\n levelkey.reluri = decrypturi;\n levelkey.key = null;\n // Initialization Vector (IV)\n levelkey.iv = decryptiv;\n }\n }\n break;\n case 'START':\n let startParams = value1;\n let startAttrs = new AttrList(startParams);\n let startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n //TIME-OFFSET can be 0\n if ( !isNaN(startTimeOffset) ) {\n level.startTimeOffset = startTimeOffset;\n }\n break;\n case 'MAP':\n let mapAttrs = new AttrList(value1);\n frag.relurl = mapAttrs.URI;\n frag.rawByteRange = mapAttrs.BYTERANGE;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n level.initSegment = frag;\n frag = new Fragment();\n break;\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n frag = prevFrag;\n //logger.log('found ' + level.fragments.length + ' fragments');\n if(frag && !frag.relurl) {\n level.fragments.pop();\n totalduration-=frag.duration;\n }\n level.totalduration = totalduration;\n level.averagetargetduration = totalduration / level.fragments.length;\n level.endSN = currentSN - 1;\n level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;\n level.endCC = cc;\n return level;\n }\n\n loadsuccess(response, stats, context, networkDetails=null) {\n var string = response.data,\n url = response.url,\n type = context.type,\n id = context.id,\n level = context.level,\n hls = this.hls;\n\n this.loaders[type] = undefined;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n stats.tload = performance.now();\n //stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n if (string.indexOf('#EXTM3U') === 0) {\n if (string.indexOf('#EXTINF:') > 0) {\n let isLevel = (type !== 'audioTrack' && type !== 'subtitleTrack'),\n levelId = !isNaN(level) ? level : !isNaN(id) ? id : 0,\n levelDetails = this.parseLevelPlaylist(string, url, levelId, (type === 'audioTrack' ? 'audio' : (type === 'subtitleTrack' ? 'subtitle' : 'main') ));\n levelDetails.tload = stats.tload;\n if (type === 'manifest') {\n // first request, stream manifest (no master playlist), fire manifest loaded event with level details\n hls.trigger(Event.MANIFEST_LOADED, {levels: [{url: url, details : levelDetails}], audioTracks : [], url: url, stats: stats, networkDetails: networkDetails});\n }\n stats.tparsed = performance.now();\n if (levelDetails.targetduration) {\n if (isLevel) {\n hls.trigger(Event.LEVEL_LOADED, {details: levelDetails, level: level || 0, id: id || 0, stats: stats, networkDetails: networkDetails});\n } else {\n if (type === 'audioTrack') {\n hls.trigger(Event.AUDIO_TRACK_LOADED, {details: levelDetails, id: id, stats: stats, networkDetails: networkDetails});\n }\n else if (type === 'subtitleTrack') {\n hls.trigger(Event.SUBTITLE_TRACK_LOADED, {details: levelDetails, id: id, stats: stats, networkDetails: networkDetails});\n }\n }\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'invalid targetduration', networkDetails: networkDetails});\n }\n } else {\n let levels = this.parseMasterPlaylist(string, url);\n // multi level playlist, parse level info\n if (levels.length) {\n const audioGroups = levels.map(l => ({ id: l.attrs.AUDIO, codec: l.audioCodec}));\n let audioTracks = this.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n let subtitles = this.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n let embeddedAudioFound = false;\n audioTracks.forEach(audioTrack => {\n if(!audioTrack.url) {\n embeddedAudioFound = true;\n }\n });\n // if no embedded audio track defined, but audio codec signaled in quality level, we need to signal this main audio track\n // this could happen with playlists with alt audio rendition in which quality levels (main) contains both audio+video. but with mixed audio track not signaled\n if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');\n audioTracks.unshift({ type : 'main', name : 'main'});\n }\n }\n hls.trigger(Event.MANIFEST_LOADED, {levels, audioTracks, subtitles, url, stats, networkDetails});\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest', networkDetails: networkDetails});\n }\n }\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter', networkDetails: networkDetails});\n }\n }\n\n loaderror(response, context, networkDetails=null) {\n var details, fatal,loader = context.loader;\n switch(context.type) {\n case 'manifest':\n details = ErrorDetails.MANIFEST_LOAD_ERROR;\n fatal = true;\n break;\n case 'level':\n details = ErrorDetails.LEVEL_LOAD_ERROR;\n fatal = false;\n break;\n case 'audioTrack':\n details = ErrorDetails.AUDIO_TRACK_LOAD_ERROR;\n fatal = false;\n break;\n }\n if (loader) {\n loader.abort();\n this.loaders[context.type] = undefined;\n }\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, response: response, context : context, networkDetails: networkDetails});\n }\n\n loadtimeout(stats, context, networkDetails=null) {\n var details, fatal, loader = context.loader;\n switch(context.type) {\n case 'manifest':\n details = ErrorDetails.MANIFEST_LOAD_TIMEOUT;\n fatal = true;\n break;\n case 'level':\n details = ErrorDetails.LEVEL_LOAD_TIMEOUT;\n fatal = false;\n break;\n case 'audioTrack':\n details = ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT;\n fatal = false;\n break;\n }\n if (loader) {\n loader.abort();\n this.loaders[context.type] = undefined;\n }\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, context : context, networkDetails: networkDetails});\n }\n}\n\nexport default PlaylistLoader;\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/playlist-loader.js","/*\n * Fragment Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\n\nclass FragmentLoader extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.FRAG_LOADING);\n this.loaders = {};\n }\n\n destroy() {\n let loaders = this.loaders;\n for (let loaderName in loaders) {\n let loader = loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n EventHandler.prototype.destroy.call(this);\n }\n\n onFragLoading(data) {\n let frag = data.frag,\n type = frag.type,\n loader = this.loaders[type],\n config = this.hls.config;\n\n frag.loaded = 0;\n if (loader) {\n logger.warn(`abort previous fragment loader for type:${type}`);\n loader.abort();\n }\n loader = this.loaders[type] = frag.loader = typeof(config.fLoader) !== 'undefined' ? new config.fLoader(config) : new config.loader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n loaderContext = { url : frag.url, frag : frag, responseType : 'arraybuffer', progressData : false};\n let start = frag.byteRangeStartOffset, end = frag.byteRangeEndOffset;\n if (!isNaN(start) && !isNaN(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n loaderConfig = { timeout : config.fragLoadingTimeOut, maxRetry : 0 , retryDelay : 0, maxRetryDelay : config.fragLoadingMaxRetryTimeout};\n loaderCallbacks = { onSuccess : this.loadsuccess.bind(this), onError :this.loaderror.bind(this), onTimeout : this.loadtimeout.bind(this), onProgress: this.loadprogress.bind(this)};\n loader.load(loaderContext,loaderConfig,loaderCallbacks);\n }\n\n loadsuccess(response, stats, context, networkDetails=null) {\n let payload = response.data, frag = context.frag;\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.FRAG_LOADED, {payload: payload, frag: frag, stats: stats, networkDetails: networkDetails});\n }\n\n loaderror(response, context, networkDetails=null) {\n let loader = context.loader;\n if (loader) {\n loader.abort();\n }\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails});\n }\n\n loadtimeout(stats, context, networkDetails=null) {\n let loader = context.loader;\n if (loader) {\n loader.abort();\n }\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails});\n }\n\n // data will be used for progressive parsing\n loadprogress(stats, context, data, networkDetails=null) { // jshint ignore:line\n let frag = context.frag;\n frag.loaded = stats.loaded;\n this.hls.trigger(Event.FRAG_LOAD_PROGRESS, {frag: frag, stats: stats, networkDetails: networkDetails});\n }\n}\n\nexport default FragmentLoader;\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/fragment-loader.js","/*\n * Decrypt key Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\n\nclass KeyLoader extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.KEY_LOADING);\n this.loaders = {};\n this.decryptkey = null;\n this.decrypturl = null;\n }\n\n destroy() {\n for (let loaderName in this.loaders) {\n let loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n EventHandler.prototype.destroy.call(this);\n }\n\n onKeyLoading(data) {\n let frag = data.frag,\n type = frag.type,\n loader = this.loaders[type],\n decryptdata = frag.decryptdata,\n uri = decryptdata.uri;\n // if uri is different from previous one or if decrypt key not retrieved yet\n if (uri !== this.decrypturl || this.decryptkey === null) {\n let config = this.hls.config;\n\n if (loader) {\n logger.warn(`abort previous key loader for type:${type}`);\n loader.abort();\n }\n frag.loader = this.loaders[type] = new config.loader(config);\n this.decrypturl = uri;\n this.decryptkey = null;\n\n let loaderContext, loaderConfig, loaderCallbacks;\n loaderContext = { url : uri, frag : frag, responseType : 'arraybuffer'};\n loaderConfig = { timeout : config.fragLoadingTimeOut, maxRetry : config.fragLoadingMaxRetry , retryDelay : config.fragLoadingRetryDelay, maxRetryDelay : config.fragLoadingMaxRetryTimeout};\n loaderCallbacks = { onSuccess : this.loadsuccess.bind(this), onError :this.loaderror.bind(this), onTimeout : this.loadtimeout.bind(this)};\n frag.loader.load(loaderContext,loaderConfig,loaderCallbacks);\n } else if (this.decryptkey) {\n // we already loaded this key, return it\n decryptdata.key = this.decryptkey;\n this.hls.trigger(Event.KEY_LOADED, {frag: frag});\n }\n }\n\n loadsuccess(response, stats, context) {\n let frag = context.frag;\n this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.KEY_LOADED, {frag: frag});\n }\n\n loaderror(response, context) {\n let frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response});\n }\n\n loadtimeout(stats, context) {\n let frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag});\n }\n}\n\nexport default KeyLoader;\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/key-loader.js","var BinarySearch = {\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param {Array} list The array to search.\n * @param {Function} comparisonFunction\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @return {*} The object if it is found or null otherwise.\n */\n search: function(list, comparisonFunction) {\n var minIndex = 0;\n var maxIndex = list.length - 1;\n var currentIndex = null;\n var currentElement = null;\n \n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n \n var comparisonResult = comparisonFunction(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n }\n else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n }\n else {\n return currentElement;\n }\n }\n \n return null;\n }\n};\n\nexport default BinarySearch;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/binary-search.js","/**\n * Buffer Helper utils, providing methods dealing buffer length retrieval\n*/\n\nconst BufferHelper = {\n isBuffered : function(media,position) {\n if (media) {\n let buffered = media.buffered;\n for (let i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n return false;\n },\n\n bufferInfo : function(media, pos,maxHoleDuration) {\n if (media) {\n var vbuffered = media.buffered, buffered = [],i;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({start: vbuffered.start(i), end: vbuffered.end(i)});\n }\n return this.bufferedInfo(buffered,pos,maxHoleDuration);\n } else {\n return {len: 0, start: pos, end: pos, nextStart : undefined} ;\n }\n },\n\n bufferedInfo : function(buffered,pos,maxHoleDuration) {\n var buffered2 = [],\n // bufferStart and bufferEnd are buffer boundaries around current video position\n bufferLen,bufferStart, bufferEnd,bufferStartNext,i;\n // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n buffered.sort(function (a, b) {\n var diff = a.start - b.start;\n if (diff) {\n return diff;\n } else {\n return b.end - a.end;\n }\n });\n // there might be some small holes between buffer time range\n // consider that holes smaller than maxHoleDuration are irrelevant and build another\n // buffer time range representations that discards those holes\n for (i = 0; i < buffered.length; i++) {\n var buf2len = buffered2.length;\n if(buf2len) {\n var buf2end = buffered2[buf2len - 1].end;\n // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n if((buffered[i].start - buf2end) < maxHoleDuration) {\n // merge overlapping time ranges\n // update lastRange.end only if smaller than item.end\n // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n if(buffered[i].end > buf2end) {\n buffered2[buf2len - 1].end = buffered[i].end;\n }\n } else {\n // big hole\n buffered2.push(buffered[i]);\n }\n } else {\n // first value\n buffered2.push(buffered[i]);\n }\n }\n for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {\n var start = buffered2[i].start,\n end = buffered2[i].end;\n //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return {len: bufferLen, start: bufferStart, end: bufferEnd, nextStart : bufferStartNext};\n }\n};\n\nexport default BufferHelper;\n\n\n\n// WEBPACK FOOTER //\n// ./src/helper/buffer-helper.js","/**\n * MediaSource helper\n */\n\nexport function getMediaSource() {\n if (typeof window !== 'undefined') {\n return window.MediaSource || window.WebKitMediaSource;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/helper/mediasource-helper.js","import Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport {logger} from '../utils/logger';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport EventEmitter from 'events';\nimport work from 'webworkify-webpack';\nimport {getMediaSource} from '../helper/mediasource-helper';\n\nconst MediaSource = getMediaSource();\n\nclass Demuxer {\n\n constructor(hls, id) {\n this.hls = hls;\n this.id = id;\n // observer setup\n const observer = this.observer = new EventEmitter();\n const config = hls.config;\n observer.trigger = function trigger (event, ...data) {\n observer.emit(event, event, ...data);\n };\n\n observer.off = function off (event, ...data) {\n observer.removeListener(event, ...data);\n };\n\n var forwardMessage = function(ev,data) {\n data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n hls.trigger(ev,data);\n }.bind(this);\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSING_DATA, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n const typeSupported = {\n mp4 : MediaSource.isTypeSupported('video/mp4'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"')\n };\n // navigator.vendor is not always available in Web Worker\n // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n const vendor = navigator.vendor;\n if (config.enableWorker && (typeof(Worker) !== 'undefined')) {\n logger.log('demuxing in webworker');\n let w;\n try {\n w = this.w = work(require.resolve('../demux/demuxer-worker.js'));\n this.onwmsg = this.onWorkerMessage.bind(this);\n w.addEventListener('message', this.onwmsg);\n w.onerror = function(event) { hls.trigger(Event.ERROR, {type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event : 'demuxerWorker', err : { message : event.message + ' (' + event.filename + ':' + event.lineno + ')' }});};\n w.postMessage({cmd: 'init', typeSupported : typeSupported, vendor : vendor, id : id, config: JSON.stringify(config)});\n } catch(err) {\n logger.error('error while initializing DemuxerWorker, fallback on DemuxerInline');\n if (w) {\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n URL.revokeObjectURL(w.objectURL);\n }\n this.demuxer = new DemuxerInline(observer,typeSupported,config,vendor);\n this.w = undefined;\n }\n } else {\n this.demuxer = new DemuxerInline(observer,typeSupported,config, vendor);\n }\n }\n\n destroy() {\n let w = this.w;\n if (w) {\n w.removeEventListener('message', this.onwmsg);\n w.terminate();\n this.w = null;\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n this.demuxer = null;\n }\n }\n let observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n this.observer = null;\n }\n }\n\n push(data, initSegment, audioCodec, videoCodec, frag, duration,accurateTimeOffset,defaultInitPTS) {\n const w = this.w;\n const timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start;\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n const discontinuity = !(lastFrag && (frag.cc === lastFrag.cc));\n const trackSwitch = !(lastFrag && (frag.level === lastFrag.level));\n const nextSN = lastFrag && (frag.sn === (lastFrag.sn+1));\n const contiguous = !trackSwitch && nextSN;\n if (discontinuity) {\n logger.log(`${this.id}:discontinuity detected`);\n }\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\n this.frag = frag;\n if (w) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n w.postMessage({cmd: 'demux', data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset,defaultInitPTS}, data instanceof ArrayBuffer ? [data] : []);\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset,defaultInitPTS);\n }\n }\n }\n\n onWorkerMessage(ev) {\n let data = ev.data,\n hls = this.hls;\n //console.log('onWorkerMessage:' + data.event);\n switch(data.event) {\n case 'init':\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n URL.revokeObjectURL(this.w.objectURL);\n break;\n // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects\n case Event.FRAG_PARSING_DATA:\n data.data.data1 = new Uint8Array(data.data1);\n if (data.data2) {\n data.data.data2 = new Uint8Array(data.data2);\n }\n /* falls through */\n default:\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\n hls.trigger(data.event, data.data);\n break;\n }\n }\n}\n\nexport default Demuxer;\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/demuxer.js","/**\n * Level Helper class, providing methods dealing with playlist sliding and drift\n*/\n\nimport {logger} from '../utils/logger';\n\nexport function updatePTS(fragments,fromIdx, toIdx) {\n var fragFrom = fragments[fromIdx], fragTo = fragments[toIdx], fragToPTS = fragTo.startPTS;\n // if we know startPTS[toIdx]\n if (!isNaN(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n if (toIdx > fromIdx) {\n fragFrom.duration = fragToPTS - fragFrom.start;\n if (fragFrom.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragFrom.sn},level ${fragFrom.level}, there should be some duration drift between playlist and fragment!`);\n }\n } else {\n fragTo.duration = fragFrom.start - fragToPTS;\n if (fragTo.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragTo.sn},level ${fragTo.level}, there should be some duration drift between playlist and fragment!`);\n }\n }\n } else {\n // we dont know startPTS[toIdx]\n if (toIdx > fromIdx) {\n fragTo.start = fragFrom.start + fragFrom.duration;\n } else {\n fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n }\n}\n\nexport function updateFragPTSDTS(details,frag,startPTS,endPTS,startDTS,endDTS) {\n // update frag PTS/DTS\n let maxStartPTS = startPTS;\n if (!isNaN(frag.startPTS)) {\n // delta PTS between audio and video\n let deltaPTS = Math.abs(frag.startPTS - startPTS);\n if (isNaN(frag.deltaPTS)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);\n }\n maxStartPTS = Math.max(startPTS,frag.startPTS);\n startPTS = Math.min(startPTS, frag.startPTS);\n endPTS = Math.max(endPTS, frag.endPTS);\n startDTS = Math.min(startDTS, frag.startDTS);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n const drift = startPTS - frag.start;\n frag.start = frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.endPTS = endPTS;\n frag.startDTS = startDTS;\n frag.endDTS = endDTS;\n frag.duration = endPTS - startPTS;\n\n const sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n var fragIdx, fragments, i;\n fragIdx = sn - details.startSN;\n fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happpen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updatePTS(fragments, i, i - 1);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updatePTS(fragments, i, i + 1);\n }\n details.PTSKnown = true;\n //logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);\n\n return drift;\n}\n\nexport function mergeDetails(oldDetails,newDetails) {\n var start = Math.max(oldDetails.startSN,newDetails.startSN)-newDetails.startSN,\n end = Math.min(oldDetails.endSN,newDetails.endSN)-newDetails.startSN,\n delta = newDetails.startSN - oldDetails.startSN,\n oldfragments = oldDetails.fragments,\n newfragments = newDetails.fragments,\n ccOffset =0,\n PTSFrag;\n\n // check if old/new playlists have fragments in common\n if ( end < start) {\n newDetails.PTSKnown = false;\n return;\n }\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n for(var i = start ; i <= end ; i++) {\n var oldFrag = oldfragments[delta+i],\n newFrag = newfragments[i];\n if (newFrag && oldFrag) {\n ccOffset = oldFrag.cc - newFrag.cc;\n if (!isNaN(oldFrag.startPTS)) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS;\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.duration = oldFrag.duration;\n newFrag.backtracked = oldFrag.backtracked;\n newFrag.dropped = oldFrag.dropped;\n PTSFrag = newFrag;\n }\n }\n }\n\n if(ccOffset) {\n logger.log(`discontinuity sliding from playlist, take drift into account`);\n for(i = 0 ; i < newfragments.length ; i++) {\n newfragments[i].cc += ccOffset;\n }\n }\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if(PTSFrag) {\n updateFragPTSDTS(newDetails,PTSFrag,PTSFrag.startPTS,PTSFrag.endPTS,PTSFrag.startDTS,PTSFrag.endDTS);\n } else {\n // ensure that delta is within oldfragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n if (delta >= 0 && delta < oldfragments.length) {\n // adjust start by sliding offset\n var sliding = oldfragments[delta].start;\n for(i = 0 ; i < newfragments.length ; i++) {\n newfragments[i].start += sliding;\n }\n }\n }\n // if we are here, it means we have fragments overlapping between\n // old and new level. reliable PTS info is thus relying on old level\n newDetails.PTSKnown = oldDetails.PTSKnown;\n }\n\n\n\n// WEBPACK FOOTER //\n// ./src/helper/level-helper.js","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString : function(r) {\n var log = '', len = r.length;\n for (var i=0; i<len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n return log;\n }\n};\n\nexport default TimeRanges;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/timeRanges.js","import BinarySearch from './binary-search';\nimport {logger} from '../utils/logger';\n\nexport function findFirstFragWithCC(fragments, cc) {\n let firstFrag = null;\n\n for (let i = 0; i < fragments.length; i += 1) {\n const currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nexport function findFragWithCC(fragments, CC) {\n return BinarySearch.search(fragments, (candidate) => {\n if (candidate.cc < CC) {\n return 1;\n } else if (candidate.cc > CC) {\n return -1;\n } else {\n return 0;\n }\n });\n}\n\nexport function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {\n let shouldAlign = false;\n if (lastLevel && lastLevel.details && details) {\n if (details.endCC > details.startCC || (lastFrag && lastFrag.cc < details.startCC)) {\n shouldAlign = true;\n }\n }\n return shouldAlign;\n}\n\n// Find the first frag in the previous level which matches the CC of the first frag of the new level\nexport function findDiscontinuousReferenceFrag(prevDetails, curDetails) {\n const prevFrags = prevDetails.fragments;\n const curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n logger.log('No fragments to align');\n return;\n }\n\n const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n logger.log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nexport function adjustPts(sliding, details) {\n details.fragments.forEach((frag) => {\n if (frag) {\n let start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n });\n details.PTSKnown = true;\n}\n\n// If a change in CC is detected, the PTS can no longer be relied upon\n// Attempt to align the level by using the last level - find the last frag matching the current CC and use it's PTS\n// as a reference\nexport function alignDiscontinuities(lastFrag, lastLevel, details) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);\n if (referenceFrag) {\n logger.log('Adjusting PTS using last level due to CC increase within current level');\n adjustPts(referenceFrag.start, details);\n }\n }\n // try to align using programDateTime attribute (if available)\n if (details.PTSKnown === false && lastLevel && lastLevel.details) {\n // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM\n // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM\n // then we can deduce that playlist B sliding is 1000+8 = 1008s\n let lastPDT = lastLevel.details.programDateTime;\n let newPDT = details.programDateTime;\n // date diff is in ms. frag.start is in seconds\n let sliding = (newPDT - lastPDT)/1000 + lastLevel.details.fragments[0].start;\n if (!isNaN(sliding)) {\n logger.log(`adjusting PTS using programDateTime delta, sliding:${sliding.toFixed(3)}`);\n adjustPts(sliding,details);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/discontinuities.js","/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport BufferHelper from '../helper/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport * as LevelHelper from '../helper/level-helper';import TimeRanges from '../utils/timeRanges';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\nimport { alignDiscontinuities } from '../utils/discontinuities';\n\n\nconst State = {\n STOPPED : 'STOPPED',\n IDLE : 'IDLE',\n KEY_LOADING : 'KEY_LOADING',\n FRAG_LOADING : 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY : 'FRAG_LOADING_WAITING_RETRY',\n WAITING_LEVEL : 'WAITING_LEVEL',\n PARSING : 'PARSING',\n PARSED : 'PARSED',\n BUFFER_FLUSHING : 'BUFFER_FLUSHING',\n ENDED : 'ENDED',\n ERROR : 'ERROR'\n};\n\nclass StreamController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.LEVEL_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_LOAD_EMERGENCY_ABORTED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_SWITCHED,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED);\n\n this.config = hls.config;\n this.audioCodecSwap = false;\n this.ticks = 0;\n this._state = State.STOPPED;\n this.ontick = this.tick.bind(this);\n }\n\n destroy() {\n this.stopLoad();\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n EventHandler.prototype.destroy.call(this);\n this.state = State.STOPPED;\n }\n\n startLoad(startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n if (!this.timer) {\n this.timer = setInterval(this.ontick, 100);\n }\n this.level = -1;\n this.fragLoadError = 0;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n this.level = hls.nextLoadLevel = startLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;\n this.tick();\n } else {\n this.forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n stopLoad() {\n var frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.state = State.STOPPED;\n this.forceStartLoad = false;\n }\n\n tick() {\n this.ticks++;\n if (this.ticks === 1) {\n this.doTick();\n if (this.ticks > 1) {\n setTimeout(this.tick, 1);\n }\n this.ticks = 0;\n }\n }\n\n doTick() {\n switch(this.state) {\n case State.ERROR:\n //don't do anything in error state to avoid breaking further ...\n break;\n case State.BUFFER_FLUSHING:\n // in buffer flushing state, reset fragLoadError counter\n this.fragLoadError = 0;\n break;\n case State.IDLE:\n this._doTickIdle();\n break;\n case State.WAITING_LEVEL:\n var level = this.levels[this.level];\n // check if playlist is already loaded\n if (level && level.details) {\n this.state = State.IDLE;\n }\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if(!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log(`mediaController: retryDate reached, switch back to IDLE state`);\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle() {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch disable\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (this.levelLastLoaded === undefined || (\n !media && (this.startFragRequested || !config.startFragPrefetch))) {\n return;\n }\n\n // if we have not yet loaded any fragment, start loading from start position\n let pos;\n if (this.loadedmetadata) {\n pos = media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n // determine next load level\n let level = hls.nextLoadLevel,\n levelInfo = this.levels[level];\n\n if (!levelInfo) {\n return;\n }\n\n let levelBitrate = levelInfo.bitrate,\n maxBufLen;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s\n if (levelBitrate) {\n maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);\n } else {\n maxBufLen = config.maxBufferLength;\n }\n maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);\n\n // determine next candidate fragment to be loaded, based on current position and end of buffer position\n // ensure up to `config.maxMaxBufferLength` of buffer upfront\n\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),\n bufferLen = bufferInfo.len;\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n\n // if buffer length is less than maxBufLen try to load a new fragment ...\n logger.trace(`buffer length of ${bufferLen.toFixed(3)} is below max of ${maxBufLen.toFixed(3)}. checking for more payload ...`);\n\n // set next load level : this will trigger a playlist load if needed\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) {\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n // we just got done loading the final fragment and there is no other buffered range after ...\n // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between\n // so we should not switch to ENDED in that case, to be able to buffer them\n // dont switch to ENDED if we need to backtrack last fragment\n let fragPrevious = this.fragPrevious;\n if (!levelDetails.live && fragPrevious && !fragPrevious.backtracked && fragPrevious.sn === levelDetails.endSN && !bufferInfo.nextStart) {\n // fragPrevious is last fragment. retrieve level duration using last frag start offset + duration\n // real duration might be lower than initial duration if there are drifts between real frag duration and playlist signaling\n const duration = Math.min(media.duration,fragPrevious.start + fragPrevious.duration);\n // if everything (almost) til the end is buffered, let's signal eos\n // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference (audio/video offsets...)\n // tolerate up to one frag duration to cope with these cases.\n // also cope with almost zero last frag duration (max last frag duration with 200ms) refer to https://github.com/video-dev/hls.js/pull/657\n if (duration - Math.max(bufferInfo.end,fragPrevious.start) <= Math.max(0.2,fragPrevious.duration)) {\n // Finalize the media stream\n let data = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n this.hls.trigger(Event.BUFFER_EOS,data);\n this.state = State.ENDED;\n return;\n }\n }\n\n // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)\n this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);\n }\n\n _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {\n const fragPrevious = this.fragPrevious,\n level = this.level,\n fragments = levelDetails.fragments,\n fragLen = fragments.length;\n\n // empty playlist\n if (fragLen === 0) {\n return;\n }\n\n // find fragment index, contiguous with end of buffer position\n let start = fragments[0].start,\n end = fragments[fragLen-1].start + fragments[fragLen-1].duration,\n bufferEnd = bufferInfo.end,\n frag;\n\n if (levelDetails.initSegment && !levelDetails.initSegment.data) {\n frag = levelDetails.initSegment;\n } else {\n // in case of live playlist we need to ensure that requested position is not located before playlist start\n if (levelDetails.live) {\n let initialLiveManifestSize = this.config.initialLiveManifestSize;\n if(fragLen < initialLiveManifestSize){\n logger.warn(`Can not start playback of a level, reason: not enough fragments ${fragLen} < ${initialLiveManifestSize}`);\n return;\n }\n\n frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);\n // if it explicitely returns null don't load any fragment and exit function now\n if (frag === null) {\n return;\n }\n\n } else {\n // VoD playlist: if bufferEnd before start of playlist, load first fragment\n if (bufferEnd < start) {\n frag = fragments[0];\n }\n }\n }\n if (!frag) {\n frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);\n }\n if(frag) {\n this._loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd);\n }\n return;\n }\n\n _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {\n const config = this.hls.config, media = this.media;\n\n let frag;\n\n // check if requested position is within seekable boundaries :\n //logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);\n let maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount*levelDetails.targetduration;\n\n if (bufferEnd < Math.max(start-config.maxFragLookUpTolerance, end - maxLatency)) {\n let liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n logger.log(`buffer end: ${bufferEnd.toFixed(3)} is located too far from the end of live sliding playlist, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);\n bufferEnd = liveSyncPosition;\n if (media && media.readyState && media.duration > liveSyncPosition) {\n media.currentTime = liveSyncPosition;\n }\n this.nextLoadPosition = liveSyncPosition;\n }\n\n // if end of buffer greater than live edge, don't load any fragment\n // this could happen if live playlist intermittently slides in the past.\n // level 1 loaded [182580161,182580167]\n // level 1 loaded [182580162,182580169]\n // Loading 182580168 of [182580162 ,182580169],level 1 ..\n // Loading 182580169 of [182580162 ,182580169],level 1 ..\n // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168\n // level 1 loaded [182580164,182580171]\n //\n // don't return null in case media not loaded yet (readystate === 0)\n if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {\n return null;\n }\n\n if (this.startFragRequested && !levelDetails.PTSKnown) {\n /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...\n try to load frag matching with next SN.\n even if SN are not synchronized between playlists, loading this frag will help us\n compute playlist sliding and find the right one after in case it was not the right consecutive one */\n if (fragPrevious) {\n const targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n logger.log(`live playlist, switching playlist, load frag with next SN: ${frag.sn}`);\n }\n }\n // next frag SN not available (or not with same continuity counter)\n // look for a frag sharing the same CC\n if (!frag) {\n frag = BinarySearch.search(fragments, function(frag) {\n return fragPrevious.cc - frag.cc;\n });\n if (frag) {\n logger.log(`live playlist, switching playlist, load frag with same CC: ${frag.sn}`);\n }\n }\n }\n if (!frag) {\n /* we have no idea about which fragment should be loaded.\n so let's load mid fragment. it will help computing playlist sliding and find the right one\n */\n frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];\n logger.log(`live playlist, switching playlist, unknown, load middle frag : ${frag.sn}`);\n }\n }\n return frag;\n }\n\n _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {\n const config = this.hls.config;\n let frag;\n let foundFrag;\n let maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;\n let fragmentWithinToleranceTest = (candidate) => {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n return -1;\n }\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest);\n }\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen-1];\n }\n if (foundFrag) {\n frag = foundFrag;\n const curSNIdx = frag.sn - levelDetails.startSN;\n const sameLevel = fragPrevious && frag.level === fragPrevious.level;\n const prevFrag = fragments[curSNIdx - 1];\n const nextFrag = fragments[curSNIdx + 1];\n //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.sn === fragPrevious.sn) {\n if (sameLevel && !frag.backtracked) {\n if (frag.sn < levelDetails.endSN) {\n let deltaPTS = fragPrevious.deltaPTS;\n // if there is a significant delta between audio and video, larger than max allowed hole,\n // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)\n // let's try to load previous fragment again to get last keyframe\n // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)\n if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {\n frag = prevFrag;\n logger.warn(`SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this`);\n // decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded\n fragPrevious.loadCounter--;\n } else {\n frag = nextFrag;\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n }\n } else {\n frag = null;\n }\n } else if (frag.backtracked) {\n // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes\n if (nextFrag && nextFrag.backtracked) {\n logger.warn(`Already backtracked from fragment ${nextFrag.sn}, will not backtrack to fragment ${frag.sn}. Loading fragment ${nextFrag.sn}`);\n frag = nextFrag;\n } else {\n // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe\n // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment\n logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');\n frag.dropped = 0;\n if (prevFrag) {\n if (prevFrag.loadCounter) {\n prevFrag.loadCounter--;\n }\n frag = prevFrag;\n frag.backtracked = true;\n } else if (curSNIdx) {\n // can't backtrack on very first fragment\n frag = null;\n }\n }\n }\n }\n }\n return frag;\n }\n\n _loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd) {\n const hls = this.hls,\n config = hls.config;\n\n //logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));\n if ((frag.decryptdata && frag.decryptdata.uri != null) && (frag.decryptdata.key == null)) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);\n this.state = State.KEY_LOADING;\n hls.trigger(Event.KEY_LOADING, {frag: frag});\n } else {\n logger.log(`Loading ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}, currentTime:${pos.toFixed(3)},bufferEnd:${bufferEnd.toFixed(3)}`);\n // ensure that we are not reloading the same fragments in loop ...\n if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx++;\n } else {\n this.fragLoadIdx = 0;\n }\n if (frag.loadCounter) {\n frag.loadCounter++;\n let maxThreshold = config.fragLoadingLoopThreshold;\n // if this frag has already been loaded 3 times, and if it has been reloaded recently\n if (frag.loadCounter > maxThreshold && (Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold)) {\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag});\n return;\n }\n } else {\n frag.loadCounter = 1;\n }\n frag.loadIdx = this.fragLoadIdx;\n frag.autoLevel = hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n this.fragCurrent = frag;\n this.startFragRequested = true;\n // Don't update nextLoadPosition for fragments which are not buffered\n if (!isNaN(frag.sn) && !frag.bitrateTest) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n hls.trigger(Event.FRAG_LOADING, {frag: frag});\n // lazy demuxer init, as this could take some time ... do it during frag loading\n if (!this.demuxer) {\n this.demuxer = new Demuxer(hls,'main');\n }\n this.state = State.FRAG_LOADING;\n return;\n }\n }\n\n set state(nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`main stream:${previousState}->${nextState}`);\n this.hls.trigger(Event.STREAM_STATE_TRANSITION, {previousState, nextState});\n }\n }\n\n get state() {\n return this._state;\n }\n\n getBufferedFrag(position) {\n return BinarySearch.search(this._bufferedFrags, function(frag) {\n if (position < frag.startPTS) {\n return -1;\n } else if (position > frag.endPTS) {\n return 1;\n }\n return 0;\n });\n }\n\n get currentLevel() {\n let media = this.media;\n if (media) {\n const frag = this.getBufferedFrag(media.currentTime);\n if (frag) {\n return frag.level;\n }\n }\n return -1;\n }\n\n get nextBufferedFrag() {\n let media = this.media;\n if (media) {\n // first get end range of current fragment\n return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));\n } else {\n return null;\n }\n }\n\n followingBufferedFrag(frag) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.endPTS + 0.5);\n }\n return null;\n }\n\n get nextLevel() {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n } else {\n return -1;\n }\n }\n\n _checkFragmentChanged() {\n var fragPlayingCurrent, currentTime, video = this.media;\n if (video && video.readyState && video.seeking === false) {\n currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n if(currentTime > video.playbackRate*this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\n if (BufferHelper.isBuffered(video,currentTime)) {\n fragPlayingCurrent = this.getBufferedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video,currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n var fragPlaying = fragPlayingCurrent;\n if (fragPlaying !== this.fragPlaying) {\n this.hls.trigger(Event.FRAG_CHANGED, {frag: fragPlaying});\n const fragPlayingLevel = fragPlaying.level;\n if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {\n this.hls.trigger(Event.LEVEL_SWITCHED, {level: fragPlayingLevel});\n }\n this.fragPlaying = fragPlaying;\n }\n }\n }\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n immediateLevelSwitch() {\n logger.log('immediateLevelSwitch');\n if (!this.immediateSwitch) {\n this.immediateSwitch = true;\n let media = this.media, previouslyPaused;\n if (media) {\n previouslyPaused = media.paused;\n media.pause();\n } else {\n // don't restart playback after instant level switch in case media not attached\n previouslyPaused = true;\n }\n this.previouslyPaused = previouslyPaused;\n }\n var fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n }\n // flush everything\n this.flushMainBuffer(0,Number.POSITIVE_INFINITY);\n }\n\n /*\n on immediate level switch end, after new fragment has been buffered :\n - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)\n - resume the playback if needed\n */\n immediateLevelSwitchEnd() {\n let media = this.media;\n if (media && media.buffered.length) {\n this.immediateSwitch = false;\n if(BufferHelper.isBuffered(media,media.currentTime)) {\n // only nudge if currentTime is buffered\n media.currentTime -= 0.0001;\n }\n if (!this.previouslyPaused) {\n media.play();\n }\n }\n }\n\n nextLevelSwitch() {\n /* try to switch ASAP without breaking video playback :\n in order to ensure smooth but quick level switching,\n we need to find the next flushable buffer range\n we should take into account new segment fetch time\n */\n let media = this.media;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media && media.readyState) {\n let fetchdelay, fragPlayingCurrent, nextBufferedFrag;\n if (this.fragLoadIdx !== undefined) {\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n }\n fragPlayingCurrent = this.getBufferedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0,fragPlayingCurrent.startPTS - 1);\n }\n if (!media.paused) {\n // add a safety delay of 1s\n var nextLevelId = this.hls.nextLoadLevel,nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n //logger.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (nextBufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n var fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n // start flush position is the start PTS of next buffered frag.\n // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).\n // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment\n this.flushMainBuffer(nextBufferedFrag.maxStartPTS , Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n flushMainBuffer(startOffset,endOffset) {\n this.state = State.BUFFER_FLUSHING;\n let flushScope = {startOffset: startOffset, endOffset: endOffset};\n // if alternate audio tracks are used, only flush video, otherwise flush everything\n if (this.altAudio) {\n flushScope.type = 'video';\n }\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached(data) {\n var media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('seeked', this.onvseeked);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if(this.levels && config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n }\n\n onMediaDetaching() {\n var media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery\n var levels = this.levels;\n if (levels) {\n // reset fragment load counter\n levels.forEach(level => {\n if(level.details) {\n level.details.fragments.forEach(fragment => {\n fragment.loadCounter = undefined;\n fragment.backtracked = undefined;\n });\n }\n });\n }\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('seeked', this.onvseeked);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onMediaSeeking() {\n let media = this.media, currentTime = media ? media.currentTime : undefined, config = this.config;\n if (!isNaN(currentTime)) {\n logger.log(`media seeking to ${currentTime.toFixed(3)}`);\n }\n let mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n let bufferInfo = BufferHelper.bufferInfo(mediaBuffer,currentTime,this.config.maxBufferHole);\n if (this.state === State.FRAG_LOADING) {\n let fragCurrent = this.fragCurrent;\n // check if we are seeking to a unbuffered area AND if frag loading is in progress\n if (bufferInfo.len === 0 && fragCurrent) {\n let tolerance = config.maxFragLookUpTolerance,\n fragStartOffset = fragCurrent.start - tolerance,\n fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;\n // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything\n if (currentTime < fragStartOffset || currentTime > fragEndOffset) {\n if (fragCurrent.loader) {\n logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n } else {\n logger.log('seeking outside of buffer but within currently loaded fragment range');\n }\n }\n } else if (this.state === State.ENDED) {\n // if seeking to unbuffered area, clean up fragPrevious\n if (bufferInfo.len === 0) {\n this.fragPrevious = 0;\n }\n // switch to IDLE state to check for potential new fragment\n this.state = State.IDLE;\n }\n if (media) {\n this.lastCurrentTime = currentTime;\n }\n // avoid reporting fragment loop loading error in case user is seeking several times on same position\n if (this.state !== State.FRAG_LOADING && this.fragLoadIdx !== undefined) {\n this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;\n }\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if(!this.loadedmetadata) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n // tick to speed up processing\n this.tick();\n }\n\n onMediaSeeked() {\n const media = this.media, currentTime = media ? media.currentTime : undefined;\n if (!isNaN(currentTime)) {\n logger.log(`media seeked to ${currentTime.toFixed(3)}`);\n }\n // tick to speed up FRAGMENT_PLAYING triggering\n this.tick();\n }\n\n onMediaEnded() {\n logger.log('media ended');\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n\n onManifestLoading() {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this._bufferedFrags = [];\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed(data) {\n var aac = false, heaac = false, codec;\n data.levels.forEach(level => {\n // detect if we have different kind of audio codecs used amongst playlists\n codec = level.audioCodec;\n if (codec) {\n if (codec.indexOf('mp4a.40.2') !== -1) {\n aac = true;\n }\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = (aac && heaac);\n if (this.audioCodecSwitch) {\n logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');\n }\n this.levels = data.levels;\n this.startFragRequested = false;\n let config = this.config;\n if (config.autoStartLoad || this.forceStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n }\n\n onLevelLoaded(data) {\n const newDetails = data.details;\n const newLevelId = data.level;\n const lastLevel = this.levels[this.levelLastLoaded];\n const curLevel = this.levels[newLevelId];\n const duration = newDetails.totalduration;\n let sliding = 0;\n\n logger.log(`level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live) {\n var curDetails = curLevel.details;\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails,newDetails);\n sliding = newDetails.fragments[0].start;\n this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown && !isNaN(sliding)) {\n logger.log(`live playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live playlist - outdated PTS, unknown sliding');\n alignDiscontinuities(this.fragPrevious, lastLevel, newDetails);\n }\n } else {\n logger.log('live playlist - first load, unknown sliding');\n newDetails.PTSKnown = false;\n alignDiscontinuities(this.fragPrevious, lastLevel, newDetails);\n }\n } else {\n newDetails.PTSKnown = false;\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = newLevelId;\n this.hls.trigger(Event.LEVEL_UPDATED, { details: newDetails, level: newLevelId });\n\n if (this.startFragRequested === false) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1 || this.lastCurrentTime === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if(!isNaN(startTimeOffset)) {\n if (startTimeOffset < 0) {\n logger.log(`negative start time offset ${startTimeOffset}, count from end of last fragment`);\n startTimeOffset = sliding + duration + startTimeOffset;\n }\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)\n if (newDetails.live) {\n this.startPosition = this.computeLivePosition(sliding, newDetails);\n logger.log(`configure startPosition to ${this.startPosition}`);\n } else {\n this.startPosition = 0;\n }\n }\n this.lastCurrentTime = this.startPosition;\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n //trigger handler right now\n this.tick();\n }\n\n onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded(data) {\n var fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'main' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n let stats = data.stats,\n currentLevel = this.levels[fragCurrent.level],\n details = currentLevel.details;\n logger.log(`Loaded ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}`);\n // reset frag bitrate test in any case after frag loaded event\n this.bitrateTest = false;\n this.stats = stats;\n // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0\n // then this means that we should be able to load a fragment at a higher quality level\n if (fragLoaded.bitrateTest === true && this.hls.nextLoadLevel) {\n // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo\n this.state = State.IDLE;\n this.startFragRequested = false;\n stats.tparsed = stats.tbuffered = performance.now();\n this.hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: fragCurrent, id : 'main'});\n this.tick();\n } else if (fragLoaded.sn === 'initSegment') {\n this.state = State.IDLE;\n stats.tparsed = stats.tbuffered = performance.now();\n details.initSegment.data = data.payload;\n this.hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: fragCurrent, id : 'main'});\n this.tick();\n } else {\n this.state = State.PARSING;\n // transmux the MPEG-TS data to ISO-BMFF segments\n let duration = details.totalduration,\n level = fragCurrent.level,\n sn = fragCurrent.sn,\n audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if(this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if(audioCodec === undefined) {\n audioCodec = this.lastAudioCodec;\n }\n if(audioCodec) {\n if(audioCodec.indexOf('mp4a.40.5') !==-1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n }\n this.pendingBuffering = true;\n this.appended = false;\n logger.log(`Parsing ${sn} of [${details.startSN} ,${details.endSN}],level ${level}, cc ${fragCurrent.cc}`);\n let demuxer = this.demuxer;\n if (!demuxer) {\n demuxer = this.demuxer = new Demuxer(this.hls,'main');\n }\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)\n let media = this.media;\n let mediaSeeking = media && media.seeking;\n let accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);\n let initSegmentData = details.initSegment ? details.initSegment.data : [];\n demuxer.push(data.payload, initSegmentData,audioCodec, currentLevel.videoCodec, fragCurrent, duration, accurateTimeOffset,undefined);\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n var tracks = data.tracks, trackName, track;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (tracks.audio && this.altAudio) {\n delete tracks.audio;\n }\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if(track) {\n var audioCodec = this.levels[this.level].audioCodec,\n ua = navigator.userAgent.toLowerCase();\n if(audioCodec && this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if(audioCodec.indexOf('mp4a.40.5') !==-1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // in case AAC and HE-AAC audio codecs are signalled in manifest\n // force HE-AAC , as it seems that most browsers prefers that way,\n // except for mono streams OR on FF\n // these conditions might need to be reviewed ...\n if (this.audioCodecSwitch) {\n // don't force HE-AAC if mono stream\n if(track.metadata.channelCount !== 1 &&\n // don't force HE-AAC if firefox\n ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if(ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n logger.log(`Android: force audio codec to ${audioCodec}`);\n }\n track.levelCodec = audioCodec;\n track.id = data.id;\n }\n track = tracks.video;\n if(track) {\n track.levelCodec = this.levels[this.level].videoCodec;\n track.id = data.id;\n }\n this.hls.trigger(Event.BUFFER_CODECS,tracks);\n // loop through tracks that are going to be provided to bufferController\n for (trackName in tracks) {\n track = tracks[trackName];\n logger.log(`main track:${trackName},container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n var initSegment = track.initSegment;\n if (initSegment) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, {type: trackName, data: initSegment, parent : 'main', content : 'initSegment'});\n }\n }\n //trigger handler right now\n this.tick();\n }\n }\n\n onFragParsingData(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller\n this.state === State.PARSING) {\n var level = this.levels[this.level],\n frag = fragCurrent;\n if (isNaN(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n logger.log(`Parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb},dropped:${data.dropped || 0}`);\n\n // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)\n if(data.type === 'video') {\n frag.dropped = data.dropped;\n if (frag.dropped) {\n if (!frag.backtracked) {\n const levelDetails = level.details;\n if (levelDetails && frag.sn === levelDetails.startSN) {\n logger.warn('missing video frame(s) on first frag, appending with gap');\n } else {\n logger.warn('missing video frame(s), backtracking fragment');\n // Return back to the IDLE state without appending to buffer\n // Causes findFragments to backtrack a segment and find the keyframe\n // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment\n frag.backtracked = true;\n this.nextLoadPosition = data.startPTS;\n this.state = State.IDLE;\n this.fragPrevious = frag;\n this.tick();\n return;\n }\n } else {\n logger.warn('Already backtracked on this fragment, appending with the gap');\n }\n } else {\n // Only reset the backtracked flag if we've loaded the frag without any dropped frames\n frag.backtracked = false;\n }\n }\n\n var drift = LevelHelper.updateFragPTSDTS(level.details,frag,data.startPTS,data.endPTS,data.startDTS,data.endDTS),\n hls = this.hls;\n hls.trigger(Event.LEVEL_PTS_UPDATED, {details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS});\n\n // has remuxer dropped video frames located before first keyframe ?\n [data.data1, data.data2].forEach(buffer => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (buffer && buffer.length && this.state === State.PARSING) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n hls.trigger(Event.BUFFER_APPENDING, {type: data.type, data: buffer, parent : 'main',content : 'data'});\n }\n });\n //trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onAudioTrackSwitching(data) {\n // if any URL found on new audio track, it is an alternate audio track\n var altAudio = !!data.url,\n trackId = data.id;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n logger.log(`switching on main audio, use media.buffered to schedule main fragment loading`);\n this.mediaBuffer = this.media;\n let fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent.loader) {\n logger.log('switching to main audio track, cancel main fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // destroy demuxer to force init segment generation (following audio switch)\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n }\n let hls = this.hls;\n // switching to main audio, flush all audio and trigger track switched\n hls.trigger(Event.BUFFER_FLUSHING, {startOffset: 0 , endOffset: Number.POSITIVE_INFINITY, type : 'audio'});\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {id : trackId});\n this.altAudio = false;\n }\n }\n\n onAudioTrackSwitched(data) {\n var trackId = data.id,\n altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n let videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n logger.log(`switching on alternate audio, use video.buffered to schedule main fragment loading`);\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n\n\n onBufferCreated(data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for(var type in tracks) {\n let track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n this.videoBuffer = tracks[type].buffer;\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n logger.log(`alternate track found, use ${name}.buffered to schedule main fragment loading`);\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n onBufferAppended(data) {\n if (data.parent === 'main') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed() {\n //trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n const frag = this.fragCurrent;\n if (frag) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`main buffered : ${TimeRanges.toString(media.buffered)}`);\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n let bufferedFrags = this._bufferedFrags.filter(frag => {return BufferHelper.isBuffered(media,(frag.startPTS + frag.endPTS) / 2);});\n // push new range\n bufferedFrags.push(frag);\n // sort frags, as we use BinarySearch for lookup in getBufferedFrag ...\n this._bufferedFrags = bufferedFrags.sort(function(a,b) {return (a.startPTS - b.startPTS);});\n this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = performance.now();\n // we should get rid of this.fragLastKbps\n this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));\n this.hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: frag, id : 'main'});\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError(data) {\n let frag = data.frag || this.fragCurrent;\n // don't handle frag error not related to main fragment\n if (frag && frag.type !== 'main') {\n return;\n }\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n let mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);\n\n switch(data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n if (!data.fatal) {\n // keep retrying until the limit will be reached\n if ((this.fragLoadError + 1) <= this.config.fragLoadingMaxRetry) {\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n let delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);\n // reset load counter to avoid frag loop loading error\n frag.loadCounter = 0;\n logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = performance.now() + delay;\n // retry loading state\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.fragLoadError++;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`mediaController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.FRAG_LOOP_LOADING_ERROR:\n if(!data.fatal) {\n // if buffer is not empty\n if (mediaBuffered) {\n // try to reduce max buffer length : rationale is that we could get\n // frag loop loading error because of buffer eviction\n this._reduceMaxBufferLength(frag.duration);\n this.state = State.IDLE;\n } else {\n // buffer empty. report as fatal if in manual mode or if lowest level.\n // level controller takes care of emergency switch down logic\n if (!frag.autoLevel || frag.level === 0) {\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n }\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if(this.state !== State.ERROR) {\n if (data.fatal) {\n // if fatal error, stop processing\n this.state = State.ERROR;\n logger.warn(`streamController: ${data.details},switch to ${this.state} state ...`);\n } else {\n // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE\n if (!data.levelRetry && this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n }\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n this._reduceMaxBufferLength(this.config.maxBufferLength);\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole buffer to recover\n logger.warn('buffer full error also media.currentTime is not buffered, flush everything');\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0,Number.POSITIVE_INFINITY);\n }\n }\n break;\n default:\n break;\n }\n }\n\n _reduceMaxBufferLength(minLength) {\n let config = this.config;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength/=2;\n logger.warn(`main:reduce max buffer length to ${config.maxMaxBufferLength}s`);\n if (this.fragLoadIdx !== undefined) {\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;\n }\n }\n }\n\n_checkBuffer() {\n var media = this.media,\n config = this.config;\n // if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek\n if(media && media.readyState) {\n let currentTime = media.currentTime,\n mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media,\n buffered = mediaBuffer.buffered;\n // adjust currentTime to start position on loaded metadata\n if(!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n let startPosition = media.seeking ? currentTime : this.startPosition,\n startPositionBuffered = BufferHelper.isBuffered(mediaBuffer,startPosition),\n firstbufferedPosition = buffered.start(0),\n startNotBufferedButClose = !startPositionBuffered && (Math.abs(startPosition-firstbufferedPosition) < config.maxSeekHole);\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition || startNotBufferedButClose) {\n logger.log(`target start position:${startPosition}`);\n // if startPosition not buffered, let's seek to buffered.start(0)\n if(startNotBufferedButClose) {\n startPosition = firstbufferedPosition;\n logger.log(`target start position not buffered, seek to buffered.start(0) ${startPosition}`);\n }\n logger.log(`adjust currentTime from ${currentTime} to ${startPosition}`);\n media.currentTime = startPosition;\n }\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n let bufferInfo = BufferHelper.bufferInfo(media,currentTime,0),\n expectedPlaying = !(media.paused || // not playing when media is paused\n media.ended || // not playing when media is ended\n media.buffered.length === 0), // not playing if nothing buffered\n jumpThreshold = 0.5, // tolerance needed as some browsers stalls playback before reaching buffered range end\n playheadMoving = currentTime !== this.lastCurrentTime;\n\n if (playheadMoving) {\n // played moving, but was previously stalled => now not stuck anymore\n if (this.stallReported) {\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(performance.now()-this.stalled)}ms`);\n this.stallReported = false;\n }\n this.stalled = undefined;\n this.nudgeRetry = 0;\n } else {\n // playhead not moving\n if(expectedPlaying) {\n // playhead not moving BUT media expected to play\n const tnow = performance.now();\n const hls = this.hls;\n if(!this.stalled) {\n // stall just detected, store current time\n this.stalled = tnow;\n this.stallReported = false;\n } else {\n // playback already stalled, check stalling duration\n // if stalling for more than a given threshold, let's try to recover\n const stalledDuration = tnow - this.stalled;\n const bufferLen = bufferInfo.len;\n let nudgeRetry = this.nudgeRetry || 0;\n // have we reached stall deadline ?\n if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) {\n // report stalled error once\n if (!this.stallReported) {\n this.stallReported = true;\n logger.warn(`playback stalling in low buffer @${currentTime}`);\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer : bufferLen});\n }\n // if buffer len is below threshold, try to jump to start of next buffer range if close\n // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)\n var nextBufferStart = bufferInfo.nextStart, delta = nextBufferStart-currentTime;\n if(nextBufferStart &&\n (delta < config.maxSeekHole) &&\n (delta > 0)) {\n this.nudgeRetry = ++nudgeRetry;\n const nudgeOffset = nudgeRetry * config.nudgeOffset;\n // next buffer is close ! adjust currentTime to nextBufferStart\n // this will ensure effective video decoding\n logger.log(`adjust currentTime from ${media.currentTime} to next buffered @ ${nextBufferStart} + nudge ${nudgeOffset}`);\n media.currentTime = nextBufferStart + nudgeOffset;\n // reset stalled so to rearm watchdog timer\n this.stalled = undefined;\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole : nextBufferStart + nudgeOffset - currentTime});\n }\n } else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // report stalled error once\n if (!this.stallReported) {\n this.stallReported = true;\n logger.warn(`playback stalling in high buffer @${currentTime}`);\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer : bufferLen});\n }\n // reset stalled so to rearm watchdog timer\n this.stalled = undefined;\n this.nudgeRetry = ++nudgeRetry;\n if (nudgeRetry < config.nudgeMaxRetry) {\n const currentTime = media.currentTime;\n const targetTime = currentTime + nudgeRetry * config.nudgeOffset;\n logger.log(`adjust currentTime from ${currentTime} to ${targetTime}`);\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n media.currentTime = targetTime;\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_NUDGE_ON_STALL, fatal: false});\n } else {\n logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, raise fatal error`);\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: true});\n }\n }\n }\n }\n }\n }\n }\n }\n\n onFragLoadEmergencyAborted() {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if(!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.tick();\n }\n\n onBufferFlushed() {\n /* after successful buffer flushing, filter flushed fragments from bufferedFrags\n use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)\n */\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n this._bufferedFrags = this._bufferedFrags.filter(frag => {return BufferHelper.isBuffered(media,(frag.startPTS + frag.endPTS) / 2);});\n\n if (this.fragLoadIdx !== undefined) {\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n }\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n }\n\n swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n\n computeLivePosition(sliding, levelDetails) {\n let targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;\n return sliding + Math.max(0, levelDetails.totalduration - targetLatency);\n }\n\n get liveSyncPosition() {\n return this._liveSyncPosition;\n }\n\n set liveSyncPosition(value) {\n this._liveSyncPosition = value;\n }\n}\nexport default StreamController;\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/stream-controller.js","/*\n * Level Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {isCodecSupportedInMp4} from '../utils/codecs';\n\nclass LevelController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.FRAG_LOADED,\n Event.ERROR);\n this._manualLevel = -1;\n this.timer = null;\n }\n\n destroy() {\n this.cleanTimer();\n this._manualLevel = -1;\n }\n\n cleanTimer() {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n startLoad() {\n let levels = this._levels;\n\n this.canload = true;\n this.levelRetryCount = 0;\n\n // clean up live level details to force reload them, and reset load errors\n if(levels) {\n levels.forEach(level => {\n level.loadError = 0;\n const levelDetails = level.details;\n if (levelDetails && levelDetails.live) {\n level.details = undefined;\n }\n });\n }\n // speed up live playlist refresh if timer exists\n if (this.timer) {\n this.tick();\n }\n }\n\n stopLoad() {\n this.canload = false;\n }\n\n onManifestLoaded(data) {\n let levels = [];\n let bitrateStart;\n let levelSet = {};\n let levelFromSet = null;\n let videoCodecFound = false;\n let audioCodecFound = false;\n let chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());\n let audioTracks = [];\n\n // regroup redundant levels together\n data.levels.forEach(level => {\n level.loadError = 0;\n level.fragmentError = false;\n\n videoCodecFound = videoCodecFound || !!level.videoCodec;\n audioCodecFound = audioCodecFound || !!level.audioCodec || !!(level.attrs && level.attrs.AUDIO);\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n if (chromeOrFirefox === true && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate];\n\n if (levelFromSet === undefined) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] =level;\n levels.push(level);\n }\n else {\n levelFromSet.url.push( level .url);\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound === true && audioCodecFound === true) {\n levels = levels.filter(({videoCodec}) => !!videoCodec);\n }\n\n // only keep levels with supported audio/video codecs\n levels = levels.filter(({audioCodec, videoCodec}) => {\n return (!audioCodec || isCodecSupportedInMp4(audioCodec)) && (!videoCodec || isCodecSupportedInMp4(videoCodec));\n });\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(track => !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio'));\n }\n\n if(levels.length) {\n // start bitrate is the first bitrate of the manifest\n bitrateStart = levels[0].bitrate;\n // sort level on bitrate\n levels.sort(function (a, b) {\n return a.bitrate - b.bitrate;\n });\n this._levels = levels;\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n logger.log(`manifest loaded,${levels.length} level(s) found, first bitrate:${bitrateStart}`);\n break;\n }\n }\n this.hls.trigger(Event.MANIFEST_PARSED, {levels, audioTracks, firstLevel: this._firstLevel, stats: data.stats, audio : audioCodecFound, video : videoCodecFound, altAudio : audioTracks.length > 0});\n } else {\n this.hls.trigger(Event.ERROR, {\n type : ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal : true,\n url : this.hls.url,\n reason : 'no level with compatible codecs found in manifest'\n });\n }\n }\n\n get levels() {\n return this._levels;\n }\n\n get level() {\n return this._level;\n }\n\n set level(newLevel) {\n let levels = this._levels;\n if (levels) {\n newLevel = Math.min(newLevel, levels.length-1);\n if (this._level !== newLevel || levels[newLevel].details === undefined) {\n this.setLevelInternal(newLevel);\n }\n }\n }\n\n setLevelInternal(newLevel) {\n const levels = this._levels;\n const hls = this.hls;\n // check if level idx is valid\n if (newLevel >= 0 && newLevel < levels.length) {\n // stopping live reloading timer if any\n this.cleanTimer();\n if (this._level !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this._level = newLevel;\n var levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n // LEVEL_SWITCH to be deprecated in next major release\n hls.trigger(Event.LEVEL_SWITCH, levelProperties);\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n var level = levels[newLevel], levelDetails = level.details;\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live === true) {\n // level not retrieved yet, or live playlist we need to (re)load it\n var urlId = level.urlId;\n hls.trigger(Event.LEVEL_LOADING, {url: level.url[urlId], level: newLevel, id: urlId});\n }\n } else {\n // invalid level id given, trigger error\n hls.trigger(Event.ERROR, {type : ErrorTypes.OTHER_ERROR, details: ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx'});\n }\n }\n\n get manualLevel() {\n return this._manualLevel;\n }\n\n set manualLevel(newLevel) {\n this._manualLevel = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel() {\n return this._firstLevel;\n }\n\n set firstLevel(newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel() {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel(newLevel) {\n this._startLevel = newLevel;\n }\n\n onError(data) {\n if (data.fatal === true) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.cleanTimer();\n }\n return;\n }\n\n let details = data.details, levelError = false, fragmentError = false;\n let levelIndex, level;\n let {config} = this.hls;\n\n // try to recover not fatal errors\n switch (details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.FRAG_LOOP_LOADING_ERROR:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n levelIndex = data.frag.level;\n fragmentError = true;\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n levelIndex = data.context.level;\n levelError = true;\n break;\n case ErrorDetails.REMUX_ALLOC_ERROR:\n levelIndex = data.level;\n break;\n }\n /* try to switch to a redundant stream if any available.\n * if no redundant stream available, emergency switch down (if in auto mode and current level not 0)\n * otherwise, we cannot recover this network error ...\n */\n if (levelIndex !== undefined) {\n level = this._levels[levelIndex];\n level.loadError++;\n level.fragmentError = fragmentError;\n\n // Allow fragment retry as long as configuration allows.\n // Since fragment retry logic could depend on the levels, we should not enforce retry limits when there is an issue with fragments\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n if (fragmentError === true){\n // if any redundant streams available and if we haven't try them all (level.loadError is reseted on successful frag/level load.\n // if level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n const redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n logger.warn(`level controller,${details} for level ${levelIndex}: switching to redundant stream id ${level.urlId}`);\n } else {\n // we could try to recover if in auto mode and current level not lowest level (0)\n if ((this._manualLevel === -1) && levelIndex !== 0) {\n logger.warn(`level controller,${details}: switch-down for next fragment`);\n this.hls.nextAutoLevel = levelIndex - 1;\n } else {\n logger.warn(`level controller, ${details}: reload a fragment`);\n // reset this._level so that another call to set level() will trigger again a frag load\n this._level = undefined;\n }\n }\n } else if (levelError === true){\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n const delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // reset load counter to avoid frag loop loading error\n this.timer = setTimeout(() => this.tick(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n data.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller,${details}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`cannot recover ${details} error`);\n this._level = undefined;\n // stopping live reloading timer if any\n this.cleanTimer();\n // switch error to fatal\n data.fatal = true;\n }\n }\n }\n }\n\n // reset errors on the successful load of a fragment\n onFragLoaded({frag}) {\n if (frag !== undefined && frag.type === 'main') {\n const level = this._levels[frag.level];\n if (level !== undefined) {\n level.fragmentError = false;\n level.loadError = 0;\n this.levelRetryCount = 0;\n }\n }\n }\n\n onLevelLoaded(data) {\n const levelId = data.level;\n // only process level loaded events matching with expected level\n if (levelId === this._level) {\n let curLevel = this._levels[levelId];\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if(curLevel.fragmentError === false){\n curLevel.loadError = 0;\n this.levelRetryCount = 0;\n }\n let newDetails = data.details;\n // if current playlist is a live playlist, arm a timer to reload it\n if (newDetails.live) {\n let reloadInterval = 1000 * ( newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration),\n curDetails = curLevel.details;\n if (curDetails && newDetails.endSN === curDetails.endSN) {\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval /= 2;\n logger.log(`same live playlist, reload twice faster`);\n }\n // decrement reloadInterval with level loading delay\n reloadInterval -= performance.now() - data.stats.trequest;\n // in any case, don't reload more than every second\n reloadInterval = Math.max(1000, Math.round(reloadInterval));\n logger.log(`live playlist, reload in ${reloadInterval} ms`);\n this.timer = setTimeout(() => this.tick(), reloadInterval);\n } else {\n this.cleanTimer();\n }\n }\n }\n\n tick() {\n var levelId = this._level;\n if (levelId !== undefined && this.canload) {\n var level = this._levels[levelId];\n if (level && level.url) {\n var urlId = level.urlId;\n this.hls.trigger(Event.LEVEL_LOADING, {url: level.url[urlId], level: levelId, id: urlId});\n }\n }\n }\n\n get nextLoadLevel() {\n if (this._manualLevel !== -1) {\n return this._manualLevel;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel(nextLevel) {\n this.level = nextLevel;\n if (this._manualLevel === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n}\n\nexport default LevelController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/level-controller.js","/*\n * id3 metadata track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport ID3 from '../demux/id3';\n\nclass ID3TrackController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_METADATA);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Add ID3 metatadata text track.\n onMediaAttached(data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n }\n\n onMediaDetaching() {\n this.media = undefined;\n }\n\n onFragParsingMetadata(data) {\n const fragment = data.frag;\n const samples = data.samples;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.media.addTextTrack('metadata', 'id3');\n this.id3Track.mode = 'hidden';\n }\n\n // Attempt to recreate Safari functionality by creating\n // WebKitDataCue objects when available and store the decoded\n // ID3 data in the value property of the cue\n let Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;\n\n for (let i = 0; i < samples.length; i++) {\n const frames = ID3.getID3Frames(samples[i].data);\n if (frames) {\n const startTime = samples[i].pts;\n let endTime = i < samples.length - 1 ? samples[i+1].pts : fragment.endPTS;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n\n for(let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!ID3.isTimeStampFrame(frame)) {\n const cue = new Cue(startTime, endTime, '');\n cue.value = frame;\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n}\n\nexport default ID3TrackController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/id3-track-controller.js","/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor(halfLife) {\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = 0;\n this.totalWeight_ = 0;\n }\n\n sample(weight,value) {\n var adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n\n getTotalWeight() {\n return this.totalWeight_;\n }\n\n getEstimate() {\n if (this.alpha_) {\n var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n return this.estimate_ / zeroFactor;\n } else {\n return this.estimate_;\n }\n }\n}\n\nexport default EWMA;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/ewma.js","/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nimport EWMA from '../utils/ewma';\n\n\nclass EwmaBandWidthEstimator {\n\n constructor(hls,slow,fast,defaultEstimate) {\n this.hls = hls;\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n }\n\n sample(durationMs,numBytes) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n var bandwidth = 8000* numBytes / durationMs,\n //console.log('instant bw:'+ Math.round(bandwidth));\n // we weight sample using loading duration....\n weight = durationMs / 1000;\n this.fast_.sample(weight,bandwidth);\n this.slow_.sample(weight,bandwidth);\n }\n\n canEstimate() {\n let fast = this.fast_;\n return (fast && fast.getTotalWeight() >= this.minWeight_);\n }\n\n\n getEstimate() {\n if (this.canEstimate()) {\n //console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n //console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(),this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n\n destroy() {\n }\n}\nexport default EwmaBandWidthEstimator;\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/ewma-bandwidth-estimator.js","/*\n * simple ABR Controller\n * - compute next level based on last fragment bw heuristics\n * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport BufferHelper from '../helper/buffer-helper';\nimport {ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\nimport EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\n\nclass AbrController extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.FRAG_LOADING,\n Event.FRAG_LOADED,\n Event.FRAG_BUFFERED,\n Event.ERROR);\n this.lastLoadedFragLevel = 0;\n this._nextAutoLevel = -1;\n this.hls = hls;\n this.timer = null;\n this._bwEstimator = null;\n this.onCheck = this._abandonRulesCheck.bind(this);\n }\n\n destroy() {\n this.clearTimer();\n EventHandler.prototype.destroy.call(this);\n }\n\n onFragLoading(data) {\n let frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.timer = setInterval(this.onCheck, 100);\n }\n // lazy init of bw Estimator, rationale is that we use different params for Live/VoD\n // so we need to wait for stream manifest / playlist type to instantiate it.\n if (!this._bwEstimator) {\n let hls = this.hls,\n level = data.frag.level,\n isLive = hls.levels[level].details.live,\n config = hls.config,\n ewmaFast, ewmaSlow;\n\n if (isLive) {\n ewmaFast = config.abrEwmaFastLive;\n ewmaSlow = config.abrEwmaSlowLive;\n } else {\n ewmaFast = config.abrEwmaFastVoD;\n ewmaSlow = config.abrEwmaSlowVoD;\n }\n this._bwEstimator = new EwmaBandWidthEstimator(hls,ewmaSlow,ewmaFast,config.abrEwmaDefaultEstimate);\n }\n this.fragCurrent = frag;\n }\n }\n\n _abandonRulesCheck() {\n /*\n monitor fragment retrieval time...\n we compute expected time of arrival of the complete fragment.\n we compare it to expected time of buffer starvation\n */\n let hls = this.hls, v = hls.media,frag = this.fragCurrent, loader = frag.loader, minAutoLevel = hls.minAutoLevel;\n\n // if loader has been destroyed or loading has been aborted, stop timer and return\n if(!loader || ( loader.stats && loader.stats.aborted)) {\n logger.warn('frag loader destroy or aborted, disarm abandonRules');\n this.clearTimer();\n return;\n }\n let stats = loader.stats;\n /* only monitor frag retrieval time if\n (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */\n if (v && stats && ((!v.paused && (v.playbackRate !== 0)) || !v.readyState) && frag.autoLevel && frag.level) {\n let requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(v.playbackRate);\n // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate\n if (requestDelay > (500 * frag.duration / playbackRate)) {\n let levels = hls.levels,\n loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay), // byte/s; at least 1 byte/s to avoid division by zero\n // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size\n level = levels[frag.level],\n levelBitrate = level.realBitrate ? Math.max(level.realBitrate,level.bitrate) : level.bitrate,\n expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),\n pos = v.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (BufferHelper.bufferInfo(v,pos,hls.config.maxBufferHole).end - pos) / playbackRate;\n // consider emergency switch down only if we have less than 2 frag buffered AND\n // time to finish loading current fragment is bigger than buffer starvation delay\n // ie if we risk buffer starvation if bw does not increase quickly\n if ((bufferStarvationDelay < (2 * frag.duration / playbackRate)) && (fragLoadedDelay > bufferStarvationDelay)) {\n let fragLevelNextLoadedDelay, nextLoadLevel;\n // lets iterate through lower level and try to find the biggest one that could avoid rebuffering\n // we start from current level - 1 and we step down , until we find a matching level\n for (nextLoadLevel = frag.level - 1 ; nextLoadLevel > minAutoLevel ; nextLoadLevel--) {\n // compute time to load next fragment at lower level\n // 0.8 : consider only 80% of current bw to be conservative\n // 8 = bits per byte (bps/Bps)\n let levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate,levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;\n fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);\n if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n // we found a lower level that be rebuffering free with current estimated bw !\n break;\n }\n }\n // only emergency switch down if it takes less time to load new fragment at lowest level instead\n // of finishing loading current one ...\n if (fragLevelNextLoadedDelay < fragLoadedDelay) {\n logger.warn(`loading too slow, abort fragment loading and switch to level ${nextLoadLevel}:fragLoadedDelay[${nextLoadLevel}]<fragLoadedDelay[${frag.level-1}];bufferStarvationDelay:${fragLevelNextLoadedDelay.toFixed(1)}<${fragLoadedDelay.toFixed(1)}:${bufferStarvationDelay.toFixed(1)}`);\n // force next load level in auto mode\n hls.nextLoadLevel = nextLoadLevel;\n // update bw estimate for this fragment before cancelling load (this will help reducing the bw)\n this._bwEstimator.sample(requestDelay,stats.loaded);\n //abort fragment loading\n loader.abort();\n // stop abandon rules timer\n this.clearTimer();\n hls.trigger(Event.FRAG_LOAD_EMERGENCY_ABORTED, {frag: frag, stats: stats });\n }\n }\n }\n }\n }\n\n onFragLoaded(data) {\n let frag = data.frag;\n if (frag.type === 'main' && !isNaN(frag.sn)) {\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // store level id after successful fragment load\n this.lastLoadedFragLevel = frag.level;\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const level = this.hls.levels[frag.level];\n let loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;\n let loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;\n level.loaded = { bytes : loadedBytes, duration : loadedDuration };\n level.realBitrate = Math.round(8*loadedBytes/loadedDuration);\n }\n // if fragment has been loaded to perform a bitrate test,\n if (data.frag.bitrateTest) {\n let stats = data.stats;\n stats.tparsed = stats.tbuffered = stats.tload;\n this.onFragBuffered(data);\n }\n }\n }\n\n onFragBuffered(data) {\n var stats = data.stats, frag = data.frag;\n // only update stats on first frag buffering\n // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly\n // and leading to wrong bw estimation\n // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)\n if (stats.aborted !== true && frag.loadCounter === 1 && frag.type === 'main' && !isNaN(frag.sn) && ((!frag.bitrateTest || stats.tload === stats.tbuffered))) {\n // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached\n // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached\n // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation\n let fragLoadingProcessingMs = stats.tparsed - stats.trequest;\n logger.log(`latency/loading/parsing/append/kbps:${Math.round(stats.tfirst-stats.trequest)}/${Math.round(stats.tload-stats.tfirst)}/${Math.round(stats.tparsed-stats.tload)}/${Math.round(stats.tbuffered-stats.tparsed)}/${Math.round(8*stats.loaded/(stats.tbuffered-stats.trequest))}`);\n this._bwEstimator.sample(fragLoadingProcessingMs,stats.loaded);\n stats.bwEstimate = this._bwEstimator.getEstimate();\n // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration\n if (frag.bitrateTest) {\n this.bitrateTestDelay = fragLoadingProcessingMs/1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n }\n\n onError(data) {\n // stop timer in case of frag loading error\n switch(data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n this.clearTimer();\n break;\n default:\n break;\n }\n }\n\n clearTimer() {\n clearInterval(this.timer);\n this.timer = null;\n }\n\n // return next auto level\n get nextAutoLevel() {\n const forcedAutoLevel = this._nextAutoLevel;\n const bwEstimator = this._bwEstimator;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {\n return forcedAutoLevel;\n }\n // compute next level using ABR logic\n let nextABRAutoLevel = this._nextABRAutoLevel;\n // if forced auto level has been defined, use it to cap ABR computed quality level\n if (forcedAutoLevel !== -1) {\n nextABRAutoLevel = Math.min(forcedAutoLevel,nextABRAutoLevel);\n }\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel() {\n var hls = this.hls, maxAutoLevel = hls.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = hls.minAutoLevel;\n const v = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = (v ? v.currentTime : 0),\n // playbackRate is the absolute value of the playback rate; if v.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = ((v && (v.playbackRate !== 0)) ? Math.abs(v.playbackRate) : 1.0),\n avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n bufferStarvationDelay = (BufferHelper.bufferInfo(v, pos, config.maxBufferHole).end - pos) / playbackRate;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n let bestLevel = this._findBestLevel(currentLevel,currentFragDuration,avgbw,minAutoLevel,maxAutoLevel,bufferStarvationDelay,config.abrBandWidthFactor,config.abrBandWidthUpFactor,levels);\n if (bestLevel >= 0) {\n return bestLevel;\n } else {\n logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');\n // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n // if no matching level found, logic will return 0\n let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration,config.maxStarvationDelay) : config.maxStarvationDelay,\n bwFactor = config.abrBandWidthFactor,\n bwUpFactor = config.abrBandWidthUpFactor;\n if (bufferStarvationDelay === 0) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n let bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration,config.maxLoadingDelay) : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n logger.trace(`bitrate test took ${Math.round(1000*bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000*maxStarvationDelay)} ms`);\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n bestLevel = this._findBestLevel(currentLevel,currentFragDuration,avgbw,minAutoLevel,maxAutoLevel,bufferStarvationDelay+maxStarvationDelay,bwFactor,bwUpFactor,levels);\n return Math.max(bestLevel,0);\n }\n }\n\n _findBestLevel(currentLevel,currentFragDuration,currentBw,minAutoLevel,maxAutoLevel,maxFetchDuration,bwFactor,bwUpFactor,levels) {\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n let levelInfo = levels[i],\n levelDetails = levelInfo.details,\n avgDuration = levelDetails ? levelDetails.totalduration/levelDetails.fragments.length : currentFragDuration,\n live = levelDetails ? levelDetails.live : false,\n adjustedbw;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (i <= currentLevel) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n const bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate,levels[i].bitrate) : levels[i].bitrate,\n fetchDuration = bitrate * avgDuration / adjustedbw;\n\n logger.trace(`level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ${i}/${Math.round(adjustedbw)}/${bitrate}/${avgDuration}/${maxFetchDuration}/${fetchDuration}`);\n // if adjusted bw is greater than level bitrate AND\n if (adjustedbw > bitrate &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1\n (!fetchDuration || (live && !this.bitrateTestDelay) || fetchDuration < maxFetchDuration) ) {\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n set nextAutoLevel(nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n}\n\nexport default AbrController;\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/abr-controller.js","/*\n * Buffer Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {getMediaSource} from '../helper/mediasource-helper';\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHING,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_PARSED,\n Event.BUFFER_RESET,\n Event.BUFFER_APPENDING,\n Event.BUFFER_CODECS,\n Event.BUFFER_EOS,\n Event.BUFFER_FLUSHING,\n Event.LEVEL_PTS_UPDATED,\n Event.LEVEL_UPDATED);\n\n // the value that we have set mediasource.duration to\n // (the actual duration may be tweaked slighly by the browser)\n this._msDuration = null;\n // the value that we want to set mediaSource.duration to\n this._levelDuration = null;\n\n // Source Buffer listeners\n this.onsbue = this.onSBUpdateEnd.bind(this);\n this.onsbe = this.onSBUpdateError.bind(this);\n this.pendingTracks = {};\n this.tracks = {};\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n onLevelPtsUpdated(data) {\n let type = data.type;\n let audioTrack = this.tracks.audio;\n\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue\n // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`\n // event if SB is in updating state.\n // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n\n if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') { // Chrome audio mp3 track\n let audioBuffer = this.sourceBuffer.audio;\n let delta = Math.abs(audioBuffer.timestampOffset - data.start);\n\n // adjust timestamp offset if time delta is greater than 100ms\n if (delta > 0.1) {\n let updating = audioBuffer.updating;\n\n try {\n audioBuffer.abort();\n } catch (err) {\n updating = true;\n logger.warn('can not abort audio buffer: ' + err);\n }\n\n if (!updating) {\n logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);\n audioBuffer.timestampOffset = data.start;\n } else {\n this.audioTimestampOffset = data.start;\n }\n }\n }\n }\n\n onManifestParsed(data) {\n let audioExpected = data.audio,\n videoExpected = data.video || (data.levels.length && data.audio),\n sourceBufferNb = 0;\n // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n if (data.altAudio && (audioExpected || videoExpected)) {\n sourceBufferNb = (audioExpected ? 1 : 0) + (videoExpected ? 1 : 0);\n logger.log(`${sourceBufferNb} sourceBuffer(s) expected`);\n }\n this.sourceBufferNb = sourceBufferNb;\n }\n\n onMediaAttaching(data) {\n let media = this.media = data.media;\n if (media) {\n // setup the media source\n var ms = this.mediaSource = new MediaSource();\n //Media Source listeners\n this.onmso = this.onMediaSourceOpen.bind(this);\n this.onmse = this.onMediaSourceEnded.bind(this);\n this.onmsc = this.onMediaSourceClose.bind(this);\n ms.addEventListener('sourceopen', this.onmso);\n ms.addEventListener('sourceended', this.onmse);\n ms.addEventListener('sourceclose', this.onmsc);\n // link video and media Source\n media.src = URL.createObjectURL(ms);\n }\n }\n\n onMediaDetaching() {\n logger.log('media source detaching');\n var ms = this.mediaSource;\n if (ms) {\n if (ms.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n ms.endOfStream();\n } catch(err) {\n logger.warn(`onMediaDetaching:${err.message} while calling endOfStream`);\n }\n }\n ms.removeEventListener('sourceopen', this.onmso);\n ms.removeEventListener('sourceended', this.onmse);\n ms.removeEventListener('sourceclose', this.onmsc);\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (this.media) {\n URL.revokeObjectURL(this.media.src);\n this.media.removeAttribute('src');\n this.media.load();\n }\n\n this.mediaSource = null;\n this.media = null;\n this.pendingTracks = {};\n this.tracks = {};\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n this.onmso = this.onmse = this.onmsc = null;\n this.hls.trigger(Event.MEDIA_DETACHED);\n }\n\n onMediaSourceOpen() {\n logger.log('media source opened');\n this.hls.trigger(Event.MEDIA_ATTACHED, { media : this.media });\n let mediaSource = this.mediaSource;\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this.onmso);\n }\n this.checkPendingTracks();\n }\n\n checkPendingTracks() {\n // if any buffer codecs pending, check if we have enough to create sourceBuffers\n let pendingTracks = this.pendingTracks,\n pendingTracksNb = Object.keys(pendingTracks).length;\n // if any pending tracks and (if nb of pending tracks gt or equal than expected nb or if unknown expected nb)\n if (pendingTracksNb && (\n this.sourceBufferNb <= pendingTracksNb ||\n this.sourceBufferNb === 0)) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n this.doAppending();\n }\n }\n\n onMediaSourceClose() {\n logger.log('media source closed');\n }\n\n onMediaSourceEnded() {\n logger.log('media source ended');\n }\n\n\n onSBUpdateEnd() {\n // update timestampOffset\n if (this.audioTimestampOffset) {\n let audioBuffer = this.sourceBuffer.audio;\n logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);\n audioBuffer.timestampOffset = this.audioTimestampOffset;\n delete this.audioTimestampOffset;\n }\n\n if (this._needsFlush) {\n this.doFlush();\n }\n\n if (this._needsEos) {\n this.checkEos();\n }\n this.appending = false;\n let parent = this.parent;\n // count nb of pending segments waiting for appending on this sourcebuffer\n let pending = this.segments.reduce( (counter, segment) => (segment.parent === parent) ? counter + 1 : counter , 0);\n this.hls.trigger(Event.BUFFER_APPENDED, { parent : parent, pending : pending });\n\n // don't append in flushing mode\n if (!this._needsFlush) {\n this.doAppending();\n }\n\n this.updateMediaElementDuration();\n }\n\n onSBUpdateError(event) {\n logger.error('sourceBuffer error:', event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // this error might not always be fatal (it is fatal if decode error is set, in that case\n // it will be followed by a mediaElement error ...)\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false});\n // we don't need to do more than that, as accordin to the spec, updateend will be fired just after\n }\n\n onBufferReset() {\n var sourceBuffer = this.sourceBuffer;\n for(var type in sourceBuffer) {\n var sb = sourceBuffer[type];\n try {\n this.mediaSource.removeSourceBuffer(sb);\n sb.removeEventListener('updateend', this.onsbue);\n sb.removeEventListener('error', this.onsbe);\n } catch(err) {\n }\n }\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n onBufferCodecs(tracks) {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n // if sourcebuffers already created, do nothing ...\n if (Object.keys(this.sourceBuffer).length === 0) {\n for (var trackName in tracks) { this.pendingTracks[trackName] = tracks[trackName]; }\n let mediaSource = this.mediaSource;\n if (mediaSource && mediaSource.readyState === 'open') {\n // try to create sourcebuffers if mediasource opened\n this.checkPendingTracks();\n }\n }\n }\n\n\n createSourceBuffers(tracks) {\n var sourceBuffer = this.sourceBuffer,mediaSource = this.mediaSource;\n\n for (let trackName in tracks) {\n if(!sourceBuffer[trackName]) {\n let track = tracks[trackName];\n // use levelCodec as first priority\n let codec = track.levelCodec || track.codec;\n let mimeType = `${track.container};codecs=${codec}`;\n logger.log(`creating sourceBuffer(${mimeType})`);\n try {\n let sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);\n sb.addEventListener('updateend', this.onsbue);\n sb.addEventListener('error', this.onsbe);\n this.tracks[trackName] = {codec: codec, container: track.container};\n track.buffer = sb;\n } catch(err) {\n logger.error(`error while trying to add sourceBuffer:${err.message}`);\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType : mimeType});\n }\n }\n }\n this.hls.trigger(Event.BUFFER_CREATED, { tracks : tracks } );\n }\n\n onBufferAppending(data) {\n if (!this._needsFlush) {\n if (!this.segments) {\n this.segments = [ data ];\n } else {\n this.segments.push(data);\n }\n this.doAppending();\n }\n }\n\n onBufferAppendFail(data) {\n logger.error('sourceBuffer error:',data.event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // this error might not always be fatal (it is fatal if decode error is set, in that case\n // it will be followed by a mediaElement error ...)\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false});\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n onBufferEos(data) {\n var sb = this.sourceBuffer;\n let dataType = data.type;\n for(let type in sb) {\n if (!dataType || type === dataType) {\n if (!sb[type].ended) {\n sb[type].ended = true;\n logger.log(`${type} sourceBuffer now EOS`);\n }\n }\n }\n this.checkEos();\n }\n\n // if all source buffers are marked as ended, signal endOfStream() to MediaSource.\n checkEos() {\n var sb = this.sourceBuffer, mediaSource = this.mediaSource;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n for(let type in sb) {\n let sbobj = sb[type];\n if (!sbobj.ended) {\n return;\n }\n if(sbobj.updating) {\n this._needsEos = true;\n return;\n }\n }\n logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');\n //Notify the media element that it now has all of the media data\n try {\n mediaSource.endOfStream();\n } catch(e) {\n logger.warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n }\n\n\n onBufferFlushing(data) {\n this.flushRange.push({start: data.startOffset, end: data.endOffset, type : data.type});\n // attempt flush immediatly\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n onLevelUpdated(event) {\n let details = event.details;\n if (details.fragments.length === 0) {\n return;\n }\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this.updateMediaElementDuration();\n }\n\n // https://github.com/video-dev/hls.js/issues/355\n updateMediaElementDuration() {\n let media = this.media,\n mediaSource = this.mediaSource,\n sourceBuffer = this.sourceBuffer,\n levelDuration = this._levelDuration;\n if (levelDuration === null || !media || !mediaSource || !sourceBuffer || media.readyState === 0 || mediaSource.readyState !== 'open') {\n return;\n }\n for (let type in sourceBuffer) {\n if (sourceBuffer[type].updating) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n if (this._msDuration === null) {\n // initialise to the value that the media source is reporting\n this._msDuration = mediaSource.duration;\n }\n let duration = media.duration;\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update mediasource duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n if ((levelDuration > this._msDuration && levelDuration > duration) || (duration === Infinity || isNaN(duration) )) {\n logger.log(`Updating mediasource duration to ${levelDuration.toFixed(3)}`);\n this._msDuration = mediaSource.duration = levelDuration;\n }\n }\n\n doFlush() {\n // loop through all buffer ranges to flush\n while(this.flushRange.length) {\n var range = this.flushRange[0];\n // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer\n if (this.flushBuffer(range.start, range.end, range.type)) {\n // range flushed, remove from flush array\n this.flushRange.shift();\n this.flushBufferCounter = 0;\n } else {\n this._needsFlush = true;\n // avoid looping, wait for SB update end to retrigger a flush\n return;\n }\n }\n if (this.flushRange.length === 0) {\n // everything flushed\n this._needsFlush = false;\n\n // let's recompute this.appended, which is used to avoid flush looping\n var appended = 0;\n var sourceBuffer = this.sourceBuffer;\n try {\n for (var type in sourceBuffer) {\n appended += sourceBuffer[type].buffered.length;\n }\n } catch(error) {\n // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource\n // this is harmess at this stage, catch this to avoid reporting an internal exception\n logger.error('error while accessing sourceBuffer.buffered');\n }\n this.appended = appended;\n this.hls.trigger(Event.BUFFER_FLUSHED);\n }\n }\n\n doAppending() {\n var hls = this.hls, sourceBuffer = this.sourceBuffer, segments = this.segments;\n if (Object.keys(sourceBuffer).length) {\n if (this.media.error) {\n this.segments = [];\n logger.error('trying to append although a media error occured, flush segment and abort');\n return;\n }\n if (this.appending) {\n //logger.log(`sb appending in progress`);\n return;\n }\n if (segments && segments.length) {\n let segment = segments.shift();\n try {\n let type = segment.type, sb = sourceBuffer[type];\n if(sb) {\n if(!sb.updating) {\n // reset sourceBuffer ended flag before appending segment\n sb.ended = false;\n //logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);\n this.parent = segment.parent;\n sb.appendBuffer(segment.data);\n this.appendError = 0;\n this.appended++;\n this.appending = true;\n } else {\n segments.unshift(segment);\n }\n } else {\n // in case we don't have any source buffer matching with this segment type,\n // it means that Mediasource fails to create sourcebuffer\n // discard this segment, and trigger update end\n this.onSBUpdateEnd();\n }\n } catch(err) {\n // in case any error occured while appending, put back segment in segments table\n logger.error(`error while trying to append buffer:${err.message}`);\n segments.unshift(segment);\n var event = {type: ErrorTypes.MEDIA_ERROR, parent : segment.parent};\n if(err.code !== 22) {\n if (this.appendError) {\n this.appendError++;\n } else {\n this.appendError = 1;\n }\n event.details = ErrorDetails.BUFFER_APPEND_ERROR;\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. retrying help recovering this\n */\n if (this.appendError > hls.config.appendErrorMaxRetry) {\n logger.log(`fail ${hls.config.appendErrorMaxRetry} times to append segment in sourceBuffer`);\n segments = [];\n event.fatal = true;\n hls.trigger(Event.ERROR, event);\n return;\n } else {\n event.fatal = false;\n hls.trigger(Event.ERROR, event);\n }\n } else {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n this.segments = [];\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n event.fatal = false;\n hls.trigger(Event.ERROR,event);\n return;\n }\n }\n }\n }\n }\n\n /*\n flush specified buffered range,\n return true once range has been flushed.\n as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end\n */\n flushBuffer(startOffset, endOffset, typeIn) {\n var sb, i, bufStart, bufEnd, flushStart, flushEnd, sourceBuffer = this.sourceBuffer;\n if (Object.keys(sourceBuffer).length) {\n logger.log(`flushBuffer,pos/start/end: ${this.media.currentTime.toFixed(3)}/${startOffset}/${endOffset}`);\n // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments\n if (this.flushBufferCounter < this.appended) {\n for (var type in sourceBuffer) {\n // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one\n // if no, let's flush all sourcebuffers\n if (typeIn && type !== typeIn) {\n continue;\n }\n sb = sourceBuffer[type];\n // we are going to flush buffer, mark source buffer as 'not ended'\n sb.ended = false;\n if (!sb.updating) {\n try {\n for (i = 0; i < sb.buffered.length; i++) {\n bufStart = sb.buffered.start(i);\n bufEnd = sb.buffered.end(i);\n // workaround firefox not able to properly flush multiple buffered range.\n if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) {\n flushStart = startOffset;\n flushEnd = endOffset;\n } else {\n flushStart = Math.max(bufStart, startOffset);\n flushEnd = Math.min(bufEnd, endOffset);\n }\n /* sometimes sourcebuffer.remove() does not flush\n the exact expected time range.\n to avoid rounding issues/infinite loop,\n only flush buffer range of length greater than 500ms.\n */\n if (Math.min(flushEnd,bufEnd) - flushStart > 0.5 ) {\n this.flushBufferCounter++;\n logger.log(`flush ${type} [${flushStart},${flushEnd}], of [${bufStart},${bufEnd}], pos:${this.media.currentTime}`);\n sb.remove(flushStart, flushEnd);\n return false;\n }\n }\n } catch(e) {\n logger.warn('exception while accessing sourcebuffer, it might have been removed from MediaSource');\n }\n } else {\n //logger.log('abort ' + type + ' append in progress');\n // this will abort any appending in progress\n //sb.abort();\n logger.warn('cannot flush, sb updating in progress');\n return false;\n }\n }\n } else {\n logger.warn('abort flushing too many retries');\n }\n logger.log('buffer flushed');\n }\n // everything flushed !\n return true;\n }\n}\n\nexport default BufferController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/buffer-controller.js","/*\n * cap stream level to media size dimension controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\n\nclass CapLevelController extends EventHandler {\n\tconstructor(hls) {\n super(hls,\n Event.FPS_DROP_LEVEL_CAPPING,\n Event.MEDIA_ATTACHING,\n Event.MANIFEST_PARSED);\n\t}\n\n\tdestroy() {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = this.restrictedLevels = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n }\n }\n }\n\n onFpsDropLevelCapping(data) {\n\t // Don't add a restricted level more than once\n if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {\n this.restrictedLevels.push(data.droppedLevel);\n }\n }\n\n\tonMediaAttaching(data) {\n this.media = data.media instanceof HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed(data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n if (hls.config.capLevelToPlayerSize) {\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.levels = data.levels;\n hls.firstLevel = this.getMaxLevel(data.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n }\n\n detectPlayerSize() {\n if (this.media) {\n let levelsLength = this.levels ? this.levels.length : 0;\n if (levelsLength) {\n const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);\n if (hls.autoLevelCapping > this.autoLevelCapping) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n hls.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel(capLevelIndex) {\n if (!this.levels) {\n return -1;\n }\n\n const validLevels = this.levels.filter((level, index) =>\n CapLevelController.isLevelAllowed(index, this.restrictedLevels) && index <= capLevelIndex\n );\n\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n }\n\n get mediaWidth() {\n let width;\n const media = this.media;\n if (media) {\n width = media.width || media.clientWidth || media.offsetWidth;\n width *= CapLevelController.contentScaleFactor;\n }\n return width;\n }\n\n get mediaHeight() {\n let height;\n const media = this.media;\n if (media) {\n height = media.height || media.clientHeight || media.offsetHeight;\n height *= CapLevelController.contentScaleFactor;\n }\n return height;\n }\n\n static get contentScaleFactor() {\n let pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch(e) {}\n return pixelRatio;\n }\n\n static isLevelAllowed(level, restrictedLevels = []) {\n return restrictedLevels.indexOf(level) === -1;\n }\n\n static getMaxLevelByMediaSize(levels, width, height) {\n if (!levels || (levels && !levels.length)) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandiwdth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n\n for (let i = 0; i < levels.length; i+= 1) {\n const level = levels[i];\n if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/cap-level-controller.js","/*\n * FPS Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\n\nclass FPSController extends EventHandler{\n\n constructor(hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n this.isVideoPlaybackQualityAvailable = false;\n }\n\n onMediaAttaching(data) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const video = this.video = data.media instanceof HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n }\n }\n\n checkFPS(video, decodedFrames, droppedFrames) {\n let currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n let currentPeriod = currentTime - this.lastTime,\n currentDropped = droppedFrames - this.lastDroppedFrames,\n currentDecoded = decodedFrames - this.lastDecodedFrames,\n droppedFPS = 1000 * currentDropped / currentPeriod,\n hls = this.hls;\n hls.trigger(Event.FPS_DROP, {currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames});\n if (droppedFPS > 0) {\n //logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n let currentLevel = hls.currentLevel;\n logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);\n if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {\n currentLevel = currentLevel - 1;\n hls.trigger(Event.FPS_DROP_LEVEL_CAPPING, {level: currentLevel, droppedLevel: hls.currentLevel});\n hls.autoLevelCapping = currentLevel;\n hls.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval() {\n const video = this.video;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n let videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n } else {\n this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);\n }\n }\n }\n}\n\nexport default FPSController;\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fps-controller.js","/**\n * XHR based logger\n*/\n\nimport {logger} from '../utils/logger';\n\nclass XhrLoader {\n\n constructor(config) {\n if (config && config.xhrSetup) {\n this.xhrSetup = config.xhrSetup;\n }\n }\n\n destroy() {\n this.abort();\n this.loader = null;\n }\n\n abort() {\n var loader = this.loader;\n if (loader && loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n\n window.clearTimeout(this.requestTimeout);\n this.requestTimeout = null;\n window.clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n\n load(context, config, callbacks) {\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.stats = {trequest: performance.now(), retry: 0};\n this.retryDelay = config.retryDelay;\n this.loadInternal();\n }\n\n loadInternal() {\n var xhr, context = this.context;\n xhr = this.loader = new XMLHttpRequest();\n \n let stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n const xhrSetup = this.xhrSetup;\n\n try {\n if (xhrSetup) {\n try {\n xhrSetup(xhr, context.url);\n } catch (e) {\n // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n xhr.open('GET', context.url, true);\n xhrSetup(xhr, context.url);\n }\n }\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks.onError({ code : xhr.status, text: e.message }, context, xhr);\n return;\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader('Range','bytes=' + context.rangeStart + '-' + (context.rangeEnd-1));\n }\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType;\n\n // setup timeout before we perform request\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);\n xhr.send();\n }\n\n readystatechange(event) {\n var xhr = event.currentTarget,\n readyState = xhr.readyState,\n stats = this.stats,\n context = this.context,\n config = this.config;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >=2) {\n // clear xhr timeout and rearm it if readyState less than 4\n window.clearTimeout(this.requestTimeout);\n if (stats.tfirst === 0) {\n stats.tfirst = Math.max(performance.now(), stats.trequest);\n }\n if (readyState === 4) {\n let status = xhr.status;\n // http status between 200 to 299 are all successful\n if (status >= 200 && status < 300) {\n stats.tload = Math.max(stats.tfirst,performance.now());\n let data,len;\n if (context.responseType === 'arraybuffer') {\n data = xhr.response;\n len = data.byteLength;\n } else {\n data = xhr.responseText;\n len = data.length;\n }\n stats.loaded = stats.total = len;\n let response = { url : xhr.responseURL, data : data };\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n if (stats.retry >= config.maxRetry || (status >= 400 && status < 499)) {\n logger.error(`${status} while loading ${context.url}` );\n this.callbacks.onError({ code : status, text : xhr.statusText}, context, xhr);\n } else {\n // retry\n logger.warn(`${status} while loading ${context.url}, retrying in ${this.retryDelay}...`);\n // aborts and resets internal state\n this.destroy();\n // schedule retry\n this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);\n // set exponential backoff\n this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);\n stats.retry++;\n }\n }\n } else {\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);\n }\n }\n }\n\n loadtimeout() {\n logger.warn(`timeout while loading ${this.context.url}` );\n this.callbacks.onTimeout(this.stats, this.context, null);\n }\n\n loadprogress(event) {\n var xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n let onProgress = this.callbacks.onProgress;\n if (onProgress) {\n // third arg is to provide on progress data\n onProgress(stats, this.context, null, xhr);\n }\n }\n}\n\nexport default XhrLoader;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/xhr-loader.js","/*\n * audio track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\nimport {ErrorTypes} from '../errors';\n\nclass AudioTrackController extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.AUDIO_TRACK_LOADED,\n Event.ERROR);\n this.ticks = 0;\n this.ontick = this.tick.bind(this);\n }\n\n destroy() {\n this.cleanTimer();\n EventHandler.prototype.destroy.call(this);\n }\n\n cleanTimer() {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n tick() {\n this.ticks++;\n if (this.ticks === 1) {\n this.doTick();\n if (this.ticks > 1) {\n setTimeout(this.tick, 1);\n }\n this.ticks = 0;\n }\n }\n\n doTick() {\n this.updateTrack(this.trackId);\n }\n\n onError(data) {\n if(data.fatal && data.type === ErrorTypes.NETWORK_ERROR) {\n this.cleanTimer();\n }\n }\n\n onManifestLoading() {\n // reset audio tracks on manifest loading\n this.tracks = [];\n this.trackId = -1;\n }\n\n onManifestParsed(data) {\n let tracks = data.audioTracks || [];\n let defaultFound = false;\n this.tracks = tracks;\n this.hls.trigger(Event.AUDIO_TRACKS_UPDATED, {audioTracks : tracks});\n // loop through available audio tracks and autoselect default if needed\n let id = 0;\n tracks.forEach(track => {\n if(track.default && !defaultFound) {\n this.audioTrack = id;\n defaultFound = true;\n return;\n }\n id++;\n });\n if (defaultFound === false && tracks.length) {\n logger.log('no default audio track defined, use first audio track as default');\n this.audioTrack = 0;\n }\n }\n\n onAudioTrackLoaded(data) {\n if (data.id < this.tracks.length) {\n logger.log(`audioTrack ${data.id} loaded`);\n this.tracks[data.id].details = data.details;\n // check if current playlist is a live playlist\n if (data.details.live && !this.timer) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n this.timer = setInterval(this.ontick, 1000 * data.details.targetduration);\n }\n if (!data.details.live && this.timer) {\n // playlist is not live and timer is armed : stopping it\n this.cleanTimer();\n }\n }\n }\n\n /** get alternate audio tracks list from playlist **/\n get audioTracks() {\n return this.tracks;\n }\n\n /** get index of the selected audio track (index in audio track lists) **/\n get audioTrack() {\n return this.trackId;\n }\n\n /** select an audio track, based on its index in audio track lists**/\n set audioTrack(audioTrackId) {\n if (this.trackId !== audioTrackId || this.tracks[audioTrackId].details === undefined) {\n this.setAudioTrackInternal(audioTrackId);\n }\n }\n\n setAudioTrackInternal(newId) {\n // check if level idx is valid\n if (newId >= 0 && newId < this.tracks.length) {\n // stopping live reloading timer if any\n this.cleanTimer();\n this.trackId = newId;\n logger.log(`switching to audioTrack ${newId}`);\n let audioTrack = this.tracks[newId],\n hls = this.hls,\n type = audioTrack.type,\n url = audioTrack.url,\n eventObj = {id: newId, type : type, url : url};\n // keep AUDIO_TRACK_SWITCH for legacy reason\n hls.trigger(Event.AUDIO_TRACK_SWITCH, eventObj);\n hls.trigger(Event.AUDIO_TRACK_SWITCHING, eventObj);\n // check if we need to load playlist for this audio Track\n let details = audioTrack.details;\n if (url && (details === undefined || details.live === true)) {\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`(re)loading playlist for audioTrack ${newId}`);\n hls.trigger(Event.AUDIO_TRACK_LOADING, {url: url, id: newId});\n }\n }\n }\n\n updateTrack(newId) {\n // check if level idx is valid\n if (newId >= 0 && newId < this.tracks.length) {\n // stopping live reloading timer if any\n this.cleanTimer();\n this.trackId = newId;\n logger.log(`updating audioTrack ${newId}`);\n let audioTrack = this.tracks[newId], url = audioTrack.url;\n // check if we need to load playlist for this audio Track\n let details = audioTrack.details;\n if (url && (details === undefined || details.live === true)) {\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`(re)loading playlist for audioTrack ${newId}`);\n this.hls.trigger(Event.AUDIO_TRACK_LOADING, {url: url, id: newId});\n }\n }\n }\n}\n\nexport default AudioTrackController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/audio-track-controller.js","/*\n * Audio Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport BufferHelper from '../helper/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport * as LevelHelper from '../helper/level-helper';import TimeRanges from '../utils/timeRanges';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\nimport { findFragWithCC } from '../utils/discontinuities';\n\nconst State = {\n STOPPED : 'STOPPED',\n STARTING : 'STARTING',\n IDLE : 'IDLE',\n PAUSED : 'PAUSED',\n KEY_LOADING : 'KEY_LOADING',\n FRAG_LOADING : 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY : 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK : 'WAITING_TRACK',\n PARSING : 'PARSING',\n PARSED : 'PARSED',\n BUFFER_FLUSHING : 'BUFFER_FLUSHING',\n ENDED : 'ENDED',\n ERROR : 'ERROR',\n WAITING_INIT_PTS : 'WAITING_INIT_PTS'\n};\n\nclass AudioStreamController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.AUDIO_TRACKS_UPDATED,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED,\n Event.INIT_PTS_FOUND);\n\n this.config = hls.config;\n this.audioCodecSwap = false;\n this.ticks = 0;\n this._state = State.STOPPED;\n this.ontick = this.tick.bind(this);\n this.initPTS=[];\n this.waitingFragment=null;\n this.videoTrackCC = null;\n }\n\n destroy() {\n this.stopLoad();\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n EventHandler.prototype.destroy.call(this);\n this.state = State.STOPPED;\n }\n\n //Signal that video PTS was found\n onInitPtsFound(data) {\n var demuxerId=data.id, cc = data.frag.cc, initPTS = data.initPTS;\n if(demuxerId === 'main') {\n //Always update the new INIT PTS\n //Can change due level switch\n this.initPTS[cc] = initPTS;\n this.videoTrackCC = cc;\n logger.log(`InitPTS for cc:${cc} found from video track:${initPTS}`);\n\n //If we are waiting we need to demux/remux the waiting frag\n //With the new initPTS\n if (this.state === State.WAITING_INIT_PTS) {\n this.tick();\n }\n }\n }\n\n startLoad(startPosition) {\n if (this.tracks) {\n var lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n if (!this.timer) {\n this.timer = setInterval(this.ontick, 100);\n }\n this.fragLoadError = 0;\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`audio:override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n this.state = State.IDLE;\n } else {\n this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;\n this.state = State.STARTING;\n }\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime;\n this.tick();\n } else {\n this.startPosition = startPosition;\n this.state = State.STOPPED;\n }\n }\n\n stopLoad() {\n var frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.state = State.STOPPED;\n }\n\n set state(nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`audio stream:${previousState}->${nextState}`);\n }\n }\n\n get state() {\n return this._state;\n }\n\n tick() {\n this.ticks++;\n if (this.ticks === 1) {\n this.doTick();\n if (this.ticks > 1) {\n setTimeout(this.tick, 1);\n }\n this.ticks = 0;\n }\n }\n\n doTick() {\n var pos, track, trackDetails, hls = this.hls, config = hls.config;\n //logger.log('audioStream:' + this.state);\n switch(this.state) {\n case State.ERROR:\n //don't do anything in error state to avoid breaking further ...\n case State.PAUSED:\n //don't do anything in paused state either ...\n case State.BUFFER_FLUSHING:\n break;\n case State.STARTING:\n this.state = State.WAITING_TRACK;\n this.loadedmetadata = false;\n break;\n case State.IDLE:\n const tracks = this.tracks;\n // audio tracks not received => exit loop\n if (!tracks) {\n break;\n }\n // if video not attached AND\n // start fragment already requested OR start frag prefetch disable\n // exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!this.media &&\n (this.startFragRequested || !config.startFragPrefetch)) {\n break;\n }\n // determine next candidate fragment to be loaded, based on current position and\n // end of buffer position\n // if we have not yet loaded any fragment, start loading from start position\n if (this.loadedmetadata) {\n pos = this.media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n if (pos === undefined) {\n break;\n }\n }\n let media = this.mediaBuffer ? this.mediaBuffer : this.media,\n videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,\n bufferInfo = BufferHelper.bufferInfo(media,pos,config.maxBufferHole),\n mainBufferInfo = BufferHelper.bufferInfo(videoBuffer,pos,config.maxBufferHole),\n bufferLen = bufferInfo.len,\n bufferEnd = bufferInfo.end,\n fragPrevious = this.fragPrevious,\n // ensure we buffer at least config.maxBufferLength (default 30s)\n // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)\n maxBufLen = Math.max(config.maxBufferLength,mainBufferInfo.len),\n audioSwitch = this.audioSwitch,\n trackId = this.trackId;\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {\n trackDetails = tracks[trackId].details;\n // if track info not retrieved yet, switch state and wait for track retrieval\n if (typeof trackDetails === 'undefined') {\n this.state = State.WAITING_TRACK;\n break;\n }\n\n // we just got done loading the final fragment, check if we need to finalize media stream\n if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN) {\n // if we are not seeking or if we are seeking but everything (almost) til the end is buffered, let's signal eos\n // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference when switching\n // between different renditions. using half frag duration should help cope with these cases.\n if (!this.media.seeking || (this.media.duration-bufferEnd) < fragPrevious.duration/2) {\n // Finalize the media stream\n this.hls.trigger(Event.BUFFER_EOS,{ type : 'audio'});\n this.state = State.ENDED;\n break;\n }\n }\n\n // find fragment index, contiguous with end of buffer position\n let fragments = trackDetails.fragments,\n fragLen = fragments.length,\n start = fragments[0].start,\n end = fragments[fragLen-1].start + fragments[fragLen-1].duration,\n frag;\n\n // When switching audio track, reload audio as close as possible to currentTime\n if(audioSwitch){\n if (trackDetails.live && !trackDetails.PTSKnown) {\n logger.log(`switching audiotrack, live stream, unknown PTS,load first fragment`);\n bufferEnd = 0;\n } else {\n bufferEnd = pos;\n // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n if (trackDetails.PTSKnown && pos < start) {\n // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start\n if (bufferInfo.end > start || bufferInfo.nextStart) {\n logger.log('alt audio track ahead of main track, seek to start of alt audio track');\n this.media.currentTime = start + 0.05;\n } else {\n return;\n }\n }\n }\n }\n if (trackDetails.initSegment && !trackDetails.initSegment.data) {\n frag = trackDetails.initSegment;\n }\n // if bufferEnd before start of playlist, load first fragment\n else if (bufferEnd <= start) {\n frag = fragments[0];\n if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {\n // Ensure we find a fragment which matches the continuity of the video track\n frag = findFragWithCC(fragments, this.videoTrackCC);\n }\n if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {\n // we just loaded this first fragment, and we are still lagging behind the start of the live playlist\n // let's force seek to start\n const nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;\n logger.log(`no alt audio available @currentTime:${this.media.currentTime}, seeking @${nextBuffered + 0.05}`);\n this.media.currentTime = nextBuffered + 0.05;\n return;\n }\n } else {\n let foundFrag;\n let maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;\n let fragmentWithinToleranceTest = (candidate) => {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);\n if ((candidate.start + candidate.duration - candidateLookupTolerance) <= bufferEnd) {\n return 1;\n }// if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n return -1;\n }\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest);\n }\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen-1];\n }\n if (foundFrag) {\n frag = foundFrag;\n start = foundFrag.start;\n //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {\n if (frag.sn < trackDetails.endSN) {\n frag = fragments[frag.sn + 1 - trackDetails.startSN];\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n } else {\n frag = null;\n }\n }\n }\n }\n if(frag) {\n //logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));\n if (frag.decryptdata && (frag.decryptdata.uri != null) && (frag.decryptdata.key == null)) {\n logger.log(`Loading key for ${frag.sn} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}`);\n this.state = State.KEY_LOADING;\n hls.trigger(Event.KEY_LOADING, {frag: frag});\n } else {\n logger.log(`Loading ${frag.sn}, cc: ${frag.cc} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}, currentTime:${pos},bufferEnd:${bufferEnd.toFixed(3)}`);\n // ensure that we are not reloading the same fragments in loop ...\n if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx++;\n } else {\n this.fragLoadIdx = 0;\n }\n if (frag.loadCounter) {\n frag.loadCounter++;\n let maxThreshold = config.fragLoadingLoopThreshold;\n // if this frag has already been loaded 3 times, and if it has been reloaded recently\n if (frag.loadCounter > maxThreshold && (Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold)) {\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag});\n return;\n }\n } else {\n frag.loadCounter = 1;\n }\n frag.loadIdx = this.fragLoadIdx;\n this.fragCurrent = frag;\n this.startFragRequested = true;\n if (!isNaN(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n hls.trigger(Event.FRAG_LOADING, {frag: frag});\n this.state = State.FRAG_LOADING;\n }\n }\n }\n break;\n case State.WAITING_TRACK:\n track = this.tracks[this.trackId];\n // check if playlist is already loaded\n if (track && track.details) {\n this.state = State.IDLE;\n }\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = performance.now();\n var retryDate = this.retryDate;\n media = this.media;\n var isSeeking = media && media.seeking;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if(!retryDate || (now >= retryDate) || isSeeking) {\n logger.log(`audioStreamController: retryDate reached, switch back to IDLE state`);\n this.state = State.IDLE;\n }\n break;\n case State.WAITING_INIT_PTS:\n const videoTrackCC = this.videoTrackCC;\n if (this.initPTS[videoTrackCC] === undefined) {\n break;\n }\n\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingFrag = this.waitingFragment;\n if (waitingFrag) {\n const waitingFragCC = waitingFrag.frag.cc;\n if (videoTrackCC !== waitingFragCC) {\n track = this.tracks[this.trackId];\n if (track.details && track.details.live) {\n logger.warn(`Waiting fragment CC (${waitingFragCC}) does not match video track CC (${videoTrackCC})`);\n this.waitingFragment = null;\n this.state = State.IDLE;\n }\n } else {\n this.state = State.FRAG_LOADING;\n this.onFragLoaded(this.waitingFragment);\n this.waitingFragment = null;\n }\n } else {\n this.state = State.IDLE;\n }\n\n break;\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n }\n\n onMediaAttached(data) {\n var media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if(this.tracks && config.autoStartLoad) {\n this.startLoad(config.startPosition);\n }\n }\n\n onMediaDetaching() {\n var media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery\n var tracks = this.tracks;\n if (tracks) {\n // reset fragment load counter\n tracks.forEach(track => {\n if(track.details) {\n track.details.fragments.forEach(fragment => {\n fragment.loadCounter = undefined;\n });\n }\n });\n }\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n this.media = this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onMediaSeeking() {\n if (this.state === State.ENDED) {\n // switch to IDLE state to check for potential new fragment\n this.state = State.IDLE;\n }\n if (this.media) {\n this.lastCurrentTime = this.media.currentTime;\n }\n // avoid reporting fragment loop loading error in case user is seeking several times on same position\n if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n }\n // tick to speed up processing\n this.tick();\n }\n\n onMediaEnded() {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n\n onAudioTracksUpdated(data) {\n logger.log('audio tracks updated');\n this.tracks = data.audioTracks;\n }\n\n onAudioTrackSwitching(data) {\n // if any URL found on new audio track, it is an alternate audio track\n var altAudio = !!data.url;\n this.trackId = data.id;\n\n this.fragCurrent = null;\n this.state = State.PAUSED;\n this.waitingFragment=null;\n // destroy useless demuxer when switching audio to main\n if (!altAudio) {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n } else {\n // switching to audio track, start timer if not already started\n if (!this.timer) {\n this.timer = setInterval(this.ontick, 100);\n }\n }\n\n //should we switch tracks ?\n if(altAudio){\n this.audioSwitch = true;\n //main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.state=State.IDLE;\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n }\n }\n this.tick();\n }\n\n onAudioTrackLoaded(data) {\n var newDetails = data.details,\n trackId = data.id,\n track = this.tracks[trackId],\n duration = newDetails.totalduration,\n sliding = 0;\n\n logger.log(`track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live) {\n var curDetails = track.details;\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails,newDetails);\n sliding = newDetails.fragments[0].start;\n // TODO\n //this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown) {\n logger.log(`live audio playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live audio playlist - outdated PTS, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n logger.log('live audio playlist - first load, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n }\n track.details = newDetails;\n\n // compute start position\n if (!this.startFragRequested) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if(!isNaN(startTimeOffset)) {\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n this.startPosition = 0;\n }\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment\n if (this.state === State.WAITING_TRACK) {\n this.state = State.IDLE;\n }\n //trigger handler right now\n this.tick();\n }\n\n onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded(data) {\n var fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'audio' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n var track = this.tracks[this.trackId],\n details = track.details,\n duration = details.totalduration,\n trackId = fragCurrent.level,\n sn = fragCurrent.sn,\n cc = fragCurrent.cc,\n audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',\n stats = this.stats = data.stats;\n if (sn === 'initSegment') {\n this.state = State.IDLE;\n\n stats.tparsed = stats.tbuffered = performance.now();\n details.initSegment.data = data.payload;\n this.hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: fragCurrent, id : 'audio'});\n this.tick();\n } else {\n this.state = State.PARSING;\n // transmux the MPEG-TS data to ISO-BMFF segments\n this.appended = false;\n if(!this.demuxer) {\n this.demuxer = new Demuxer(this.hls,'audio');\n }\n //Check if we have video initPTS\n // If not we need to wait for it\n let initPTS = this.initPTS[cc];\n let initSegmentData = details.initSegment ? details.initSegment.data : [];\n if (details.initSegment || initPTS !== undefined) {\n this.pendingBuffering = true;\n logger.log(`Demuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n let accurateTimeOffset = false; //details.PTSKnown || !details.live;\n this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);\n } else {\n logger.log(`unknown video PTS for continuity counter ${cc}, waiting for video PTS before demuxing audio frag ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n this.waitingFragment=data;\n this.state=State.WAITING_INIT_PTS;\n }\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let tracks = data.tracks, track;\n\n // delete any video track found on audio demuxer\n if (tracks.video) {\n delete tracks.video;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if(track) {\n track.levelCodec = track.codec;\n track.id = data.id;\n this.hls.trigger(Event.BUFFER_CODECS,tracks);\n logger.log(`audio track:audio,container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n let appendObj = {type: 'audio', data: initSegment, parent : 'audio',content : 'initSegment'};\n if (this.audioSwitch) {\n this.pendingData = [appendObj];\n } else {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n }\n //trigger handler right now\n this.tick();\n }\n }\n }\n\n onFragParsingData(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n data.type === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let trackId= this.trackId,\n track = this.tracks[trackId],\n hls = this.hls;\n\n if (isNaN(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n logger.log(`parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb}`);\n LevelHelper.updateFragPTSDTS(track.details,fragCurrent,data.startPTS,data.endPTS);\n\n let audioSwitch = this.audioSwitch, media = this.media, appendOnBufferFlush = false;\n //Only flush audio from old audio tracks when PTS is known on new audio track\n if(audioSwitch && media) {\n if (media.readyState) {\n let currentTime = media.currentTime;\n logger.log('switching audio track : currentTime:'+ currentTime);\n if (currentTime >= data.startPTS) {\n logger.log('switching audio track : flushing all audio');\n this.state = State.BUFFER_FLUSHING;\n hls.trigger(Event.BUFFER_FLUSHING, {startOffset: 0 , endOffset: Number.POSITIVE_INFINITY, type : 'audio'});\n appendOnBufferFlush = true;\n //Lets announce that the initial audio track switch flush occur\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {id : trackId});\n }\n } else {\n //Lets announce that the initial audio track switch flush occur\n this.audioSwitch=false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {id : trackId});\n }\n }\n\n\n let pendingData = this.pendingData;\n if(!this.audioSwitch) {\n [data.data1, data.data2].forEach(buffer => {\n if (buffer && buffer.length) {\n pendingData.push({type: data.type, data: buffer, parent : 'audio',content : 'data'});\n }\n });\n if (!appendOnBufferFlush && pendingData.length) {\n pendingData.forEach(appendObj => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (this.state === State.PARSING) {\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n });\n this.pendingData = [];\n this.appended = true;\n }\n }\n //trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n\n onBufferCreated(data) {\n let audioTrack = data.tracks.audio;\n if (audioTrack) {\n this.mediaBuffer = audioTrack.buffer;\n this.loadedmetadata = true;\n }\n if (data.tracks.video) {\n this.videoBuffer = data.tracks.video.buffer;\n }\n }\n\n onBufferAppended(data) {\n if (data.parent === 'audio') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed() {\n //trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n let frag = this.fragCurrent, stats = this.stats, hls = this.hls;\n if (frag) {\n this.fragPrevious = frag;\n stats.tbuffered = performance.now();\n hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: frag, id : 'audio'});\n let media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`audio buffered : ${TimeRanges.toString(media.buffered)}`);\n if (this.audioSwitch && this.appended) {\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {id : this.trackId});\n }\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError(data) {\n let frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n return;\n }\n switch(data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n if(!data.fatal) {\n var loadError = this.fragLoadError;\n if(loadError) {\n loadError++;\n } else {\n loadError=1;\n }\n let config = this.config;\n if (loadError <= config.fragLoadingMaxRetry) {\n this.fragLoadError = loadError;\n // reset load counter to avoid frag loop loading error\n frag.loadCounter = 0;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n var delay = Math.min(Math.pow(2,loadError-1)*config.fragLoadingRetryDelay,config.fragLoadingMaxRetryTimeout);\n logger.warn(`audioStreamController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = performance.now() + delay;\n // retry loading state\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`audioStreamController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.FRAG_LOOP_LOADING_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received\n if(this.state !== State.ERROR) {\n // if fatal error, stop processing, otherwise move to IDLE to retry loading\n this.state = data.fatal ? State.ERROR : State.IDLE;\n logger.warn(`audioStreamController: ${data.details} while loading frag,switch to ${this.state} state ...`);\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {\n const media = this.mediaBuffer,\n currentTime = this.media.currentTime,\n mediaBuffered = media && BufferHelper.isBuffered(media,currentTime) && BufferHelper.isBuffered(media,currentTime+0.5);\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n const config = this.config;\n if(config.maxMaxBufferLength >= config.maxBufferLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength/=2;\n logger.warn(`audio:reduce max buffer length to ${config.maxMaxBufferLength}s`);\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;\n }\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n logger.warn('buffer full error also media.currentTime is not buffered, flush audio buffer');\n this.fragCurrent = null;\n // flush everything\n this.state = State.BUFFER_FLUSHING;\n this.hls.trigger(Event.BUFFER_FLUSHING, {startOffset: 0 , endOffset: Number.POSITIVE_INFINITY, type : 'audio'});\n }\n }\n break;\n default:\n break;\n }\n }\n\n onBufferFlushed() {\n let pendingData = this.pendingData;\n if (pendingData && pendingData.length) {\n logger.log('appending pending audio data on Buffer Flushed');\n pendingData.forEach(appendObj => {\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n });\n this.appended = true;\n this.pendingData = [];\n this.state = State.PARSED;\n } else {\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n this.tick();\n }\n }\n}\nexport default AudioStreamController;\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/audio-stream-controller.js","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport default (function() {\n if (typeof window !== 'undefined' && window.VTTCue) {\n return window.VTTCue;\n }\n\n var autoKeyword = 'auto';\n var directionSetting = {\n '': true,\n lr: true,\n rl: true\n };\n var alignSetting = {\n start: true,\n middle: true,\n end: true,\n left: true,\n right: true\n };\n\n function findDirectionSetting(value) {\n if (typeof value !== 'string') {\n return false;\n }\n var dir = directionSetting[value.toLowerCase()];\n return dir ? value.toLowerCase() : false;\n }\n\n function findAlignSetting(value) {\n if (typeof value !== 'string') {\n return false;\n }\n var align = alignSetting[value.toLowerCase()];\n return align ? value.toLowerCase() : false;\n }\n\n function extend(obj) {\n var i = 1;\n for (; i < arguments.length; i++) {\n var cobj = arguments[i];\n for (var p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue(startTime, endTime, text) {\n var cue = this;\n var isIE8 = (function () {\n if (typeof navigator === 'undefined') {\n return;\n }\n return (/MSIE\\s8\\.0/).test(navigator.userAgent);\n })();\n var baseObj = {};\n\n if (isIE8) {\n cue = document.createElement('custom');\n } else {\n baseObj.enumerable = true;\n }\n\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n var _id = '';\n var _pauseOnExit = false;\n var _startTime = startTime;\n var _endTime = endTime;\n var _text = text;\n var _region = null;\n var _vertical = '';\n var _snapToLines = true;\n var _line = 'auto';\n var _lineAlign = 'start';\n var _position = 50;\n var _positionAlign = 'middle';\n var _size = 50;\n var _align = 'middle';\n\n Object.defineProperty(cue, 'id', extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value) {\n _id = '' + value;\n }\n }));\n\n Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value) {\n _pauseOnExit = !!value;\n }\n }));\n\n Object.defineProperty(cue, 'startTime', extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n _startTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'endTime', extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n _endTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'text', extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value) {\n _text = '' + value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'region', extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value) {\n _region = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'vertical', extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value) {\n var setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _vertical = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'line', extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value) {\n if (typeof value !== 'number' && value !== autoKeyword) {\n throw new SyntaxError('An invalid number or illegal string was specified.');\n }\n _line = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _lineAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'position', extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n _position = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _positionAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'size', extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n _size = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'align', extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _align = setting;\n this.hasBeenReset = true;\n }\n }));\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = undefined;\n\n if (isIE8) {\n return cue;\n }\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n var WebVTT = window.WebVTT;\n return WebVTT.convertCueToDOMTree(window, this.text);\n };\n\n return VTTCue;\n})();\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/vttcue.js","/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716\n */\n\nimport VTTCue from './vttcue';\n\nconst StringDecoder = function StringDecoder() {\n return {\n decode: function(data) {\n if (!data) {\n return '';\n }\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n return decodeURIComponent(encodeURIComponent(data));\n },\n };\n };\n\nfunction VTTParser() {\n this.window = window;\n this.state = 'INITIAL';\n this.buffer = '';\n this.decoder = new StringDecoder();\n this.regionList = [];\n}\n\n\n// Try to parse input as a time stamp.\nfunction parseTimeStamp(input) {\n\n function computeSeconds(h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;\n }\n\n var m = input.match(/^(\\d+):(\\d{2})(:\\d{2})?\\.(\\d{3})/);\n if (!m) {\n return null;\n }\n\n if (m[3]) {\n // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);\n } else if (m[1] > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[1], m[2], 0, m[4]);\n } else {\n // Timestamp takes the form of [minutes]:[seconds].[milliseconds]\n return computeSeconds(0, m[1], m[2], m[4]);\n }\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nfunction Settings() {\n this.values = Object.create(null);\n}\n\nSettings.prototype = {\n // Only accept the first assignment to any key.\n set: function(k, v) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n },\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get: function(k, dflt, defaultKey) {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n return this.has(k) ? this.values[k] : dflt;\n },\n // Check whether we have a value for a key.\n has: function(k) {\n return k in this.values;\n },\n // Accept a setting if its one of the given alternatives.\n alt: function(k, v, a) {\n for (var n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n },\n // Accept a setting if its a valid (signed) integer.\n integer: function(k, v) {\n if (/^-?\\d+$/.test(v)) { // integer\n this.set(k, parseInt(v, 10));\n }\n },\n // Accept a setting if its a valid percentage.\n percent: function(k, v) {\n var m;\n if ((m = v.match(/^([\\d]{1,3})(\\.[\\d]*)?%$/))) {\n v = parseFloat(v);\n if (v >= 0 && v <= 100) {\n this.set(k, v);\n return true;\n }\n }\n return false;\n }\n};\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interprete each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions(input, callback, keyValueDelim, groupDelim) {\n var groups = groupDelim ? input.split(groupDelim) : [input];\n for (var i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n var kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n var k = kv[0];\n var v = kv[1];\n callback(k, v);\n }\n}\n\nvar defaults = new VTTCue(0, 0, 0);\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Safari doesn't yet support this change, but FF and Chrome do.\nvar center = defaults.align === 'middle' ? 'middle' : 'center';\n\nfunction parseCue(input, cue, regionList) {\n // Remember the original input if we need to throw an error.\n var oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp() {\n var ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings(input, cue) {\n var settings = new Settings();\n\n parseOptions(input, function(k, v) {\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (var i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n var vals = v.split(','),\n vals0 = vals[0];\n settings.integer(k, vals0);\n if (settings.percent(k, vals0)) {\n settings.set('snapToLines', false);\n }\n settings.alt(k, vals0, ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);\n }\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n }, /:/, /\\s/);\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n var line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n var position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;\n }\n cue.position = position;\n }\n\n function skipWhitespace() {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.substr(0, 3) !== '-->') { // (3) next characters must match '-->'\n throw new Error('Malformed time stamp (time stamps must be separated by \\'-->\\'): ' +\n oInput);\n }\n input = input.substr(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\n\nfunction fixLineBreaks(input) {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\n\nVTTParser.prototype = {\n parse: function(data) {\n var self = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n self.buffer += self.decoder.decode(data, {stream: true});\n }\n\n function collectNextLine() {\n var buffer = self.buffer;\n var pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n ++pos;\n }\n var line = buffer.substr(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n self.buffer = buffer.substr(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader(input) {\n parseOptions(input, function(k, v) {\n switch (k) {\n case 'Region':\n // 3.3 WebVTT region metadata header syntax\n console.log('parse region', v);\n //parseRegion(v);\n break;\n }\n }, /:/);\n }\n\n // 5.1 WebVTT file parsing.\n try {\n var line;\n if (self.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n line = collectNextLine();\n // strip of UTF-8 BOM if any\n // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n var m = line.match(/^()?WEBVTT([ \\t].*)?$/);\n if (!m || !m[0]) {\n throw new Error('Malformed WebVTT signature.');\n }\n\n self.state = 'HEADER';\n }\n\n var alreadyCollectedLine = false;\n while (self.buffer) {\n // We can't parse a line until we have the full line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n if (!alreadyCollectedLine) {\n line = collectNextLine();\n } else {\n alreadyCollectedLine = false;\n }\n\n switch (self.state) {\n case 'HEADER':\n // 13-18 - Allow a header (metadata) under the WEBVTT line.\n if (/:/.test(line)) {\n parseHeader(line);\n } else if (!line) {\n // An empty line terminates the header and starts the body (cues).\n self.state = 'ID';\n }\n continue;\n case 'NOTE':\n // Ignore NOTE blocks.\n if (!line) {\n self.state = 'ID';\n }\n continue;\n case 'ID':\n // Check for the start of NOTE blocks.\n if (/^NOTE($|[ \\t])/.test(line)) {\n self.state = 'NOTE';\n break;\n }\n // 19-29 - Allow any number of line terminators, then initialize new cue values.\n if (!line) {\n continue;\n }\n self.cue = new VTTCue(0, 0, '');\n self.state = 'CUE';\n // 30-39 - Check if self line contains an optional identifier or timing data.\n if (line.indexOf('-->') === -1) {\n self.cue.id = line;\n continue;\n }\n // Process line as start of a cue.\n /*falls through*/\n case 'CUE':\n // 40 - Collect cue timings and settings.\n try {\n parseCue(line, self.cue, self.regionList);\n } catch (e) {\n // In case of an error ignore rest of the cue.\n self.cue = null;\n self.state = 'BADCUE';\n continue;\n }\n self.state = 'CUETEXT';\n continue;\n case 'CUETEXT':\n var hasSubstring = line.indexOf('-->') !== -1;\n // 34 - If we have an empty line then report the cue.\n // 35 - If we have the special substring '-->' then report the cue,\n // but do not collect the line as we need to process the current\n // one as a new cue.\n if (!line || hasSubstring && (alreadyCollectedLine = true)) {\n // We are done parsing self cue.\n if (self.oncue) {\n self.oncue(self.cue);\n }\n self.cue = null;\n self.state = 'ID';\n continue;\n }\n if (self.cue.text) {\n self.cue.text += '\\n';\n }\n self.cue.text += line;\n continue;\n case 'BADCUE': // BADCUE\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n self.state = 'ID';\n }\n continue;\n }\n }\n } catch (e) {\n\n // If we are currently parsing a cue, report what we have.\n if (self.state === 'CUETEXT' && self.cue && self.oncue) {\n self.oncue(self.cue);\n }\n self.cue = null;\n // Enter BADWEBVTT state if header was not parsed correctly otherwise\n // another exception occurred so enter BADCUE state.\n self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n }\n return this;\n },\n flush: function() {\n var self = this;\n try {\n // Finish decoding the stream.\n self.buffer += self.decoder.decode();\n // Synthesize the end of the current cue or region.\n if (self.cue || self.state === 'HEADER') {\n self.buffer += '\\n\\n';\n self.parse();\n }\n // If we've flushed, parsed, and we're still on the INITIAL state then\n // that means we don't have enough of the stream to parse the first\n // line.\n if (self.state === 'INITIAL') {\n throw new Error('Malformed WebVTT signature.');\n }\n } catch (e) {\n throw e;\n }\n if (self.onflush) {\n self.onflush();\n }\n return this;\n }\n};\n\nexport { fixLineBreaks };\n\nexport default VTTParser;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/vttparser.js","import { fixLineBreaks } from './vttparser';\n\nexport function newCue(track, startTime, endTime, captionScreen) {\n var row;\n var cue;\n var indenting;\n var indent;\n var text;\n var VTTCue = window.VTTCue || window.TextTrackCue;\n\n for (var r=0; r<captionScreen.rows.length; r++)\n {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty())\n {\n for (var c=0; c<row.chars.length; c++)\n {\n if (row.chars[c].uchar.match(/\\s/) && indenting)\n {\n indent++;\n }\n else\n {\n text += row.chars[c].uchar;\n indenting = false;\n }\n }\n //To be used for cleaning-up orphaned roll-up captions\n row.cueStartTime = startTime;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime)\n {\n endTime += 0.0001;\n }\n\n cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));\n\n if (indent >= 16)\n {\n indent--;\n }\n else\n {\n indent++;\n }\n\n // VTTCue.line get's flakey when using controls, so let's now include line 13&14\n // also, drop line 1 since it's to close to the top\n if (navigator.userAgent.match(/Firefox\\//))\n {\n cue.line = r + 1;\n }\n else\n {\n cue.line = (r > 7 ? r - 2 : r + 1);\n }\n cue.align = 'left';\n // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break\n cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\\//) ? 50 : 0)));\n track.addCue(cue);\n }\n }\n}\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/cues.js","/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n /**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nvar specialCea608CharsCodes = {\n 0x2a : 0xe1, // lowercase a, acute accent\n 0x5c : 0xe9, // lowercase e, acute accent\n 0x5e : 0xed, // lowercase i, acute accent\n 0x5f : 0xf3, // lowercase o, acute accent\n 0x60 : 0xfa, // lowercase u, acute accent\n 0x7b : 0xe7, // lowercase c with cedilla\n 0x7c : 0xf7, // division symbol\n 0x7d : 0xd1, // uppercase N tilde\n 0x7e : 0xf1, // lowercase n tilde\n 0x7f : 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80 : 0xae, // Registered symbol (R)\n 0x81 : 0xb0, // degree sign\n 0x82 : 0xbd, // 1/2 symbol\n 0x83 : 0xbf, // Inverted (open) question mark\n 0x84 : 0x2122, // Trademark symbol (TM)\n 0x85 : 0xa2, // Cents symbol\n 0x86 : 0xa3, // Pounds sterling\n 0x87 : 0x266a, // Music 8'th note\n 0x88 : 0xe0, // lowercase a, grave accent\n 0x89 : 0x20, // transparent space (regular)\n 0x8a : 0xe8, // lowercase e, grave accent\n 0x8b : 0xe2, // lowercase a, circumflex accent\n 0x8c : 0xea, // lowercase e, circumflex accent\n 0x8d : 0xee, // lowercase i, circumflex accent\n 0x8e : 0xf4, // lowercase o, circumflex accent\n 0x8f : 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90 : 0xc1, // capital letter A with acute\n 0x91 : 0xc9, // capital letter E with acute\n 0x92 : 0xd3, // capital letter O with acute\n 0x93 : 0xda, // capital letter U with acute\n 0x94 : 0xdc, // capital letter U with diaresis\n 0x95 : 0xfc, // lowercase letter U with diaeresis\n 0x96 : 0x2018, // opening single quote\n 0x97 : 0xa1, // inverted exclamation mark\n 0x98 : 0x2a, // asterisk\n 0x99 : 0x2019, // closing single quote\n 0x9a : 0x2501, // box drawings heavy horizontal\n 0x9b : 0xa9, // copyright sign\n 0x9c : 0x2120, // Service mark\n 0x9d : 0x2022, // (round) bullet\n 0x9e : 0x201c, // Left double quotation mark\n 0x9f : 0x201d, // Right double quotation mark\n 0xa0 : 0xc0, // uppercase A, grave accent\n 0xa1 : 0xc2, // uppercase A, circumflex\n 0xa2 : 0xc7, // uppercase C with cedilla\n 0xa3 : 0xc8, // uppercase E, grave accent\n 0xa4 : 0xca, // uppercase E, circumflex\n 0xa5 : 0xcb, // capital letter E with diaresis\n 0xa6 : 0xeb, // lowercase letter e with diaresis\n 0xa7 : 0xce, // uppercase I, circumflex\n 0xa8 : 0xcf, // uppercase I, with diaresis\n 0xa9 : 0xef, // lowercase i, with diaresis\n 0xaa : 0xd4, // uppercase O, circumflex\n 0xab : 0xd9, // uppercase U, grave accent\n 0xac : 0xf9, // lowercase u, grave accent\n 0xad : 0xdb, // uppercase U, circumflex\n 0xae : 0xab, // left-pointing double angle quotation mark\n 0xaf : 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0 : 0xc3, // Uppercase A, tilde\n 0xb1 : 0xe3, // Lowercase a, tilde\n 0xb2 : 0xcd, // Uppercase I, acute accent\n 0xb3 : 0xcc, // Uppercase I, grave accent\n 0xb4 : 0xec, // Lowercase i, grave accent\n 0xb5 : 0xd2, // Uppercase O, grave accent\n 0xb6 : 0xf2, // Lowercase o, grave accent\n 0xb7 : 0xd5, // Uppercase O, tilde\n 0xb8 : 0xf5, // Lowercase o, tilde\n 0xb9 : 0x7b, // Open curly brace\n 0xba : 0x7d, // Closing curly brace\n 0xbb : 0x5c, // Backslash\n 0xbc : 0x5e, // Caret\n 0xbd : 0x5f, // Underscore\n 0xbe : 0x7c, // Pipe (vertical line)\n 0xbf : 0x223c, // Tilde operator\n 0xc0 : 0xc4, // Uppercase A, umlaut\n 0xc1 : 0xe4, // Lowercase A, umlaut\n 0xc2 : 0xd6, // Uppercase O, umlaut\n 0xc3 : 0xf6, // Lowercase o, umlaut\n 0xc4 : 0xdf, // Esszett (sharp S)\n 0xc5 : 0xa5, // Yen symbol\n 0xc6 : 0xa4, // Generic currency sign\n 0xc7 : 0x2503, // Box drawings heavy vertical\n 0xc8 : 0xc5, // Uppercase A, ring\n 0xc9 : 0xe5, // Lowercase A, ring\n 0xca : 0xd8, // Uppercase O, stroke\n 0xcb : 0xf8, // Lowercase o, strok\n 0xcc : 0x250f, // Box drawings heavy down and right\n 0xcd : 0x2513, // Box drawings heavy down and left\n 0xce : 0x2517, // Box drawings heavy up and right\n 0xcf : 0x251b // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nvar getCharForByte = function(byte) {\n var charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n return String.fromCharCode(charCode);\n};\n\nvar NR_ROWS = 15,\n NR_COLS = 100;\n// Tables to look up row from PAC data\nvar rowsLowCh1 = {0x11 : 1, 0x12 : 3, 0x15 : 5, 0x16 : 7, 0x17 : 9, 0x10 : 11, 0x13 : 12, 0x14 : 14};\nvar rowsHighCh1 = {0x11 : 2, 0x12 : 4, 0x15 : 6, 0x16 : 8, 0x17 : 10, 0x13 : 13, 0x14 : 15};\nvar rowsLowCh2 = {0x19 : 1, 0x1A : 3, 0x1D : 5, 0x1E : 7, 0x1F : 9, 0x18 : 11, 0x1B : 12, 0x1C : 14};\nvar rowsHighCh2 = {0x19 : 2, 0x1A : 4, 0x1D : 6, 0x1E : 8, 0x1F : 10, 0x1B : 13, 0x1C : 15};\n\nvar backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];\n\n/**\n * Simple logger class to be able to write with time-stamps and filter on level.\n */\nvar logger = {\n verboseFilter : {'DATA' : 3, 'DEBUG' : 3, 'INFO' : 2, 'WARNING' : 2, 'TEXT' : 1, 'ERROR' : 0},\n time : null,\n verboseLevel : 0, // Only write errors\n setTime : function(newTime) {\n this.time = newTime;\n },\n log : function(severity, msg) {\n var minLevel = this.verboseFilter[severity];\n if (this.verboseLevel >= minLevel) {\n console.log(this.time + ' [' + severity + '] ' + msg);\n }\n }\n};\n\nvar numArrayToHexArray = function(numArray) {\n var hexArray = [];\n for (var j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n return hexArray;\n};\n\nclass PenState {\n\n constructor(foreground, underline, italics, background, flash) {\n this.foreground = foreground || 'white';\n this.underline = underline || false;\n this.italics = italics || false;\n this.background = background || 'black';\n this.flash = flash || false;\n }\n\n reset() {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n\n setStyles(styles) {\n var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (var i = 0 ; i < attribs.length; i++) {\n var style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n\n isDefault() {\n return (this.foreground === 'white' && !this.underline && !this.italics &&\n this.background === 'black' && !this.flash);\n }\n\n equals(other) {\n return ( (this.foreground === other.foreground) &&\n (this.underline === other.underline) &&\n (this.italics === other.italics) &&\n (this.background === other.background) &&\n (this.flash === other.flash) );\n }\n\n copy(newPenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n }\n\n toString() {\n return ('color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics +\n ', background=' + this.background + ', flash=' + this.flash);\n }\n}\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\nclass StyledUnicodeChar\n{\n\n constructor(uchar, foreground, underline, italics, background, flash) {\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(foreground, underline,italics, background, flash);\n }\n\n reset() {\n this.uchar = ' ';\n this.penState.reset();\n }\n\n setChar(uchar, newPenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n\n setPenState(newPenState) {\n this.penState.copy(newPenState);\n }\n\n equals(other) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n\n copy(newChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n\n isEmpty() {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n}\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\nclass Row {\n constructor() {\n this.chars = [];\n for (var i = 0 ; i < NR_COLS ; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals(other) {\n var equal = true;\n for (var i = 0 ; i < NR_COLS; i ++) {\n if (!this.chars[i].equals(other.chars[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other) {\n for (var i = 0 ; i < NR_COLS; i ++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty() {\n var empty = true;\n for (var i = 0 ; i < NR_COLS; i ++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor(absPos) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n if (this.pos < 0) {\n logger.log('ERROR', 'Negative cursor position ' + this.pos);\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n logger.log('ERROR', 'Too large cursor position ' + this.pos);\n this.pos = NR_COLS;\n }\n }\n\n /**\n * Move the cursor relative to current position.\n */\n moveCursor(relPos) {\n var newPos = this.pos + relPos;\n if (relPos > 1) {\n for (var i = this.pos+1; i < newPos+1 ; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n }\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace() {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n\n insertChar(byte) {\n if (byte >= 0x90) { //Extended char\n this.backSpace();\n }\n var char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n logger.log('ERROR', 'Cannot insert ' + byte.toString(16) +\n ' (' + char + ') at position ' + this.pos + '. Skipping it!');\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n }\n\n clearFromPos(startPos) {\n var i;\n for (i = startPos ; i < NR_COLS ; i++) {\n this.chars[i].reset();\n }\n }\n\n clear() {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n\n clearToEndOfRow() {\n this.clearFromPos(this.pos);\n }\n\n getTextString() {\n var chars = [];\n var empty = true;\n for (var i = 0 ; i < NR_COLS ; i++) {\n var char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n\n setPenStyles(styles) {\n this.currPenState.setStyles(styles);\n var currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n}\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n*/\nclass CaptionScreen {\n\n constructor() {\n this.rows = [];\n for (var i = 0 ; i < NR_ROWS; i++) {\n this.rows.push(new Row()); // Note that we use zero-based numbering (0-14)\n }\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.reset();\n }\n\n reset() {\n for (var i = 0 ; i < NR_ROWS ; i++) {\n this.rows[i].clear();\n }\n this.currRow = NR_ROWS - 1;\n }\n\n equals(other) {\n var equal = true;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other) {\n for (var i = 0 ; i < NR_ROWS ; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty() {\n var empty = true;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n backSpace() {\n var row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow() {\n var row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar(char) {\n var row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen(styles) {\n var row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor(relPos) {\n var row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor(absPos) {\n logger.log('INFO', 'setCursor: ' + absPos);\n var row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC(pacData) {\n logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));\n var newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows-1;\n }\n\n //Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n //clear all rows first\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n //Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n //topRowIndex - the start of rows to copy (inclusive index)\n var topRowIndex = this.currRow + 1 - (this.nrRollUpRows);\n //We only copy if the last position was already shown.\n //We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n if(prevLineTime && prevLineTime < logger.time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow-this.nrRollUpRows+i+1].copy(lastOutputScreen.rows[topRowIndex+i]);\n }\n }\n }\n }\n\n this.currRow = newRow;\n var row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n var indent = pacData.indent;\n var prevPos = Math.max(indent-1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n var styles = {foreground : pacData.color, underline : pacData.underline, italics : pacData.italics, background : 'black', flash : false};\n this.setPen(styles);\n }\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData(bkgData) {\n\n logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); //Space\n }\n\n setRollUpRows(nrRows) {\n this.nrRollUpRows = nrRows;\n }\n\n rollUp() {\n if (this.nrRollUpRows === null) {\n logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');\n return; //Not properly setup\n }\n logger.log('TEXT', this.getDisplayText());\n var topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n var topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n logger.log('INFO', 'Rolling up');\n //logger.log('TEXT', this.get_display_text())\n }\n\n /**\n * Get all non-empty rows with as unicode text.\n */\n getDisplayText(asOneRow) {\n asOneRow = asOneRow || false;\n var displayText = [];\n var text = '';\n var rowNr = -1;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n var rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i+1;\n if (asOneRow) {\n displayText.push('Row ' + rowNr + ': \\'' + rowText + '\\'');\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = '[' + displayText.join(' | ') + ']';\n } else {\n text = displayText.join('\\n');\n }\n }\n return text;\n }\n\n getTextAndFormat() {\n return this.rows;\n }\n}\n\n//var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\nclass Cea608Channel\n{\n constructor(channelNumber, outputFilter) {\n\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen();\n this.nonDisplayedMemory = new CaptionScreen();\n this.lastOutputScreen = new CaptionScreen();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS-1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n }\n\n reset() {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS-1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n this.lastCueEndTime = null;\n }\n\n getHandler() {\n return this.outputFilter;\n }\n\n setHandler(newHandler) {\n this.outputFilter = newHandler;\n }\n\n setPAC(pacData) {\n this.writeScreen.setPAC(pacData);\n }\n\n setBkgData(bkgData) {\n this.writeScreen.setBkgData(bkgData);\n }\n\n setMode(newMode) {\n if (newMode === this.mode) {\n return;\n }\n this.mode = newMode;\n logger.log('INFO', 'MODE=' + newMode);\n if (this.mode === 'MODE_POP-ON') {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n }\n if (this.mode !== 'MODE_ROLL-UP') {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n }\n\n insertChars(chars) {\n for (var i = 0 ; i < chars.length ; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));\n this.outputDataUpdate();\n }\n }\n\n ccRCL() { // Resume Caption Loading (switch mode to Pop On)\n logger.log('INFO', 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS() { // BackSpace\n logger.log('INFO', 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF() { // Reserved (formerly Alarm Off)\n return;\n }\n\n ccAON() { // Reserved (formerly Alarm On)\n return;\n }\n\n ccDER() { // Delete to End of Row\n logger.log('INFO', 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n\n ccRU(nrRows) { //Roll-Up Captions-2,3,or 4 Rows\n logger.log('INFO', 'RU(' + nrRows +') - Roll Up');\n this.writeScreen = this.displayedMemory;\n this.setMode('MODE_ROLL-UP');\n this.writeScreen.setRollUpRows(nrRows);\n }\n\n ccFON() { //Flash On\n logger.log('INFO', 'FON - Flash On');\n this.writeScreen.setPen({flash : true});\n }\n\n ccRDC() { // Resume Direct Captioning (switch mode to PaintOn)\n logger.log('INFO', 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR() { // Text Restart in text mode (not supported, however)\n logger.log('INFO', 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD() { // Resume Text Display in Text mode (not supported, however)\n logger.log('INFO', 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM() { // Erase Displayed Memory\n logger.log('INFO', 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n\n ccCR() { // Carriage Return\n logger.log('CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n\n ccENM() { //Erase Non-Displayed Memory\n logger.log('INFO', 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC() { //End of Caption (Flip Memories)\n logger.log('INFO', 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n var tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());\n }\n this.outputDataUpdate(true);\n }\n\n ccTO(nrCols) { // Tab Offset 1,2, or 3 columns\n logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW(secondByte) { // Parse MIDROW command\n var styles = {flash : false};\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n var colorIndex = Math.floor(secondByte/2) - 0x10;\n var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n }\n\n outputDataUpdate(dispatch = false) {\n let t = logger.time;\n if (t === null) {\n return;\n }\n if (this.outputFilter) {\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { // Start of a new cue\n this.cueStartTime = t;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);\n if (dispatch === true && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n }\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n\n cueSplitAtTime(t) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);\n }\n this.cueStartTime = t;\n }\n }\n }\n}\n\nclass Cea608Parser {\n\n constructor(field, out1, out2) {\n this.field = field || 1;\n this.outputs = [out1, out2];\n this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];\n this.currChNr = -1; // Will be 1 or 2\n this.lastCmdA = null; // First byte of last command\n this.lastCmdB = null; // Second byte of last command\n this.bufferedData = [];\n this.startTime = null;\n this.lastTime = null;\n this.dataCounters = {'padding' : 0, 'char' : 0, 'cmd' : 0, 'other' : 0};\n }\n\n getHandler(index) {\n return this.channels[index].getHandler();\n }\n\n setHandler(index, newHandler) {\n this.channels[index].setHandler(newHandler);\n }\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData(t, byteList) {\n var cmdFound, a, b,\n charsFound = false;\n\n this.lastTime = t;\n logger.setTime(t);\n\n for (var i = 0 ; i < byteList.length ; i+=2) {\n a = byteList[i] & 0x7f;\n b = byteList[i+1] & 0x7f;\n if (a === 0 && b === 0) {\n this.dataCounters.padding += 2;\n continue;\n } else {\n logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i+1]]) +'] -> (' + numArrayToHexArray([a, b]) + ')');\n }\n cmdFound = this.parseCmd(a, b);\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n if (this.currChNr && this.currChNr >=0) {\n var channel = this.channels[this.currChNr-1];\n channel.insertChars(charsFound);\n } else {\n logger.log('WARNING', 'No channel found yet. TEXT-MODE?');\n }\n }\n }\n if (cmdFound) {\n this.dataCounters.cmd += 2;\n } else if (charsFound) {\n this.dataCounters.char += 2;\n } else {\n this.dataCounters.other += 2;\n logger.log('WARNING', 'Couldn\\'t parse cleaned data ' + numArrayToHexArray([a, b]) +\n ' orig: ' + numArrayToHexArray([byteList[i], byteList[i+1]]));\n }\n }\n }\n\n /**\n * Parse Command.\n * @returns {Boolean} Tells if a command was found\n */\n parseCmd(a, b) {\n var chNr = null;\n\n var cond1 = (a === 0x14 || a === 0x1C) && (0x20 <= b && b <= 0x2F);\n var cond2 = (a === 0x17 || a === 0x1F) && (0x21 <= b && b <= 0x23);\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null; // Repeated commands are dropped (once)\n logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');\n return true;\n }\n\n if (a === 0x14 || a === 0x17) {\n chNr = 1;\n } else {\n chNr = 2; // (a === 0x1C || a=== 0x1f)\n }\n\n var channel = this.channels[chNr - 1];\n\n if (a === 0x14 || a === 0x1C) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2A) {\n channel.ccTR();\n } else if (b === 0x2B) {\n channel.ccRTD();\n } else if (b === 0x2C) {\n channel.ccEDM();\n } else if (b === 0x2D) {\n channel.ccCR();\n } else if (b === 0x2E) {\n channel.ccENM();\n } else if (b === 0x2F) {\n channel.ccEOC();\n }\n } else { //a == 0x17 || a == 0x1F\n channel.ccTO(b - 0x20);\n }\n this.lastCmdA = a;\n this.lastCmdB = b;\n this.currChNr = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n * @returns {Boolean}\n */\n parseMidrow(a, b) {\n var chNr = null;\n\n if ( ((a === 0x11) || (a === 0x19)) && 0x20 <= b && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n if (chNr !== this.currChNr) {\n logger.log('ERROR', 'Mismatch channel in midrow parsing');\n return false;\n }\n var channel = this.channels[chNr-1];\n channel.ccMIDROW(b);\n logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');\n return true;\n }\n return false;\n }\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC(a, b) {\n\n var chNr = null;\n var row = null;\n\n var case1 = ((0x11 <= a && a <= 0x17) || (0x19 <= a && a <= 0x1F)) && (0x40 <= b && b <= 0x7F);\n var case2 = (a === 0x10 || a === 0x18) && (0x40 <= b && b <= 0x5F);\n if (! (case1 || case2)) {\n return false;\n }\n\n if (a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null;\n return true; // Repeated commands are dropped (once)\n }\n\n chNr = (a <= 0x17) ? 1 : 2;\n\n if (0x40 <= b && b <= 0x5F) {\n row = (chNr === 1) ? rowsLowCh1[a] : rowsLowCh2[a];\n } else { // 0x60 <= b <= 0x7F\n row = (chNr === 1) ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n var pacData = this.interpretPAC(row, b);\n var channel = this.channels[chNr-1];\n channel.setPAC(pacData);\n this.lastCmdA = a;\n this.lastCmdB = b;\n this.currChNr = chNr;\n return true;\n }\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns {Object} pacData with style parameters.\n */\n interpretPAC(row, byte) {\n var pacIndex = byte;\n var pacData = {color : null, italics : false, indent : null, underline : false, row : row};\n\n if (byte > 0x5F) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex/2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = (Math.floor((pacIndex-0x10)/2))*4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n }\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars(a, b) {\n\n var channelNr = null,\n charCodes = null,\n charCode1 = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (0x11 <= charCode1 && charCode1 <= 0x13) {\n // Special character\n var oneCode = b;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n logger.log('INFO', 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n charCodes = [oneCode];\n } else if (0x20 <= a && a <= 0x7f) {\n charCodes = (b === 0) ? [a] : [a, b];\n }\n if (charCodes) {\n var hexCodes = numArrayToHexArray(charCodes);\n logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));\n this.lastCmdA = null;\n this.lastCmdB = null;\n }\n return charCodes;\n }\n\n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns{Boolean} Tells if background attributes are found\n */\n parseBackgroundAttributes(a, b) {\n var bkgData,\n index,\n chNr,\n channel;\n\n var case1 = (a === 0x10 || a === 0x18) && (0x20 <= b && b <= 0x2f);\n var case2 = (a === 0x17 || a === 0x1f) && (0x2d <=b && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\n bkgData = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b-0x20)/2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + '_semi';\n }\n } else if (b === 0x2d) {\n bkgData.background = 'transparent';\n } else {\n bkgData.foreground = 'black';\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n chNr = (a < 0x18) ? 1 : 2;\n channel = this.channels[chNr-1];\n channel.setBkgData(bkgData);\n this.lastCmdA = null;\n this.lastCmdB = null;\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset() {\n for (var i=0 ; i < this.channels.length ; i++) {\n if (this.channels[i]) {\n this.channels[i].reset();\n }\n }\n this.lastCmdA = null;\n this.lastCmdB = null;\n }\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime(t) {\n for (var i=0 ; i < this.channels.length ; i++) {\n if (this.channels[i]) {\n this.channels[i].cueSplitAtTime(t);\n }\n }\n }\n}\n\nexport default Cea608Parser;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/cea-608-parser.js","export default class OutputFilter {\n\n constructor(timelineController, track) {\n this.timelineController = timelineController;\n this.track = track;\n this.startTime = null;\n this.endTime = null;\n this.screen = null;\n }\n\n dispatchCue() {\n if (this.startTime === null) {\n return;\n }\n this.timelineController.addCues('textTrack' + this.track, this.startTime, this.endTime, this.screen);\n this.startTime = null;\n }\n\n newCue(startTime, endTime, screen) {\n if (this.startTime === null || this.startTime > startTime) {\n this.startTime = startTime;\n }\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.track);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/output-filter.js","import VTTParser from './vttparser';\nimport { utf8ArrayToStr } from '../demux/id3';\n\n// String.prototype.startsWith is not supported in IE11\nconst startsWith = function(inputString, searchString, position) {\n return inputString.substr(position || 0, searchString.length) === searchString;\n};\n\nconst cueString2millis = function(timeString) {\n let ts = parseInt(timeString.substr(-3));\n let secs = parseInt(timeString.substr(-6,2));\n let mins = parseInt(timeString.substr(-9,2));\n let hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;\n\n if (isNaN(ts) || isNaN(secs) || isNaN(mins) || isNaN(hours)) {\n return -1;\n }\n\n ts += 1000 * secs;\n ts += 60*1000 * mins;\n ts += 60*60*1000 * hours;\n\n return ts;\n};\n\n// From https://github.com/darkskyapp/string-hash\nconst hash = function(text) {\n let hash = 5381;\n let i = text.length;\n while (i) {\n hash = (hash * 33) ^ text.charCodeAt(--i);\n }\n return (hash >>> 0).toString();\n};\n\nconst calculateOffset = function(vttCCs, cc, presentationTime) {\n let currCC = vttCCs[cc];\n let prevCC = vttCCs[currCC.prevCC];\n\n // This is the first discontinuity or cues have been processed since the last discontinuity\n // Offset = current discontinuity time\n if (!prevCC || (!prevCC.new && currCC.new)) {\n vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n currCC.new = false;\n return;\n }\n\n // There have been discontinuities since cues were last parsed.\n // Offset = time elapsed\n while (prevCC && prevCC.new) {\n vttCCs.ccOffset += currCC.start - prevCC.start;\n currCC.new = false;\n currCC = prevCC;\n prevCC = vttCCs[currCC.prevCC];\n }\n\n vttCCs.presentationOffset = presentationTime;\n};\n\nconst WebVTTParser = {\n parse: function(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n let re = /\\r\\n|\\n\\r|\\n|\\r/g;\n // Uint8Array.prototype.reduce is not implemented in IE11\n let vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(re, '\\n').split('\\n');\n\n let cueTime = '00:00.000';\n let mpegTs = 0;\n let localTime = 0;\n let presentationTime = 0;\n let cues = [];\n let parsingError;\n let inHeader = true;\n // let VTTCue = VTTCue || window.TextTrackCue;\n\n // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.\n let parser = new VTTParser();\n\n parser.oncue = function(cue) {\n // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n let currCC = vttCCs[cc];\n let cueOffset = vttCCs.ccOffset;\n\n // Update offsets for new discontinuities\n if (currCC && currCC.new) {\n if (localTime !== undefined) {\n // When local time is provided, offset = discontinuity start time - local time\n cueOffset = vttCCs.ccOffset = currCC.start;\n } else {\n calculateOffset(vttCCs, cc, presentationTime);\n }\n }\n\n if (presentationTime) {\n // If we have MPEGTS, offset = presentation time + discontinuity offset\n cueOffset = presentationTime + vttCCs.ccOffset - vttCCs.presentationOffset;\n }\n\n cue.startTime += cueOffset - localTime;\n cue.endTime += cueOffset - localTime;\n\n // Create a unique hash id for a cue based on start/end times and text.\n // This helps timeline-controller to avoid showing repeated captions.\n cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);\n\n // Fix encoding of special characters. TODO: Test with all sorts of weird characters.\n cue.text = decodeURIComponent(encodeURIComponent(cue.text));\n if (cue.endTime > 0) {\n cues.push(cue);\n }\n };\n\n parser.onparsingerror = function(e) {\n parsingError = e;\n };\n\n parser.onflush = function() {\n if (parsingError && errorCallBack) {\n errorCallBack(parsingError);\n return;\n }\n callBack(cues);\n };\n\n // Go through contents line by line.\n vttLines.forEach(line => {\n if (inHeader) {\n // Look for X-TIMESTAMP-MAP in header.\n if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n // Once found, no more are allowed anyway, so stop searching.\n inHeader = false;\n // Extract LOCAL and MPEGTS.\n line.substr(16).split(',').forEach(timestamp => {\n if (startsWith(timestamp, 'LOCAL:')) {\n cueTime = timestamp.substr(6);\n } else if (startsWith(timestamp, 'MPEGTS:')) {\n mpegTs = parseInt(timestamp.substr(7));\n }\n });\n try {\n // Calculate subtitle offset in milliseconds.\n // If sync PTS is less than zero, we have a 33-bit wraparound, which is fixed by adding 2^33 = 8589934592.\n syncPTS = syncPTS < 0 ? syncPTS + 8589934592 : syncPTS;\n // Adjust MPEGTS by sync PTS.\n mpegTs -= syncPTS;\n // Convert cue time to seconds\n localTime = cueString2millis(cueTime) / 1000;\n // Convert MPEGTS to seconds from 90kHz.\n presentationTime = mpegTs / 90000;\n\n if (localTime === -1) {\n parsingError = new Error(`Malformed X-TIMESTAMP-MAP: ${line}`);\n }\n }\n catch(e) {\n parsingError = new Error(`Malformed X-TIMESTAMP-MAP: ${line}`);\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line+'\\n');\n });\n\n parser.flush();\n }\n};\n\nexport default WebVTTParser;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/webvtt-parser.js","/*\n * Timeline Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport Cea608Parser from '../utils/cea-608-parser';\nimport OutputFilter from '../utils/output-filter';\nimport WebVTTParser from '../utils/webvtt-parser';\nimport {logger} from '../utils/logger';\n\nfunction clearCurrentCues(track) {\n if (track && track.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\nfunction reuseVttTextTrack(inUseTrack, manifestTrack) {\n return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);\n}\n\nfunction intersection(x1, x2, y1, y2) {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\n\nclass TimelineController extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.MEDIA_ATTACHING,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_USERDATA,\n Event.FRAG_DECRYPTED,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_LOADED,\n Event.FRAG_LOADED,\n Event.LEVEL_SWITCHING,\n Event.INIT_PTS_FOUND);\n\n this.hls = hls;\n this.config = hls.config;\n this.enabled = true;\n this.Cues = hls.config.cueHandler;\n this.textTracks = [];\n this.tracks = [];\n this.unparsedVttFrags = [];\n this.initPTS = undefined;\n this.cueRanges = [];\n\n if (this.config.enableCEA708Captions)\n {\n var channel1 = new OutputFilter(this, 1);\n var channel2 = new OutputFilter(this, 2);\n\n this.cea608Parser = new Cea608Parser(0, channel1, channel2);\n }\n }\n\n addCues(channel, startTime, endTime, screen) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n const ranges = this.cueRanges;\n let merged = false;\n for (let i = ranges.length; i--;) {\n let cueRange = ranges[i];\n let overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if ((overlap / (endTime - startTime)) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n ranges.push([startTime, endTime]);\n }\n this.Cues.newCue(this[channel], startTime, endTime, screen);\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n onInitPtsFound(data) {\n if (typeof this.initPTS === 'undefined') {\n this.initPTS = data.initPTS;\n }\n\n // Due to asynchrony, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (this.unparsedVttFrags.length) {\n this.unparsedVttFrags.forEach(frag => {\n this.onFragLoaded(frag);\n });\n this.unparsedVttFrags = [];\n }\n }\n\n getExistingTrack(channelNumber) {\n const media = this.media;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n let textTrack = media.textTracks[i];\n let propName = 'textTrack' + channelNumber;\n if (textTrack[propName] === true) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n sendAddTrackEvent(track, media) {\n var e = null;\n try {\n e = new window.Event('addtrack');\n } catch (err) {\n //for IE11\n e = document.createEvent('Event');\n e.initEvent('addtrack', false, false);\n }\n e.track = track;\n media.dispatchEvent(e);\n }\n\n createCaptionsTrack(track) {\n let trackVar = 'textTrack' + track;\n if (!this[trackVar]) {\n //Enable reuse of existing text track.\n let existingTrack = this.getExistingTrack(track);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', this.config['captionsTextTrack' + track + 'Label'], this.config.captionsTextTrack1LanguageCode);\n if (textTrack) {\n textTrack[trackVar] = true;\n this[trackVar] = textTrack;\n }\n } else {\n this[trackVar] = existingTrack;\n clearCurrentCues(this[trackVar]);\n\n this.sendAddTrackEvent(this[trackVar], this.media);\n }\n }\n }\n\n createTextTrack(kind, label, lang) {\n const media = this.media;\n if (media)\n {\n return media.addTextTrack(kind, label, lang);\n }\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n onMediaAttaching(data) {\n this.media = data.media;\n this._cleanTracks();\n }\n\n onMediaDetaching() {\n clearCurrentCues(this.textTrack1);\n clearCurrentCues(this.textTrack2);\n }\n\n onManifestLoading()\n {\n this.lastSn = -1; // Detect discontiguity in fragment parsing\n this.prevCC = -1;\n this.vttCCs = {ccOffset: 0, presentationOffset: 0}; // Detect discontinuity in subtitle manifests\n this._cleanTracks();\n\n }\n\n _cleanTracks() {\n // clear outdated subtitles\n const media = this.media;\n if (media) {\n const textTracks = media.textTracks;\n if (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n clearCurrentCues(textTracks[i]);\n }\n }\n }\n }\n\n onManifestLoaded(data) {\n this.textTracks = [];\n this.unparsedVttFrags = this.unparsedVttFrags || [];\n this.initPTS = undefined;\n this.cueRanges = [];\n\n if (this.config.enableWebVTT) {\n this.tracks = data.subtitles || [];\n const inUseTracks = this.media ? this.media.textTracks : [];\n\n this.tracks.forEach((track, index) => {\n let textTrack;\n if (index < inUseTracks.length) {\n const inUseTrack = inUseTracks[index];\n // Reuse tracks with the same label, but do not reuse 608/708 tracks\n if (reuseVttTextTrack(inUseTrack, track)) {\n textTrack = inUseTrack;\n }\n }\n if (!textTrack) {\n textTrack = this.createTextTrack('subtitles', track.name, track.lang);\n }\n textTrack.mode = track.default ? 'showing' : 'hidden';\n this.textTracks.push(textTrack);\n });\n }\n }\n\n onLevelSwitching() {\n this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';\n }\n\n onFragLoaded(data) {\n let frag = data.frag,\n payload = data.payload;\n if (frag.type === 'main') {\n var sn = frag.sn;\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (sn !== this.lastSn + 1) {\n const cea608Parser = this.cea608Parser;\n if (cea608Parser) {\n cea608Parser.reset();\n }\n }\n this.lastSn = sn;\n }\n // If fragment is subtitle type, parse as WebVTT.\n else if (frag.type === 'subtitle') {\n if (payload.byteLength) {\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived.\n if (typeof this.initPTS === 'undefined') {\n this.unparsedVttFrags.push(data);\n return;\n }\n\n var decryptData = frag.decryptdata;\n // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.\n if ((decryptData == null) || (decryptData.key == null) || (decryptData.method !== 'AES-128')) {\n this._parseVTTs(frag, payload);\n }\n }\n else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, {success: false, frag: frag});\n }\n }\n }\n\n _parseVTTs(frag, payload) {\n let vttCCs = this.vttCCs;\n if (!vttCCs[frag.cc]) {\n vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };\n this.prevCC = frag.cc;\n }\n let textTracks = this.textTracks,\n hls = this.hls;\n\n // Parse the WebVTT file contents.\n WebVTTParser.parse(payload, this.initPTS, vttCCs, frag.cc, function (cues) {\n const currentTrack = textTracks[frag.trackId];\n // Add cues and trigger event with success true.\n cues.forEach(cue => {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n if (!currentTrack.cues.getCueById(cue.id)) {\n try {\n currentTrack.addCue(cue);\n } catch (err) {\n const textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);\n textTrackCue.id = cue.id;\n currentTrack.addCue(textTrackCue);\n }\n }\n });\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, {success: true, frag: frag});\n },\n function (e) {\n // Something went wrong while parsing. Trigger event with success false.\n logger.log(`Failed to parse VTT cue: ${e}`);\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, {success: false, frag: frag});\n });\n }\n\n onFragDecrypted(data) {\n var decryptedData = data.payload,\n frag = data.frag;\n\n if (frag.type === 'subtitle') {\n if (typeof this.initPTS === 'undefined') {\n this.unparsedVttFrags.push(data);\n return;\n }\n\n this._parseVTTs(frag, decryptedData);\n }\n }\n\n onFragParsingUserdata(data) {\n // push all of the CEA-708 messages into the interpreter\n // immediately. It will create the proper timestamps based on our PTS value\n if (this.enabled && this.config.enableCEA708Captions) {\n for (var i=0; i<data.samples.length; i++) {\n var ccdatas = this.extractCea608Data(data.samples[i].bytes);\n this.cea608Parser.addData(data.samples[i].pts, ccdatas);\n }\n }\n }\n\n extractCea608Data(byteArray) {\n var count = byteArray[0] & 31;\n var position = 2;\n var tmpByte, ccbyte1, ccbyte2, ccValid, ccType;\n var actualCCBytes = [];\n\n for (var j = 0; j < count; j++) {\n tmpByte = byteArray[position++];\n ccbyte1 = 0x7F & byteArray[position++];\n ccbyte2 = 0x7F & byteArray[position++];\n ccValid = (4 & tmpByte) !== 0;\n ccType = 3 & tmpByte;\n\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n\n if (ccValid) {\n if (ccType === 0) // || ccType === 1\n {\n actualCCBytes.push(ccbyte1);\n actualCCBytes.push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\n\nexport default TimelineController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/timeline-controller.js","/*\n * subtitle track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\n\nfunction filterSubtitleTracks(textTrackList) {\n let tracks = [];\n for (let i = 0; i < textTrackList.length; i++) {\n if (textTrackList[i].kind === 'subtitles') {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nclass SubtitleTrackController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_LOADED,\n Event.SUBTITLE_TRACK_LOADED);\n this.tracks = [];\n this.trackId = -1;\n this.media = undefined;\n this.subtitleDisplay = false;\n }\n\n _onTextTracksChanged() {\n // Media is undefined when switching streams via loadSource()\n if (!this.media) {\n return;\n }\n\n let trackId = -1;\n let tracks = filterSubtitleTracks(this.media.textTracks);\n for (let id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'showing') {\n trackId = id;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n this.subtitleTrack = trackId;\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n onMediaAttached(data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n if (this.queuedDefaultTrack !== undefined) {\n this.subtitleTrack = this.queuedDefaultTrack;\n delete this.queuedDefaultTrack;\n }\n\n this.trackChangeListener = this._onTextTracksChanged.bind(this);\n\n this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);\n if (this.useTextTrackPolling) {\n this.subtitlePollingInterval = setInterval(() => {\n this.trackChangeListener();\n }, 500);\n } else {\n this.media.textTracks.addEventListener('change', this.trackChangeListener);\n }\n }\n\n onMediaDetaching() {\n if (!this.media) {\n return;\n }\n if (this.useTextTrackPolling) {\n clearInterval(this.subtitlePollingInterval);\n } else {\n this.media.textTracks.removeEventListener('change', this.trackChangeListener);\n }\n\n this.media = undefined;\n }\n\n // Reset subtitle tracks on manifest loading\n onManifestLoading() {\n this.tracks = [];\n this.trackId = -1;\n }\n\n // Fired whenever a new manifest is loaded.\n onManifestLoaded(data) {\n let tracks = data.subtitles || [];\n this.tracks = tracks;\n this.trackId = -1;\n this.hls.trigger(Event.SUBTITLE_TRACKS_UPDATED, {subtitleTracks : tracks});\n\n // loop through available subtitle tracks and autoselect default if needed\n // TODO: improve selection logic to handle forced, etc\n tracks.forEach(track => {\n if (track.default) {\n // setting this.subtitleTrack will trigger internal logic\n // if media has not been attached yet, it will fail\n // we keep a reference to the default track id\n // and we'll set subtitleTrack when onMediaAttached is triggered\n if (this.media) {\n this.subtitleTrack = track.id;\n } else {\n this.queuedDefaultTrack = track.id;\n }\n }\n });\n }\n\n // Trigger subtitle track playlist reload.\n onTick() {\n const trackId = this.trackId;\n const subtitleTrack = this.tracks[trackId];\n if (!subtitleTrack) {\n return;\n }\n\n const details = subtitleTrack.details;\n // check if we need to load playlist for this subtitle Track\n if (details === undefined || details.live === true) {\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`(re)loading playlist for subtitle track ${trackId}`);\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADING, {url: subtitleTrack.url, id: trackId});\n }\n }\n\n onSubtitleTrackLoaded(data) {\n if (data.id < this.tracks.length) {\n logger.log(`subtitle track ${data.id} loaded`);\n this.tracks[data.id].details = data.details;\n // check if current playlist is a live playlist\n if (data.details.live && !this.timer) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n this.timer = setInterval(() => {\n this.onTick();\n }, 1000 * data.details.targetduration, this);\n }\n if (!data.details.live && this.timer) {\n // playlist is not live and timer is armed : stopping it\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks() {\n return this.tracks;\n }\n\n /** get index of the selected subtitle track (index in subtitle track lists) **/\n get subtitleTrack() {\n return this.trackId;\n }\n\n /** select a subtitle track, based on its index in subtitle track lists**/\n set subtitleTrack(subtitleTrackId) {\n if (this.trackId !== subtitleTrackId) {// || this.tracks[subtitleTrackId].details === undefined) {\n this.setSubtitleTrackInternal(subtitleTrackId);\n }\n }\n\n setSubtitleTrackInternal(newId) {\n // check if level idx is valid\n if (newId < -1 || newId >= this.tracks.length) {\n return;\n }\n\n // stopping live reloading timer if any\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n\n let textTracks = filterSubtitleTracks(this.media.textTracks);\n\n // hide currently enabled subtitle track\n if (this.trackId !== -1 && this.subtitleDisplay) {\n textTracks[this.trackId].mode = 'hidden';\n }\n\n this.trackId = newId;\n logger.log(`switching to subtitle track ${newId}`);\n this.hls.trigger(Event.SUBTITLE_TRACK_SWITCH, {id: newId});\n\n if (newId === -1) {\n return;\n }\n\n let subtitleTrack = this.tracks[newId];\n if (this.subtitleDisplay) {\n textTracks[newId].mode = 'showing';\n }\n\n // check if we need to load playlist for this subtitle Track\n let details = subtitleTrack.details;\n if (details === undefined || details.live === true) {\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`(re)loading playlist for subtitle track ${newId}`);\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADING, {url: subtitleTrack.url, id: newId});\n }\n }\n}\n\nexport default SubtitleTrackController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/subtitle-track-controller.js","/*\n * Subtitle Stream Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\nimport Decrypter from '../crypt/decrypter';\n\nconst State = {\n STOPPED : 'STOPPED',\n IDLE : 'IDLE',\n KEY_LOADING : 'KEY_LOADING',\n FRAG_LOADING : 'FRAG_LOADING'\n};\n\nclass SubtitleStreamController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.ERROR,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.SUBTITLE_TRACKS_UPDATED,\n Event.SUBTITLE_TRACK_SWITCH,\n Event.SUBTITLE_TRACK_LOADED,\n Event.SUBTITLE_FRAG_PROCESSED);\n this.config = hls.config;\n this.vttFragSNsProcessed = {};\n this.vttFragQueues = undefined;\n this.currentlyProcessing = null;\n this.state = State.STOPPED;\n this.currentTrackId = -1;\n this.ticks = 0;\n this.decrypter = new Decrypter(hls.observer, hls.config);\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n this.state = State.STOPPED;\n }\n\n // Remove all queued items and create a new, empty queue for each track.\n clearVttFragQueues() {\n this.vttFragQueues = {};\n this.tracks.forEach(track => {\n this.vttFragQueues[track.id] = [];\n });\n }\n\n // If no frag is being processed and queue isn't empty, initiate processing of next frag in line.\n nextFrag() {\n if(this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) {\n let frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift();\n this.fragCurrent = frag;\n this.hls.trigger(Event.FRAG_LOADING, {frag: frag});\n this.state = State.FRAG_LOADING;\n }\n }\n\n // When fragment has finished processing, add sn to list of completed if successful.\n onSubtitleFragProcessed(data) {\n if(data.success) {\n this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn);\n }\n this.currentlyProcessing = null;\n this.state = State.IDLE;\n this.nextFrag();\n }\n\n onMediaAttached() {\n this.state = State.IDLE;\n }\n\n // If something goes wrong, procede to next frag, if we were processing one.\n onError(data) {\n let frag = data.frag;\n // don't handle frag error not related to subtitle fragment\n if (frag && frag.type !== 'subtitle') {\n return;\n }\n if(this.currentlyProcessing) {\n this.currentlyProcessing = null;\n this.nextFrag();\n }\n }\n\n tick() {\n this.ticks++;\n if (this.ticks === 1) {\n this.doTick();\n if (this.ticks > 1) {\n setTimeout(() => { this.tick(); }, 1);\n }\n this.ticks = 0;\n }\n }\n\n doTick() {\n switch(this.state) {\n case State.IDLE:\n const tracks = this.tracks;\n let trackId = this.currentTrackId;\n\n const processedFragSNs = this.vttFragSNsProcessed[trackId],\n fragQueue = this.vttFragQueues[trackId],\n currentFragSN = !!this.currentlyProcessing ? this.currentlyProcessing.sn : -1;\n\n const alreadyProcessed = function(frag) {\n return processedFragSNs.indexOf(frag.sn) > -1;\n };\n\n const alreadyInQueue = function(frag) {\n return fragQueue.some(fragInQueue => {return fragInQueue.sn === frag.sn;});\n };\n\n // exit if tracks don't exist\n if (!tracks) {\n break;\n }\n var trackDetails;\n\n if (trackId < tracks.length) {\n trackDetails = tracks[trackId].details;\n }\n\n if (typeof trackDetails === 'undefined') {\n break;\n }\n\n // Add all fragments that haven't been, aren't currently being and aren't waiting to be processed, to queue.\n trackDetails.fragments.forEach(frag => {\n if(!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) {\n // Load key if subtitles are encrypted\n if ((frag.decryptdata && frag.decryptdata.uri != null) && (frag.decryptdata.key == null)) {\n logger.log(`Loading key for ${frag.sn}`);\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, {frag: frag});\n } else {\n // Frags don't know their subtitle track ID, so let's just add that...\n frag.trackId = trackId;\n fragQueue.push(frag);\n this.nextFrag();\n }\n }\n });\n }\n }\n\n // Got all new subtitle tracks.\n onSubtitleTracksUpdated(data) {\n logger.log('subtitle tracks updated');\n this.tracks = data.subtitleTracks;\n this.clearVttFragQueues();\n this.vttFragSNsProcessed = {};\n this.tracks.forEach(track => {\n this.vttFragSNsProcessed[track.id] = [];\n });\n }\n\n onSubtitleTrackSwitch(data) {\n this.currentTrackId = data.id;\n this.clearVttFragQueues();\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded() {\n this.tick();\n }\n\n onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded(data) {\n var fragCurrent = this.fragCurrent,\n decryptData = data.frag.decryptdata;\n let fragLoaded = data.frag,\n hls = this.hls;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n data.frag.type === 'subtitle' &&\n fragCurrent.sn === data.frag.sn) {\n // check to see if the payload needs to be decrypted\n if ((data.payload.byteLength > 0) && (decryptData != null) && (decryptData.key != null) && (decryptData.method === 'AES-128')) {\n var startTime;\n try {\n startTime = performance.now();\n } catch (error) {\n startTime = Date.now();\n }\n // decrypt the subtitles\n this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function(decryptedData) {\n var endTime;\n try {\n endTime = performance.now();\n } catch (error) {\n endTime = Date.now();\n }\n hls.trigger(Event.FRAG_DECRYPTED, { frag: fragLoaded, payload : decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });\n });\n }\n }\n }\n}\nexport default SubtitleStreamController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/subtitle-stream-controller.js","/**\n * HLS config\n */\n\nimport AbrController from './controller/abr-controller';\nimport BufferController from './controller/buffer-controller';\nimport CapLevelController from './controller/cap-level-controller';\nimport FPSController from './controller/fps-controller';\nimport XhrLoader from './utils/xhr-loader';\n//import FetchLoader from './utils/fetch-loader';\n\nimport AudioTrackController from './controller/audio-track-controller';\nimport AudioStreamController from './controller/audio-stream-controller';\n\nimport * as Cues from './utils/cues';\nimport TimelineController from './controller/timeline-controller';\nimport SubtitleTrackController from './controller/subtitle-track-controller';\nimport SubtitleStreamController from './controller/subtitle-stream-controller';\n\nexport var hlsDefaultConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: undefined, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.5, // used by stream-controller\n maxSeekHole: 2, // used by stream-controller\n lowBufferWatchdogPeriod: 0.5, // used by stream-controller\n highBufferWatchdogPeriod: 3, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry : 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount:3, // used by stream-controller\n liveMaxLatencyDurationCount: Infinity, // used by stream-controller\n liveSyncDuration: undefined, // used by stream-controller\n liveMaxLatencyDuration: undefined, // used by stream-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by demuxer\n enableSoftwareAES: true, // used by decrypter\n manifestLoadingTimeOut: 10000, // used by playlist-loader\n manifestLoadingMaxRetry: 1, // used by playlist-loader\n manifestLoadingRetryDelay: 1000, // used by playlist-loader\n manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n startLevel: undefined, // used by level-controller\n levelLoadingTimeOut: 10000, // used by playlist-loader\n levelLoadingMaxRetry: 4, // used by playlist-loader\n levelLoadingRetryDelay: 1000, // used by playlist-loader\n levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n fragLoadingTimeOut: 20000, // used by fragment-loader\n fragLoadingMaxRetry: 6, // used by fragment-loader\n fragLoadingRetryDelay: 1000, // used by fragment-loader\n fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader\n fragLoadingLoopThreshold: 3, // used by stream-controller\n startFragPrefetch: false, // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000, // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller\n appendErrorMaxRetry: 3, // used by buffer-controller\n loader: XhrLoader,\n //loader: FetchLoader,\n fLoader: undefined,\n pLoader: undefined,\n xhrSetup: undefined,\n fetchSetup: undefined,\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n fpsController: FPSController,\n stretchShortVideoTrack: false, // used by mp4-remuxer\n maxAudioFramesDrift :1, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrBandWidthFactor : 0.95, // used by abr-controller\n abrBandWidthUpFactor : 0.7, // used by abr-controller\n abrMaxWithRealBitrate : false, // used by abr-controller\n maxStarvationDelay : 4, // used by abr-controller\n maxLoadingDelay : 4, // used by abr-controller\n minAutoBitrate: 0 // used by hls\n};\n\nif (typeof __SUBTITLE__ !== 'undefined' && __SUBTITLE__) {\n hlsDefaultConfig.subtitleStreamController = SubtitleStreamController;\n hlsDefaultConfig.subtitleTrackController = SubtitleTrackController;\n hlsDefaultConfig.timelineController = TimelineController;\n hlsDefaultConfig.cueHandler = Cues;\n hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller\n hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller\n hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller\n hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller\n hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller\n hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller\n}\n\nif (typeof __ALT_AUDIO__ !== 'undefined' && __ALT_AUDIO__) {\n hlsDefaultConfig.audioStreamController = AudioStreamController;\n hlsDefaultConfig.audioTrackController = AudioTrackController;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/config.js","/**\n * HLS interface\n */\nimport URLToolkit from 'url-toolkit';\nimport Event from './events';\nimport {ErrorTypes, ErrorDetails} from './errors';\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport {getMediaSource} from './helper/mediasource-helper';\nimport {logger, enableLogs} from './utils/logger';\nimport EventEmitter from 'events';\nimport {hlsDefaultConfig} from './config';\n\nexport default class Hls {\n static get version() {\n return __VERSION__;\n }\n static isSupported() {\n const mediaSource = getMediaSource();\n const sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;\n const isTypeSupported = mediaSource &&\n typeof mediaSource.isTypeSupported === 'function' &&\n mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\n\n // if SourceBuffer is exposed ensure its API is valid\n // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBufferValidAPI = !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function');\n return isTypeSupported && sourceBufferValidAPI;\n }\n\n static get Events() {\n return Event;\n }\n\n static get ErrorTypes() {\n return ErrorTypes;\n }\n\n static get ErrorDetails() {\n return ErrorDetails;\n }\n\n static get DefaultConfig() {\n if(!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n return Hls.defaultConfig;\n }\n\n static set DefaultConfig(defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n constructor(config = {}) {\n var defaultConfig = Hls.DefaultConfig;\n\n if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {\n throw new Error('Illegal hls.js config: don\\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');\n }\n\n for (var prop in defaultConfig) {\n if (prop in config) { continue; }\n config[prop] = defaultConfig[prop];\n }\n\n if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be gt \"liveSyncDurationCount\"');\n }\n\n if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be gt \"liveSyncDuration\"');\n }\n\n enableLogs(config.debug);\n this.config = config;\n this._autoLevelCapping = -1;\n // observer setup\n var observer = this.observer = new EventEmitter();\n observer.trigger = function trigger (event, ...data) {\n observer.emit(event, event, ...data);\n };\n\n observer.off = function off (event, ...data) {\n observer.removeListener(event, ...data);\n };\n this.on = observer.on.bind(observer);\n this.off = observer.off.bind(observer);\n this.trigger = observer.trigger.bind(observer);\n\n // core controllers and network loaders\n const abrController = this.abrController = new config.abrController(this);\n const bufferController = new config.bufferController(this);\n const capLevelController = new config.capLevelController(this);\n const fpsController = new config.fpsController(this);\n const playListLoader = new PlaylistLoader(this);\n const fragmentLoader = new FragmentLoader(this);\n const keyLoader = new KeyLoader(this);\n const id3TrackController = new ID3TrackController(this);\n\n // network controllers\n const levelController = this.levelController = new LevelController(this);\n const streamController = this.streamController = new StreamController(this);\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this));\n }\n this.networkControllers = networkControllers;\n\n let coreComponents = [ playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n let audioTrackController = new Controller(this);\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n let subtitleTrackController = new Controller(this);\n this.subtitleTrackController = subtitleTrackController;\n coreComponents.push(subtitleTrackController);\n }\n\n // optional subtitle controller\n [config.subtitleStreamController, config.timelineController].forEach(Controller => {\n if (Controller) {\n coreComponents.push(new Controller(this));\n }\n });\n this.coreComponents = coreComponents;\n }\n\n destroy() {\n logger.log('destroy');\n this.trigger(Event.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {component.destroy();});\n this.url = null;\n this.observer.removeAllListeners();\n this._autoLevelCapping = -1;\n }\n\n attachMedia(media) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(Event.MEDIA_ATTACHING, {media: media});\n }\n\n detachMedia() {\n logger.log('detachMedia');\n this.trigger(Event.MEDIA_DETACHING);\n this.media = null;\n }\n\n loadSource(url) {\n url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });\n logger.log(`loadSource:${url}`);\n this.url = url;\n // when attaching to a source URL, trigger a playlist load\n this.trigger(Event.MANIFEST_LOADING, {url: url});\n }\n\n startLoad(startPosition=-1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach(controller => {controller.startLoad(startPosition);});\n }\n\n stopLoad() {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {controller.stopLoad();});\n }\n\n swapAudioCodec() {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n recoverMediaError() {\n logger.log('recoverMediaError');\n var media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n }\n\n /** Return all quality levels **/\n get levels() {\n return this.levelController.levels;\n }\n\n /** Return current playback quality level **/\n get currentLevel() {\n return this.streamController.currentLevel;\n }\n\n /* set quality level immediately (-1 for automatic level selection) */\n set currentLevel(newLevel) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /** Return next playback quality level (quality level of next fragment) **/\n get nextLevel() {\n return this.streamController.nextLevel;\n }\n\n /* set quality level for next fragment (-1 for automatic level selection) */\n set nextLevel(newLevel) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /** Return the quality level of current/last loaded fragment **/\n get loadLevel() {\n return this.levelController.level;\n }\n\n /* set quality level for current/next loaded fragment (-1 for automatic level selection) */\n set loadLevel(newLevel) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /** Return the quality level of next loaded fragment **/\n get nextLoadLevel() {\n return this.levelController.nextLoadLevel;\n }\n\n /** set quality level of next loaded fragment **/\n set nextLoadLevel(level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /** Return first level (index of first level referenced in manifest)\n **/\n get firstLevel() {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /** set first level (index of first level referenced in manifest)\n **/\n set firstLevel(newLevel) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /** Return start level (level of first fragment that will be played back)\n if not overrided by user, first level appearing in manifest will be used as start level\n if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)\n **/\n get startLevel() {\n return this.levelController.startLevel;\n }\n\n /** set start level (level of first fragment that will be played back)\n if not overrided by user, first level appearing in manifest will be used as start level\n if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)\n **/\n set startLevel(newLevel) {\n logger.log(`set startLevel:${newLevel}`);\n const hls = this;\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel,hls.minAutoLevel);\n }\n hls.levelController.startLevel = newLevel;\n }\n\n /** Return the capping/max level value that could be used by automatic level selection algorithm **/\n get autoLevelCapping() {\n return this._autoLevelCapping;\n }\n\n /** set the capping/max level value that could be used by automatic level selection algorithm **/\n set autoLevelCapping(newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n\n /* check if we are in automatic level selection mode */\n get autoLevelEnabled() {\n return (this.levelController.manualLevel === -1);\n }\n\n /* return manual level */\n get manualLevel() {\n return this.levelController.manualLevel;\n }\n\n /* return min level selectable in auto mode according to config.minAutoBitrate */\n get minAutoLevel() {\n let hls = this, levels = hls.levels, minAutoBitrate = hls.config.minAutoBitrate, len = levels ? levels.length : 0;\n for (let i = 0; i < len; i++) {\n const levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate,levels[i].bitrate) : levels[i].bitrate;\n if (levelNextBitrate > minAutoBitrate) {\n return i;\n }\n }\n return 0;\n }\n\n /* return max level selectable in auto mode according to autoLevelCapping */\n get maxAutoLevel() {\n const hls = this;\n const levels = hls.levels;\n const autoLevelCapping = hls.autoLevelCapping;\n let maxAutoLevel;\n if (autoLevelCapping=== -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n return maxAutoLevel;\n }\n\n // return next auto level\n get nextAutoLevel() {\n const hls = this;\n // ensure next auto level is between min and max auto level\n return Math.min(Math.max(hls.abrController.nextAutoLevel,hls.minAutoLevel),hls.maxAutoLevel);\n }\n\n // this setter is used to force next auto level\n // this is useful to force a switch down in auto mode : in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n // forced value is valid for one fragment. upon succesful frag loading at forced level, this value will be resetted to -1 by ABR controller\n set nextAutoLevel(nextLevel) {\n const hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel,nextLevel);\n }\n\n /** get alternate audio tracks list from playlist **/\n get audioTracks() {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /** get index of the selected audio track (index in audio track lists) **/\n get audioTrack() {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /** select an audio track, based on its index in audio track lists**/\n set audioTrack(audioTrackId) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n get liveSyncPosition() {\n return this.streamController.liveSyncPosition;\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /** get index of the selected subtitle track (index in subtitle track lists) **/\n get subtitleTrack() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /** select an subtitle track, based on its index in subtitle track lists**/\n set subtitleTrack(subtitleTrackId) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n get subtitleDisplay() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n set subtitleDisplay(value) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/hls.js","function webpackBootstrapFunc (modules) {\n/******/ // The module cache\n/******/ var installedModules = {};\n\n/******/ // The require function\n/******/ function __webpack_require__(moduleId) {\n\n/******/ // Check if module is in cache\n/******/ if(installedModules[moduleId])\n/******/ return installedModules[moduleId].exports;\n\n/******/ // Create a new module (and put it into the cache)\n/******/ var module = installedModules[moduleId] = {\n/******/ i: moduleId,\n/******/ l: false,\n/******/ exports: {}\n/******/ };\n\n/******/ // Execute the module function\n/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ // Flag the module as loaded\n/******/ module.l = true;\n\n/******/ // Return the exports of the module\n/******/ return module.exports;\n/******/ }\n\n/******/ // expose the modules object (__webpack_modules__)\n/******/ __webpack_require__.m = modules;\n\n/******/ // expose the module cache\n/******/ __webpack_require__.c = installedModules;\n\n/******/ // identity function for calling harmony imports with the correct context\n/******/ __webpack_require__.i = function(value) { return value; };\n\n/******/ // define getter function for harmony exports\n/******/ __webpack_require__.d = function(exports, name, getter) {\n/******/ if(!__webpack_require__.o(exports, name)) {\n/******/ Object.defineProperty(exports, name, {\n/******/ configurable: false,\n/******/ enumerable: true,\n/******/ get: getter\n/******/ });\n/******/ }\n/******/ };\n\n/******/ // getDefaultExport function for compatibility with non-harmony modules\n/******/ __webpack_require__.n = function(module) {\n/******/ var getter = module && module.__esModule ?\n/******/ function getDefault() { return module['default']; } :\n/******/ function getModuleExports() { return module; };\n/******/ __webpack_require__.d(getter, 'a', getter);\n/******/ return getter;\n/******/ };\n\n/******/ // Object.prototype.hasOwnProperty.call\n/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n/******/ // __webpack_public_path__\n/******/ __webpack_require__.p = \"/\";\n\n/******/ // on error function for async loading\n/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)\n return f.default || f // try to call default if defined to also support babel esmodule exports\n}\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction getModuleDependencies (module) {\n var retval = []\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n\n var webpackRequireName = wrapperSignature[1]\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + '\\\\((\\/\\\\*.*?\\\\*\\/)?\\s?.*?([\\\\.|\\\\-|\\\\w|\\/|@]+).*?\\\\)', 'g') // additional chars when output.pathinfo is true\n var match\n while ((match = re.exec(fnString))) {\n retval.push(match[3])\n }\n return retval\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = [moduleId]\n var requiredModules = []\n var seenModules = {}\n\n while (modulesQueue.length) {\n var moduleToCheck = modulesQueue.pop()\n if (seenModules[moduleToCheck] || !sources[moduleToCheck]) continue\n seenModules[moduleToCheck] = true\n requiredModules.push(moduleToCheck)\n var newModules = getModuleDependencies(sources[moduleToCheck])\n modulesQueue = modulesQueue.concat(newModules)\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = __webpack_modules__\n\n var requiredModules = options.all ? Object.keys(sources) : getRequiredModules(sources, moduleId)\n var src = '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[id].toString() }).join(',') + '})(self);'\n\n var blob = new window.Blob([src], { type: 'text/javascript' })\n if (options.bare) { return blob }\n\n var URL = window.URL || window.webkitURL || window.mozURL || window.msURL\n\n var workerUrl = URL.createObjectURL(blob)\n var worker = new window.Worker(workerUrl)\n worker.objectURL = workerUrl\n\n return worker\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/webworkify-webpack/index.js\n// module id = 9\n// module chunks = 0","/* demuxer web worker.\n * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.\n * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.\n */\n\n import DemuxerInline from '../demux/demuxer-inline';\n import Event from '../events';\n import {enableLogs} from '../utils/logger';\n import EventEmitter from 'events';\n\nvar DemuxerWorker = function (self) {\n // observer setup\n var observer = new EventEmitter();\n observer.trigger = function trigger (event, ...data) {\n observer.emit(event, event, ...data);\n };\n\n observer.off = function off (event, ...data) {\n observer.removeListener(event, ...data);\n };\n\n var forwardMessage = function(ev,data) {\n self.postMessage({event: ev, data:data });\n };\n\n self.addEventListener('message', function (ev) {\n var data = ev.data;\n //console.log('demuxer cmd:' + data.cmd);\n switch (data.cmd) {\n case 'init':\n let config = JSON.parse(data.config);\n self.demuxer = new DemuxerInline(observer, data.typeSupported, config, data.vendor);\n try {\n enableLogs(config.debug === true);\n } catch(err) {\n console.warn('demuxerWorker: unable to enable logs');\n }\n // signal end of worker init\n forwardMessage('init',null);\n break;\n case 'demux':\n self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset,data.discontinuity, data.trackSwitch,data.contiguous,data.duration,data.accurateTimeOffset,data.defaultInitPTS);\n break;\n default:\n break;\n }\n });\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)\n observer.on(Event.FRAG_PARSING_DATA, function(ev, data) {\n let transferable = [];\n let message = {event: ev, data:data};\n if (data.data1) {\n message.data1 = data.data1.buffer;\n transferable.push(data.data1.buffer);\n delete data.data1;\n }\n if (data.data2) {\n message.data2 = data.data2.buffer;\n transferable.push(data.data2.buffer);\n delete data.data2;\n }\n self.postMessage(message,transferable);\n });\n};\n\nexport default DemuxerWorker;\n\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/demuxer-worker.js"],"sourceRoot":""} \ No newline at end of file diff --git a/lib/hls.js/hls.min.js b/lib/hls.js/hls.min.js new file mode 100644 index 00000000..fabf9467 --- /dev/null +++ b/lib/hls.js/hls.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Hls=e():t.Hls=e()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var a=r[i]={i:i,l:!1,exports:{}};return t[i].call(a.exports,a,a.exports,e),a.l=!0,a.exports}var r={};return e.m=t,e.c=r,e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="/dist/",e(e.s=8)}([function(t,e,r){"use strict";function i(){}function a(t,e){return e="["+t+"] > "+e}function n(t){var e=self.console[t];return e?function(){for(var r=arguments.length,i=Array(r),n=0;n<r;n++)i[n]=arguments[n];i[0]&&(i[0]=a(t,i[0])),e.apply(self.console,i)}:i}function o(t){for(var e=arguments.length,r=Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];r.forEach(function(e){u[e]=t[e]?t[e].bind(t):n(e)})}r.d(e,"a",function(){return d}),r.d(e,"b",function(){return h});var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l={trace:i,debug:i,log:i,warn:i,info:i,error:i},u=l,d=function(t){if(!0===t||"object"===(void 0===t?"undefined":s(t))){o(t,"debug","log","info","warn","error");try{u.log()}catch(t){u=l}}else u=l},h=u},function(t,e,r){"use strict";e.a={MEDIA_ATTACHING:"hlsMediaAttaching",MEDIA_ATTACHED:"hlsMediaAttached",MEDIA_DETACHING:"hlsMediaDetaching",MEDIA_DETACHED:"hlsMediaDetached",BUFFER_RESET:"hlsBufferReset",BUFFER_CODECS:"hlsBufferCodecs",BUFFER_CREATED:"hlsBufferCreated",BUFFER_APPENDING:"hlsBufferAppending",BUFFER_APPENDED:"hlsBufferAppended",BUFFER_EOS:"hlsBufferEos",BUFFER_FLUSHING:"hlsBufferFlushing",BUFFER_FLUSHED:"hlsBufferFlushed",MANIFEST_LOADING:"hlsManifestLoading",MANIFEST_LOADED:"hlsManifestLoaded",MANIFEST_PARSED:"hlsManifestParsed",LEVEL_SWITCH:"hlsLevelSwitch",LEVEL_SWITCHING:"hlsLevelSwitching",LEVEL_SWITCHED:"hlsLevelSwitched",LEVEL_LOADING:"hlsLevelLoading",LEVEL_LOADED:"hlsLevelLoaded",LEVEL_UPDATED:"hlsLevelUpdated",LEVEL_PTS_UPDATED:"hlsLevelPtsUpdated",AUDIO_TRACKS_UPDATED:"hlsAudioTracksUpdated",AUDIO_TRACK_SWITCH:"hlsAudioTrackSwitch",AUDIO_TRACK_SWITCHING:"hlsAudioTrackSwitching",AUDIO_TRACK_SWITCHED:"hlsAudioTrackSwitched",AUDIO_TRACK_LOADING:"hlsAudioTrackLoading",AUDIO_TRACK_LOADED:"hlsAudioTrackLoaded",SUBTITLE_TRACKS_UPDATED:"hlsSubtitleTracksUpdated",SUBTITLE_TRACK_SWITCH:"hlsSubtitleTrackSwitch",SUBTITLE_TRACK_LOADING:"hlsSubtitleTrackLoading",SUBTITLE_TRACK_LOADED:"hlsSubtitleTrackLoaded",SUBTITLE_FRAG_PROCESSED:"hlsSubtitleFragProcessed",INIT_PTS_FOUND:"hlsInitPtsFound",FRAG_LOADING:"hlsFragLoading",FRAG_LOAD_PROGRESS:"hlsFragLoadProgress",FRAG_LOAD_EMERGENCY_ABORTED:"hlsFragLoadEmergencyAborted",FRAG_LOADED:"hlsFragLoaded",FRAG_DECRYPTED:"hlsFragDecrypted",FRAG_PARSING_INIT_SEGMENT:"hlsFragParsingInitSegment",FRAG_PARSING_USERDATA:"hlsFragParsingUserdata",FRAG_PARSING_METADATA:"hlsFragParsingMetadata",FRAG_PARSING_DATA:"hlsFragParsingData",FRAG_PARSED:"hlsFragParsed",FRAG_BUFFERED:"hlsFragBuffered",FRAG_CHANGED:"hlsFragChanged",FPS_DROP:"hlsFpsDrop",FPS_DROP_LEVEL_CAPPING:"hlsFpsDropLevelCapping",ERROR:"hlsError",DESTROYING:"hlsDestroying",KEY_LOADING:"hlsKeyLoading",KEY_LOADED:"hlsKeyLoaded",STREAM_STATE_TRANSITION:"hlsStreamStateTransition"}},function(t,e,r){"use strict";r.d(e,"b",function(){return i}),r.d(e,"a",function(){return a});var i={NETWORK_ERROR:"networkError",MEDIA_ERROR:"mediaError",MUX_ERROR:"muxError",OTHER_ERROR:"otherError"},a={MANIFEST_LOAD_ERROR:"manifestLoadError",MANIFEST_LOAD_TIMEOUT:"manifestLoadTimeOut",MANIFEST_PARSING_ERROR:"manifestParsingError",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"manifestIncompatibleCodecsError",LEVEL_LOAD_ERROR:"levelLoadError",LEVEL_LOAD_TIMEOUT:"levelLoadTimeOut",LEVEL_SWITCH_ERROR:"levelSwitchError",AUDIO_TRACK_LOAD_ERROR:"audioTrackLoadError",AUDIO_TRACK_LOAD_TIMEOUT:"audioTrackLoadTimeOut",FRAG_LOAD_ERROR:"fragLoadError",FRAG_LOOP_LOADING_ERROR:"fragLoopLoadingError",FRAG_LOAD_TIMEOUT:"fragLoadTimeOut",FRAG_DECRYPT_ERROR:"fragDecryptError",FRAG_PARSING_ERROR:"fragParsingError",REMUX_ALLOC_ERROR:"remuxAllocError",KEY_LOAD_ERROR:"keyLoadError",KEY_LOAD_TIMEOUT:"keyLoadTimeOut",BUFFER_ADD_CODEC_ERROR:"bufferAddCodecError",BUFFER_APPEND_ERROR:"bufferAppendError",BUFFER_APPENDING_ERROR:"bufferAppendingError",BUFFER_STALLED_ERROR:"bufferStalledError",BUFFER_FULL_ERROR:"bufferFullError",BUFFER_SEEK_OVER_HOLE:"bufferSeekOverHole",BUFFER_NUDGE_ON_STALL:"bufferNudgeOnStall",INTERNAL_EXCEPTION:"internalException"}},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.d(e,"b",function(){return n});var a=function(){function t(){i(this,t)}return t.isHeader=function(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},t.isFooter=function(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},t.getID3Data=function(e,r){for(var i=r,a=0;t.isHeader(e,r);){a+=10;a+=t._readSize(e,r+6),t.isFooter(e,r+10)&&(a+=10),r+=a}if(a>0)return e.subarray(i,i+a)},t._readSize=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},t.getTimeStamp=function(e){for(var r=t.getID3Frames(e),i=0;i<r.length;i++){var a=r[i];if(t.isTimeStampFrame(a))return t._readTimeStamp(a)}},t.isTimeStampFrame=function(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info},t._getFrameData=function(e){var r=String.fromCharCode(e[0],e[1],e[2],e[3]),i=t._readSize(e,4);return{type:r,size:i,data:e.subarray(10,10+i)}},t.getID3Frames=function(e){for(var r=0,i=[];t.isHeader(e,r);){var a=t._readSize(e,r+6);r+=10;for(var n=r+a;r+8<n;){var o=t._getFrameData(e.subarray(r)),s=t._decodeFrame(o);s&&i.push(s),r+=o.size+10}t.isFooter(e,r)&&(r+=10)}return i},t._decodeFrame=function(e){return"PRIV"===e.type?t._decodePrivFrame(e):"T"===e.type[0]?t._decodeTextFrame(e):"W"===e.type[0]?t._decodeURLFrame(e):void 0},t._readTimeStamp=function(t){if(8===t.data.byteLength){var e=new Uint8Array(t.data),r=1&e[3],i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}},t._decodePrivFrame=function(e){if(!(e.size<2)){var r=t._utf8ArrayToStr(e.data),i=new Uint8Array(e.data.subarray(r.length+1));return{key:e.type,info:r,data:i.buffer}}},t._decodeTextFrame=function(e){if(!(e.size<2)){if("TXXX"===e.type){var r=1,i=t._utf8ArrayToStr(e.data.subarray(r));r+=i.length+1;var a=t._utf8ArrayToStr(e.data.subarray(r));return{key:e.type,info:i,data:a}}var n=t._utf8ArrayToStr(e.data.subarray(1));return{key:e.type,data:n}}},t._decodeURLFrame=function(e){if("WXXX"===e.type){if(e.size<2)return;var r=1,i=t._utf8ArrayToStr(e.data.subarray(r));r+=i.length+1;var a=t._utf8ArrayToStr(e.data.subarray(r));return{key:e.type,info:i,data:a}}var n=t._utf8ArrayToStr(e.data);return{key:e.type,data:n}},t._utf8ArrayToStr=function(t){for(var e=t.length,r=void 0,i=void 0,a=void 0,n="",o=0;o<e;)if(0!==(r=t[o++])&&3!==r)switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(r);break;case 12:case 13:i=t[o++],n+=String.fromCharCode((31&r)<<6|63&i);break;case 14:i=t[o++],a=t[o++],n+=String.fromCharCode((15&r)<<12|(63&i)<<6|(63&a)<<0)}return n},t}(),n=a._utf8ArrayToStr;e.a=a},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var s=function(){function t(e,r){i(this,t),this.subtle=e,this.aesIV=r}return t.prototype.decrypt=function(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)},t}(),l=s,u=function(){function t(e,r){a(this,t),this.subtle=e,this.key=r}return t.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},t}(),d=u,h=function(){function t(){n(this,t),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.initTable()}return t.prototype.uint8ArrayToUint32Array_=function(t){for(var e=new DataView(t),r=new Uint32Array(4),i=0;i<4;i++)r[i]=e.getUint32(4*i);return r},t.prototype.initTable=function(){var t=this.sBox,e=this.invSBox,r=this.subMix,i=r[0],a=r[1],n=r[2],o=r[3],s=this.invSubMix,l=s[0],u=s[1],d=s[2],h=s[3],c=new Uint32Array(256),f=0,p=0,g=0;for(g=0;g<256;g++)c[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^255&v^99,t[f]=v,e[v]=f;var y=c[f],m=c[y],b=c[m],E=257*c[v]^16843008*v;i[f]=E<<24|E>>>8,a[f]=E<<16|E>>>16,n[f]=E<<8|E>>>24,o[f]=E,E=16843009*b^65537*m^257*y^16843008*f,l[v]=E<<24|E>>>8,u[v]=E<<16|E>>>16,d[v]=E<<8|E>>>24,h[v]=E,f?(f=y^c[c[c[b^y]]],p^=c[c[p]]):f=p=1}},t.prototype.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;i<e.length&&r;)r=e[i]===this.key[i],i++;if(!r){this.key=e;var a=this.keySize=e.length;if(4!==a&&6!==a&&8!==a)throw new Error("Invalid aes key size="+a);var n=this.ksRows=4*(a+6+1),o=void 0,s=void 0,l=this.keySchedule=new Uint32Array(n),u=this.invKeySchedule=new Uint32Array(n),d=this.sBox,h=this.rcon,c=this.invSubMix,f=c[0],p=c[1],g=c[2],v=c[3],y=void 0,m=void 0;for(o=0;o<n;o++)o<a?y=l[o]=e[o]:(m=y,o%a==0?(m=m<<8|m>>>24,m=d[m>>>24]<<24|d[m>>>16&255]<<16|d[m>>>8&255]<<8|d[255&m],m^=h[o/a|0]<<24):a>6&&o%a==4&&(m=d[m>>>24]<<24|d[m>>>16&255]<<16|d[m>>>8&255]<<8|d[255&m]),l[o]=y=(l[o-a]^m)>>>0);for(s=0;s<n;s++)o=n-s,m=3&s?l[o]:l[o-4],u[s]=s<4||o<=4?m:f[d[m>>>24]]^p[d[m>>>16&255]]^g[d[m>>>8&255]]^v[d[255&m]],u[s]=u[s]>>>0}},t.prototype.networkToHostOrderSwap=function(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24},t.prototype.decrypt=function(t,e,r){for(var i,a,n=this.keySize+6,o=this.invKeySchedule,s=this.invSBox,l=this.invSubMix,u=l[0],d=l[1],h=l[2],c=l[3],f=this.uint8ArrayToUint32Array_(r),p=f[0],g=f[1],v=f[2],y=f[3],m=new Int32Array(t),b=new Int32Array(m.length),E=void 0,T=void 0,R=void 0,A=void 0,S=void 0,_=void 0,L=void 0,w=void 0,D=void 0,k=void 0,I=void 0,O=void 0,C=this.networkToHostOrderSwap;e<m.length;){for(D=C(m[e]),k=C(m[e+1]),I=C(m[e+2]),O=C(m[e+3]),S=D^o[0],_=O^o[1],L=I^o[2],w=k^o[3],i=4,a=1;a<n;a++)E=u[S>>>24]^d[_>>16&255]^h[L>>8&255]^c[255&w]^o[i],T=u[_>>>24]^d[L>>16&255]^h[w>>8&255]^c[255&S]^o[i+1],R=u[L>>>24]^d[w>>16&255]^h[S>>8&255]^c[255&_]^o[i+2],A=u[w>>>24]^d[S>>16&255]^h[_>>8&255]^c[255&L]^o[i+3],S=E,_=T,L=R,w=A,i+=4;E=s[S>>>24]<<24^s[_>>16&255]<<16^s[L>>8&255]<<8^s[255&w]^o[i],T=s[_>>>24]<<24^s[L>>16&255]<<16^s[w>>8&255]<<8^s[255&S]^o[i+1],R=s[L>>>24]<<24^s[w>>16&255]<<16^s[S>>8&255]<<8^s[255&_]^o[i+2],A=s[w>>>24]<<24^s[S>>16&255]<<16^s[_>>8&255]<<8^s[255&L]^o[i+3],i+=3,b[e]=C(E^p),b[e+1]=C(A^g),b[e+2]=C(R^v),b[e+3]=C(T^y),p=D,g=k,v=I,y=O,e+=4}return b.buffer},t.prototype.destroy=function(){this.key=void 0,this.keySize=void 0,this.ksRows=void 0,this.sBox=void 0,this.invSBox=void 0,this.subMix=void 0,this.invSubMix=void 0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.rcon=void 0},t}(),c=h,f=r(2),p=r(0),g=function(){function t(e,r){o(this,t),this.observer=e,this.config=r,this.logEnabled=!0;try{var i=crypto||self.crypto;this.subtle=i.subtle||i.webkitSubtle}catch(t){}this.disableWebCrypto=!this.subtle}return t.prototype.isSync=function(){return this.disableWebCrypto&&this.config.enableSoftwareAES},t.prototype.decrypt=function(t,e,r,i){var a=this;if(this.disableWebCrypto&&this.config.enableSoftwareAES){this.logEnabled&&(p.b.log("JS AES decrypt"),this.logEnabled=!1);var n=this.decryptor;n||(this.decryptor=n=new c),n.expandKey(e),i(n.decrypt(t,0,r))}else{this.logEnabled&&(p.b.log("WebCrypto AES decrypt"),this.logEnabled=!1);var o=this.subtle;this.key!==e&&(this.key=e,this.fastAesKey=new d(o,e)),this.fastAesKey.expandKey().then(function(n){new l(o,r).decrypt(t,n).catch(function(n){a.onWebCryptoError(n,t,e,r,i)}).then(function(t){i(t)})}).catch(function(n){a.onWebCryptoError(n,t,e,r,i)})}},t.prototype.onWebCryptoError=function(t,e,r,i,a){this.config.enableSoftwareAES?(p.b.log("WebCrypto Error, disable WebCrypto API"),this.disableWebCrypto=!0,this.logEnabled=!0,this.decrypt(e,r,i,a)):(p.b.error("decrypting error : "+t.message),this.observer.trigger(Event.ERROR,{type:f.b.MEDIA_ERROR,details:f.a.FRAG_DECRYPT_ERROR,fatal:!0,reason:t.message}))},t.prototype.destroy=function(){var t=this.decryptor;t&&(t.destroy(),this.decryptor=void 0)},t}();e.a=g},function(t,e){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function a(t){return"number"==typeof t}function n(t){return"object"==typeof t&&null!==t}function o(t){return void 0===t}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!a(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,a,s,l,u;if(this._events||(this._events={}),"error"===t&&(!this._events.error||n(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var d=new Error('Uncaught, unspecified "error" event. ('+e+")");throw d.context=e,d}if(r=this._events[t],o(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(n(r))for(s=Array.prototype.slice.call(arguments,1),u=r.slice(),a=u.length,l=0;l<a;l++)u[l].apply(this,s);return!0},r.prototype.addListener=function(t,e){var a;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?n(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,n(this._events[t])&&!this._events[t].warned&&(a=o(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&a>0&&this._events[t].length>a&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),a||(a=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var a=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,a,o,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],o=r.length,a=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(n(r)){for(s=o;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){a=s;break}if(a<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(a,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){return this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},r.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,r){!function(e){var r=/^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,i=/^([^\/;?#]*)(.*)$/,a=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g,o={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var a=this.parseURL(t);if(!s)throw new Error("Error trying to parse base URL.");return a.path=o.normalizePath(a.path),o.buildURLFromParts(a)}var n=this.parseURL(e);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return r.alwaysNormalize?(n.path=o.normalizePath(n.path),o.buildURLFromParts(n)):e;var s=this.parseURL(t);if(!s)throw new Error("Error trying to parse base URL.");if(!s.netLoc&&s.path&&"/"!==s.path[0]){var l=i.exec(s.path);s.netLoc=l[1],s.path=l[2]}s.netLoc&&!s.path&&(s.path="/");var u={scheme:s.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(u.netLoc=s.netLoc,"/"!==n.path[0]))if(n.path){var d=s.path,h=d.substring(0,d.lastIndexOf("/")+1)+n.path;u.path=o.normalizePath(h)}else u.path=s.path,n.params||(u.params=s.params,n.query||(u.query=s.query));return null===u.path&&(u.path=r.alwaysNormalize?o.normalizePath(n.path):n.path),o.buildURLFromParts(u)},parseURL:function(t){var e=r.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(a,"");t.length!==(t=t.replace(n,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};t.exports=o}()},function(t,e,r){"use strict";function i(t,e,r,i){var a,n,o,s,l,u=navigator.userAgent.toLowerCase(),d=i,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];return a=1+((192&e[r+2])>>>6),(n=(60&e[r+2])>>>2)>h.length-1?void t.trigger(Event.ERROR,{type:_.b.MEDIA_ERROR,details:_.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+n}):(s=(1&e[r+2])<<2,s|=(192&e[r+3])>>>6,w.b.log("manifest codec:"+i+",ADTS data:type:"+a+",sampleingIndex:"+n+"["+h[n]+"Hz],channelConfig:"+s),/firefox/i.test(u)?n>=6?(a=5,l=new Array(4),o=n-3):(a=2,l=new Array(2),o=n):-1!==u.indexOf("android")?(a=2,l=new Array(2),o=n):(a=5,l=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&n>=6?o=n-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(n>=6&&1===s||/vivaldi/i.test(u))||!i&&1===s)&&(a=2,l=new Array(2)),o=n)),l[0]=a<<3,l[0]|=(14&n)>>1,l[1]|=(1&n)<<7,l[1]|=s<<3,5===a&&(l[1]|=(14&o)>>1,l[2]=(1&o)<<7,l[2]|=8,l[3]=0),{config:l,samplerate:h[n],channelCount:s,codec:"mp4a.40."+a,manifestCodec:d})}function a(t,e){return 255===t[e]&&240==(246&t[e+1])}function n(t,e){return 1&t[e+1]?7:9}function o(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function s(t,e){return!!(e+1<t.length&&a(t,e))}function l(t,e){if(e+1<t.length&&a(t,e)){var r=n(t,e),i=r;e+5<t.length&&(i=o(t,e));var s=e+i;if(s===t.length||s+1<t.length&&a(t,s))return!0}return!1}function u(t,e,r,a,n){if(!t.samplerate){var o=i(e,r,a,n);t.config=o.config,t.samplerate=o.samplerate,t.channelCount=o.channelCount,t.codec=o.codec,t.manifestCodec=o.manifestCodec,w.b.log("parsed codec:"+t.codec+",rate:"+o.samplerate+",nb channel:"+o.channelCount)}}function d(t){return 9216e4/t}function h(t,e,r,i,a){var s,l,u,d=t.length;if(s=n(t,e),l=o(t,e),(l-=s)>0&&e+s+l<=d)return u=r+i*a,{headerLength:s,frameLength:l,stamp:u}}function c(t,e,r,i,a){var n=d(t.samplerate),o=h(e,r,i,a,n);if(o){var s=o.stamp,l=o.headerLength,u=o.frameLength,c={unit:e.subarray(r+l,r+l+u),pts:s,dts:s};return t.samples.push(c),t.len+=u,{sample:c,length:u+l}}}function f(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function p(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function g(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function v(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function y(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function m(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function b(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function E(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function T(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function R(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function A(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var S=r(1),_=r(2),L=r(4),w=r(0),D=r(3),k=function(){function t(e,r,i){f(this,t),this.observer=e,this.config=i,this.remuxer=r}return t.prototype.resetInitSegment=function(t,e,r,i){this._audioTrack={container:"audio/adts",type:"audio",id:0,sequenceNumber:0,isAAC:!0,samples:[],len:0,manifestCodec:e,duration:i,inputTimeScale:9e4}},t.prototype.resetTimeStamp=function(){},t.probe=function(t){if(!t)return!1;for(var e=D.a.getID3Data(t,0)||[],r=e.length,i=t.length;r<i;r++)if(l(t,r))return w.b.log("ADTS sync word found !"),!0;return!1},t.prototype.append=function(t,e,r,i){for(var a=this._audioTrack,n=D.a.getID3Data(t,0)||[],o=D.a.getTimeStamp(n),l=o?90*o:9e4*e,d=0,h=l,f=t.length,p=n.length,g=[{pts:h,dts:h,data:n}];p<f-1;)if(s(t,p)&&p+5<f){u(a,this.observer,t,p,a.manifestCodec);var v=c(a,t,p,l,d);if(!v){w.b.log("Unable to parse AAC frame");break}p+=v.length,h=v.sample.pts,d++}else D.a.isHeader(t,p)?(n=D.a.getID3Data(t,p),g.push({pts:h,dts:h,data:n}),p+=n.length):p++;this.remuxer.remux(a,{samples:[]},{samples:g,inputTimeScale:9e4},{samples:[]},e,r,i)},t.prototype.destroy=function(){},t}(),I=k,O=Math.pow(2,32)-1,C=function(){function t(e,r){p(this,t),this.observer=e,this.remuxer=r}return t.prototype.resetTimeStamp=function(t){this.initPTS=t},t.prototype.resetInitSegment=function(e,r,i,a){if(e&&e.byteLength){var n=this.initData=t.parseInitSegment(e);null==r&&(r="mp4a.40.5"),null==i&&(i="avc1.42e01e");var o={};n.audio&&n.video?o.audiovideo={container:"video/mp4",codec:r+","+i,initSegment:a?e:null}:(n.audio&&(o.audio={container:"audio/mp4",codec:r,initSegment:a?e:null}),n.video&&(o.video={container:"video/mp4",codec:i,initSegment:a?e:null})),this.observer.trigger(S.a.FRAG_PARSING_INIT_SEGMENT,{tracks:o})}else r&&(this.audioCodec=r),i&&(this.videoCodec=i)},t.probe=function(e){return t.findBox({data:e,start:0,end:Math.min(e.length,16384)},["moof"]).length>0},t.bin2str=function(t){return String.fromCharCode.apply(null,t)},t.readUint32=function(t,e){t.data&&(e+=t.start,t=t.data);var r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r},t.writeUint32=function(t,e,r){t.data&&(e+=t.start,t=t.data),t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r},t.findBox=function(e,r){var i,a,n,o,s,l,u,d=[];if(e.data?(l=e.start,o=e.end,e=e.data):(l=0,o=e.byteLength),!r.length)return null;for(i=l;i<o;)a=t.readUint32(e,i),n=t.bin2str(e.subarray(i+4,i+8)),u=a>1?i+a:o,n===r[0]&&(1===r.length?d.push({data:e,start:i+8,end:u}):(s=t.findBox({data:e,start:i+8,end:u},r.slice(1)),s.length&&(d=d.concat(s)))),i=u;return d},t.parseInitSegment=function(e){var r=[];return t.findBox(e,["moov","trak"]).forEach(function(e){var i=t.findBox(e,["tkhd"])[0];if(i){var a=i.data[i.start],n=0===a?12:20,o=t.readUint32(i,n),s=t.findBox(e,["mdia","mdhd"])[0];if(s){a=s.data[s.start],n=0===a?12:20;var l=t.readUint32(s,n),u=t.findBox(e,["mdia","hdlr"])[0];if(u){var d=t.bin2str(u.data.subarray(u.start+8,u.start+12)),h={soun:"audio",vide:"video"}[d];if(h){var c=t.findBox(e,["mdia","minf","stbl","stsd"]);if(c.length){c=c[0];var f=t.bin2str(c.data.subarray(c.start+12,c.start+16));w.b.log("MP4Demuxer:"+h+":"+f+" found")}r[o]={timescale:l,type:h},r[h]={timescale:l,id:o}}}}}}),r},t.getStartDTS=function(e,r){var i,a,n;return i=t.findBox(r,["moof","traf"]),a=[].concat.apply([],i.map(function(r){return t.findBox(r,["tfhd"]).map(function(i){var a,n;return a=t.readUint32(i,4),n=e[a].timescale||9e4,t.findBox(r,["tfdt"]).map(function(e){var r,i;return r=e.data[e.start],i=t.readUint32(e,4),1===r&&(i*=Math.pow(2,32),i+=t.readUint32(e,8)),i})[0]/n})})),n=Math.min.apply(null,a),isFinite(n)?n:0},t.offsetStartDTS=function(e,r,i){t.findBox(r,["moof","traf"]).map(function(r){return t.findBox(r,["tfhd"]).map(function(a){var n=t.readUint32(a,4),o=e[n].timescale||9e4;t.findBox(r,["tfdt"]).map(function(e){var r=e.data[e.start],a=t.readUint32(e,4);if(0===r)t.writeUint32(e,4,a-i*o);else{a*=Math.pow(2,32),a+=t.readUint32(e,8),a-=i*o,a=Math.max(a,0);var n=Math.floor(a/(O+1)),s=Math.floor(a%(O+1));t.writeUint32(e,4,n),t.writeUint32(e,8,s)}})})})},t.prototype.append=function(e,r,i,a){var n=this.initData;n||(this.resetInitSegment(e,this.audioCodec,this.videoCodec),n=this.initData);var o=void 0,s=this.initPTS;if(void 0===s){var l=t.getStartDTS(n,e);this.initPTS=s=l-r,this.observer.trigger(S.a.INIT_PTS_FOUND,{initPTS:s})}t.offsetStartDTS(n,e,s),o=t.getStartDTS(n,e),this.remuxer.remux(n.audio,n.video,null,null,o,i,a,e)},t.prototype.destroy=function(){},t}(),P=C,x={BitratesMap:[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],SamplingRateMap:[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],appendFrame:function(t,e,r,i,a){if(!(r+24>e.length)){var n=this.parseHeader(e,r);if(n&&r+n.frameLength<=e.length){var o=10368e4/n.sampleRate,s=i+a*o,l={unit:e.subarray(r,r+n.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(l),t.len+=n.frameLength,{sample:l,length:n.frameLength}}}},parseHeader:function(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,a=t[e+2]>>4&15,n=t[e+2]>>2&3,o=!!(2&t[e+2]);if(1!==r&&0!==a&&15!==a&&3!==n){var s=3===r?3-i:3===i?3:4,l=1e3*x.BitratesMap[14*s+a-1],u=3===r?0:2===r?1:2,d=x.SamplingRateMap[3*u+n],h=o?1:0;return{sampleRate:d,channelCount:t[e+3]>>6==3?1:2,frameLength:3===i?(3===r?12:6)*l/d+h<<2:(3===r?144:72)*l/d+h|0}}},isHeaderPattern:function(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])},isHeader:function(t,e){return!!(e+1<t.length&&this.isHeaderPattern(t,e))},probe:function(t,e){if(e+1<t.length&&this.isHeaderPattern(t,e)){var r=this.parseHeader(t,e),i=4;r&&r.frameLength&&(i=r.frameLength);var a=e+i;if(a===t.length||a+1<t.length&&this.isHeaderPattern(t,a))return!0}return!1}},F=x,N=function(){function t(e){g(this,t),this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}return t.prototype.loadWord=function(){var t=this.data,e=this.bytesAvailable,r=t.byteLength-e,i=new Uint8Array(4),a=Math.min(4,e);if(0===a)throw new Error("no bytes available");i.set(t.subarray(r,r+a)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*a,this.bytesAvailable-=a},t.prototype.skipBits=function(t){var e;this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,e=t>>3,t-=e>>3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},t.prototype.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&w.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),e=t-e,e>0&&this.bitsAvailable?r<<e|this.readBits(e):r},t.prototype.skipLZ=function(){var t;for(t=0;t<this.bitsAvailable;++t)if(0!=(this.word&2147483648>>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},t.prototype.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.prototype.skipEG=function(){this.skipBits(1+this.skipLZ())},t.prototype.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},t.prototype.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},t.prototype.readBoolean=function(){return 1===this.readBits(1)},t.prototype.readUByte=function(){return this.readBits(8)},t.prototype.readUShort=function(){return this.readBits(16)},t.prototype.readUInt=function(){return this.readBits(32)},t.prototype.skipScalingList=function(t){var e,r,i=8,a=8;for(e=0;e<t;e++)0!==a&&(r=this.readEG(),a=(i+r+256)%256),i=0===a?i:a},t.prototype.readSPS=function(){var t,e,r,i,a,n,o,s=0,l=0,u=0,d=0,h=this.readUByte.bind(this),c=this.readBits.bind(this),f=this.readUEG.bind(this),p=this.readBoolean.bind(this),g=this.skipBits.bind(this),v=this.skipEG.bind(this),y=this.skipUEG.bind(this),m=this.skipScalingList.bind(this);if(h(),t=h(),c(5),g(3),h(),y(),100===t||110===t||122===t||244===t||44===t||83===t||86===t||118===t||128===t){var b=f();if(3===b&&g(1),y(),y(),g(1),p())for(n=3!==b?8:12,o=0;o<n;o++)p()&&m(o<6?16:64)}y();var E=f();if(0===E)f();else if(1===E)for(g(1),v(),v(),e=f(),o=0;o<e;o++)v();y(),g(1),r=f(),i=f(),a=c(1),0===a&&g(1),g(1),p()&&(s=f(),l=f(),u=f(),d=f());var T=[1,1];if(p()&&p()){switch(h()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:T=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(r+1)-2*s-2*l),height:(2-a)*(i+1)*16-(a?2:4)*(u+d),pixelRatio:T}},t.prototype.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},t}(),M=N,U=function(){function t(e,r,i,a){v(this,t),this.decryptdata=i,this.discardEPB=a,this.decrypter=new L.a(e,r)}return t.prototype.decryptBuffer=function(t,e){this.decrypter.decrypt(t,this.decryptdata.key.buffer,this.decryptdata.iv.buffer,e)},t.prototype.decryptAacSample=function(t,e,r,i){var a=t[e].unit,n=a.subarray(16,a.length-a.length%16),o=n.buffer.slice(n.byteOffset,n.byteOffset+n.length),s=this;this.decryptBuffer(o,function(n){n=new Uint8Array(n),a.set(n,16),i||s.decryptAacSamples(t,e+1,r)})},t.prototype.decryptAacSamples=function(t,e,r){for(;;e++){if(e>=t.length)return void r();if(!(t[e].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(t,e,r,i),!i)return}}},t.prototype.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,a=32;a<=t.length-16;a+=160,i+=16)r.set(t.subarray(a,a+16),i);return r},t.prototype.getAvcDecryptedUnit=function(t,e){e=new Uint8Array(e);for(var r=0,i=32;i<=t.length-16;i+=160,r+=16)t.set(e.subarray(r,r+16),i);return t},t.prototype.decryptAvcSample=function(t,e,r,i,a,n){var o=this.discardEPB(a.data),s=this.getAvcEncryptedData(o),l=this;this.decryptBuffer(s.buffer,function(s){a.data=l.getAvcDecryptedUnit(o,s),n||l.decryptAvcSamples(t,e,r+1,i)})},t.prototype.decryptAvcSamples=function(t,e,r,i){for(;;e++,r=0){if(e>=t.length)return void i();for(var a=t[e].units;!(r>=a.length);r++){var n=a[r];if(!(n.length<=48||1!==n.type&&5!==n.type)){var o=this.decrypter.isSync();if(this.decryptAvcSample(t,e,r,i,n,o),!o)return}}}},t}(),B=U,G={video:0,audio:1,id3:2,text:3},H=function(){function t(e,r,i,a){y(this,t),this.observer=e,this.config=i,this.typeSupported=a,this.remuxer=r,this.sampleAes=null}return t.prototype.setDecryptData=function(t){null!=t&&null!=t.key&&"SAMPLE-AES"===t.method?this.sampleAes=new B(this.observer,this.config,t,this.discardEPB):this.sampleAes=null},t.probe=function(e){var r=t._syncOffset(e);return!(r<0)&&(r&&w.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},t._syncOffset=function(t){for(var e=Math.min(1e3,t.length-564),r=0;r<e;){if(71===t[r]&&71===t[r+188]&&71===t[r+376])return r;r++}return-1},t.createTrack=function(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:G[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],len:0,dropped:"video"===t?0:void 0,isAAC:"audio"===t||void 0,duration:"audio"===t?e:void 0}},t.prototype.resetInitSegment=function(e,r,i,a){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=t.createTrack("video",a),this._audioTrack=t.createTrack("audio",a),this._id3Track=t.createTrack("id3",a),this._txtTrack=t.createTrack("text",a),this.aacOverFlow=null,this.aacLastPTS=null,this.avcSample=null,this.audioCodec=r,this.videoCodec=i,this._duration=a},t.prototype.resetTimeStamp=function(){},t.prototype.append=function(e,r,i,a){var n,o,s,l,u,d=e.length,h=!1;this.contiguous=i;var c=this.pmtParsed,f=this._avcTrack,p=this._audioTrack,g=this._id3Track,v=f.pid,y=p.pid,m=g.pid,b=this._pmtId,E=f.pesData,T=p.pesData,R=g.pesData,A=this._parsePAT,L=this._parsePMT,D=this._parsePES,k=this._parseAVCPES.bind(this),I=this._parseAACPES.bind(this),O=this._parseMPEGPES.bind(this),C=this._parseID3PES.bind(this),P=t._syncOffset(e);for(d-=(d+P)%188,n=P;n<d;n+=188)if(71===e[n]){if(o=!!(64&e[n+1]),s=((31&e[n+1])<<8)+e[n+2],(48&e[n+3])>>4>1){if((l=n+5+e[n+4])===n+188)continue}else l=n+4;switch(s){case v:o&&(E&&(u=D(E))&&k(u,!1),E={data:[],size:0}),E&&(E.data.push(e.subarray(l,n+188)),E.size+=n+188-l);break;case y:o&&(T&&(u=D(T))&&(p.isAAC?I(u):O(u)),T={data:[],size:0}),T&&(T.data.push(e.subarray(l,n+188)),T.size+=n+188-l);break;case m:o&&(R&&(u=D(R))&&C(u),R={data:[],size:0}),R&&(R.data.push(e.subarray(l,n+188)),R.size+=n+188-l);break;case 0:o&&(l+=e[l]+1),b=this._pmtId=A(e,l);break;case b:o&&(l+=e[l]+1);var x=L(e,l,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);v=x.avc,v>0&&(f.pid=v),y=x.audio,y>0&&(p.pid=y,p.isAAC=x.isAAC),m=x.id3,m>0&&(g.pid=m),h&&!c&&(w.b.log("reparse from beginning"),h=!1,n=P-188),c=this.pmtParsed=!0;break;case 17:case 8191:break;default:h=!0}}else this.observer.trigger(S.a.ERROR,{type:_.b.MEDIA_ERROR,details:_.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});E&&(u=D(E))?(k(u,!0),f.pesData=null):f.pesData=E,T&&(u=D(T))?(p.isAAC?I(u):O(u),p.pesData=null):(T&&T.size&&w.b.log("last AAC PES packet truncated,might overlap between fragments"),p.pesData=T),R&&(u=D(R))?(C(u),g.pesData=null):g.pesData=R,null==this.sampleAes?this.remuxer.remux(p,f,g,this._txtTrack,r,i,a):this.decryptAndRemux(p,f,g,this._txtTrack,r,i,a)},t.prototype.decryptAndRemux=function(t,e,r,i,a,n,o){if(t.samples&&t.isAAC){var s=this;this.sampleAes.decryptAacSamples(t.samples,0,function(){s.decryptAndRemuxAvc(t,e,r,i,a,n,o)})}else this.decryptAndRemuxAvc(t,e,r,i,a,n,o)},t.prototype.decryptAndRemuxAvc=function(t,e,r,i,a,n,o){if(e.samples){var s=this;this.sampleAes.decryptAvcSamples(e.samples,0,0,function(){s.remuxer.remux(t,e,r,i,a,n,o)})}else this.remuxer.remux(t,e,r,i,a,n,o)},t.prototype.destroy=function(){this._initPTS=this._initDTS=void 0,this._duration=0},t.prototype._parsePAT=function(t,e){return(31&t[e+10])<<8|t[e+11]},t.prototype._parsePMT=function(t,e,r,i){var a,n,o,s,l={audio:-1,avc:-1,id3:-1,isAAC:!0};for(a=(15&t[e+1])<<8|t[e+2],n=e+3+a-4,o=(15&t[e+10])<<8|t[e+11],e+=12+o;e<n;){switch(s=(31&t[e+1])<<8|t[e+2],t[e]){case 207:if(!i){w.b.log("unkown stream type:"+t[e]);break}case 15:-1===l.audio&&(l.audio=s);break;case 21:-1===l.id3&&(l.id3=s);break;case 219:if(!i){w.b.log("unkown stream type:"+t[e]);break}case 27:-1===l.avc&&(l.avc=s);break;case 3:case 4:r?-1===l.audio&&(l.audio=s,l.isAAC=!1):w.b.log("MPEG audio found, not supported in this browser for now");break;case 36:w.b.warn("HEVC stream type found, not supported for now");break;default:w.b.log("unkown stream type:"+t[e])}e+=5+((15&t[e+3])<<8|t[e+4])}return l},t.prototype._parsePES=function(t){var e,r,i,a,n,o,s,l,u=0,d=t.data;if(!t||0===t.size)return null;for(;d[0].length<19&&d.length>1;){var h=new Uint8Array(d[0].length+d[1].length);h.set(d[0]),h.set(d[1],d[0].length),d[0]=h,d.splice(1,1)}if(e=d[0],1===(e[0]<<16)+(e[1]<<8)+e[2]){if((i=(e[4]<<8)+e[5])&&i>t.size-6)return null;r=e[7],192&r&&(o=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,o>4294967295&&(o-=8589934592),64&r?(s=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,s>4294967295&&(s-=8589934592),o-s>54e5&&(w.b.warn(Math.round((o-s)/9e4)+"s delta between PTS and DTS, align them"),o=s)):s=o),a=e[8],l=a+9,t.size-=l,n=new Uint8Array(t.size);for(var c=0,f=d.length;c<f;c++){e=d[c];var p=e.byteLength;if(l){if(l>p){l-=p;continue}e=e.subarray(l),p-=l,l=0}n.set(e,u),u+=p}return i&&(i-=a+3),{data:n,pts:o,dts:s,len:i}}return null},t.prototype.pushAccesUnit=function(t,e){if(t.units.length&&t.frame){var r=e.samples,i=r.length;!this.config.forceKeyFrameOnDiscontinuity||!0===t.key||e.sps&&(i||this.contiguous)?(t.id=i,r.push(t)):e.dropped++}t.debug.length&&w.b.log(t.pts+"/"+t.dts+":"+t.debug)},t.prototype._parseAVCPES=function(t,e){var r,i,a,n=this,o=this._avcTrack,s=this._parseAVCNALu(t.data),l=this.avcSample,u=!1,d=this.pushAccesUnit.bind(this),h=function(t,e,r,i){return{key:t,pts:e,dts:r,units:[],debug:i}};t.data=null,l&&s.length&&!o.audFound&&(d(l,o),l=this.avcSample=h(!1,t.pts,t.dts,"")),s.forEach(function(e){switch(e.type){case 1:i=!0,l||(l=n.avcSample=h(!0,t.pts,t.dts,"")),l.frame=!0;var s=e.data;if(u&&s.length>4){var c=new M(s).readSliceType();2!==c&&4!==c&&7!==c&&9!==c||(l.key=!0)}break;case 5:i=!0,l||(l=n.avcSample=h(!0,t.pts,t.dts,"")),l.key=!0,l.frame=!0;break;case 6:i=!0,r=new M(n.discardEPB(e.data)),r.readUByte();for(var f=0,p=0,g=!1,v=0;!g&&r.bytesAvailable>1;){f=0;do{v=r.readUByte(),f+=v}while(255===v);p=0;do{v=r.readUByte(),p+=v}while(255===v);if(4===f&&0!==r.bytesAvailable){g=!0;if(181===r.readUByte()){if(49===r.readUShort()){if(1195456820===r.readUInt()){if(3===r.readUByte()){var y=r.readUByte(),m=r.readUByte(),b=31&y,E=[y,m];for(a=0;a<b;a++)E.push(r.readUByte()),E.push(r.readUByte()),E.push(r.readUByte());n._insertSampleInOrder(n._txtTrack.samples,{type:3,pts:t.pts,bytes:E})}}}}}else if(p<r.bytesAvailable)for(a=0;a<p;a++)r.readUByte()}break;case 7:if(i=!0,u=!0,!o.sps){r=new M(e.data);var T=r.readSPS();o.width=T.width,o.height=T.height,o.pixelRatio=T.pixelRatio,o.sps=[e.data],o.duration=n._duration;var R=e.data.subarray(1,4),A="avc1.";for(a=0;a<3;a++){var S=R[a].toString(16);S.length<2&&(S="0"+S),A+=S}o.codec=A}break;case 8:i=!0,o.pps||(o.pps=[e.data]);break;case 9:i=!1,o.audFound=!0,l&&d(l,o),l=n.avcSample=h(!1,t.pts,t.dts,"");break;case 12:i=!1;break;default:i=!1,l&&(l.debug+="unknown NAL "+e.type+" ")}if(l&&i){l.units.push(e)}}),e&&l&&(d(l,o),this.avcSample=null)},t.prototype._insertSampleInOrder=function(t,e){var r=t.length;if(r>0){if(e.pts>=t[r-1].pts)t.push(e);else for(var i=r-1;i>=0;i--)if(e.pts<t[i].pts){t.splice(i,0,e);break}}else t.push(e)},t.prototype._getLastNalUnit=function(){var t=this.avcSample,e=void 0;if(!t||0===t.units.length){var r=this._avcTrack,i=r.samples;t=i[i.length-1]}if(t){var a=t.units;e=a[a.length-1]}return e},t.prototype._parseAVCNALu=function(t){var e,r,i,a,n,o=0,s=t.byteLength,l=this._avcTrack,u=l.naluState||0,d=u,h=[],c=-1;for(-1===u&&(c=0,n=31&t[0],u=0,o=1);o<s;)if(e=t[o++],u)if(1!==u)if(e)if(1===e){if(c>=0)i={data:t.subarray(c,o-u-1),type:n},h.push(i);else{var f=this._getLastNalUnit();if(f&&(d&&o<=4-d&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-d)),(r=o-u-1)>0)){var p=new Uint8Array(f.data.byteLength+r);p.set(f.data,0),p.set(t.subarray(0,r),f.data.byteLength),f.data=p}}o<s?(a=31&t[o],c=o,n=a,u=0):u=-1}else u=0;else u=3;else u=e?0:2;else u=e?0:1;if(c>=0&&u>=0&&(i={data:t.subarray(c,s),type:n,state:u},h.push(i)),0===h.length){var g=this._getLastNalUnit();if(g){var v=new Uint8Array(g.data.byteLength+t.byteLength);v.set(g.data,0),v.set(t,g.data.byteLength),g.data=v}}return l.naluState=u,h},t.prototype.discardEPB=function(t){for(var e,r,i=t.byteLength,a=[],n=1;n<i-2;)0===t[n]&&0===t[n+1]&&3===t[n+2]?(a.push(n+2),n+=2):n++;if(0===a.length)return t;e=i-a.length,r=new Uint8Array(e);var o=0;for(n=0;n<e;o++,n++)o===a[0]&&(o++,a.shift()),r[n]=t[o];return r},t.prototype._parseAACPES=function(t){var e,r,i,a,n,o=this._audioTrack,l=t.data,h=t.pts,f=this.aacOverFlow,p=this.aacLastPTS;if(f){var g=new Uint8Array(f.byteLength+l.byteLength);g.set(f,0),g.set(l,f.byteLength),l=g}for(i=0,n=l.length;i<n-1&&!s(l,i);i++);if(i){var v,y;if(i<n-1?(v="AAC PES did not start with ADTS header,offset:"+i,y=!1):(v="no ADTS header found in AAC PES",y=!0),w.b.warn("parsing error:"+v),this.observer.trigger(S.a.ERROR,{type:_.b.MEDIA_ERROR,details:_.a.FRAG_PARSING_ERROR,fatal:y,reason:v}),y)return}if(u(o,this.observer,l,i,this.audioCodec),r=0,e=d(o.samplerate),f&&p){var m=p+e;Math.abs(m-h)>1&&(w.b.log("AAC: align PTS for overlapping frames by "+Math.round((m-h)/90)),h=m)}for(;i<n;)if(s(l,i)&&i+5<n){var b=c(o,l,i,h,r);if(!b)break;i+=b.length,a=b.sample.pts,r++}else i++;f=i<n?l.subarray(i,n):null,this.aacOverFlow=f,this.aacLastPTS=a},t.prototype._parseMPEGPES=function(t){for(var e=t.data,r=e.length,i=0,a=0,n=t.pts;a<r;)if(F.isHeader(e,a)){var o=F.appendFrame(this._audioTrack,e,a,n,i);if(!o)break;a+=o.length,i++}else a++},t.prototype._parseID3PES=function(t){this._id3Track.samples.push(t)},t}(),j=H,K=function(){function t(e,r,i){m(this,t),this.observer=e,this.config=i,this.remuxer=r}return t.prototype.resetInitSegment=function(t,e,r,i){this._audioTrack={container:"audio/mpeg",type:"audio",id:-1,sequenceNumber:0,isAAC:!1,samples:[],len:0,manifestCodec:e,duration:i,inputTimeScale:9e4}},t.prototype.resetTimeStamp=function(){},t.probe=function(t){var e,r,i=D.a.getID3Data(t,0);if(i&&void 0!==D.a.getTimeStamp(i))for(e=i.length,r=Math.min(t.length-1,e+100);e<r;e++)if(F.probe(t,e))return w.b.log("MPEG Audio sync word found !"),!0;return!1},t.prototype.append=function(t,e,r,i){for(var a=D.a.getID3Data(t,0),n=90*D.a.getTimeStamp(a),o=a.length,s=t.length,l=0,u=0,d=this._audioTrack,h=[{pts:n,dts:n,data:a}];o<s;)if(F.isHeader(t,o)){var c=F.appendFrame(d,t,o,n,l);if(!c)break;o+=c.length,u=c.sample.pts,l++}else D.a.isHeader(t,o)?(a=D.a.getID3Data(t,o),h.push({pts:u,dts:u,data:a}),o+=a.length):o++;this.remuxer.remux(d,{samples:[]},{samples:h,inputTimeScale:9e4},{samples:[]},e,r,i)},t.prototype.destroy=function(){},t}(),W=K,V=function(){function t(){b(this,t)}return t.getSilentFrame=function(t,e){switch(t){case"mp4a.40.2":if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null},t}(),Y=V,z=Math.pow(2,32)-1,X=function(){function t(){E(this,t)}return t.init=function(){t.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};var e;for(e in t.types)t.types.hasOwnProperty(e)&&(t.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);t.HDLR_TYPES={video:r,audio:i};var a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);t.STTS=t.STSC=t.STCO=n,t.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),t.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),t.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),t.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var o=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);t.FTYP=t.box(t.types.ftyp,o,l,o,s),t.DINF=t.box(t.types.dinf,t.box(t.types.dref,a))},t.box=function(t){for(var e,r=Array.prototype.slice.call(arguments,1),i=8,a=r.length,n=a;a--;)i+=r[a].byteLength;for(e=new Uint8Array(i),e[0]=i>>24&255,e[1]=i>>16&255,e[2]=i>>8&255,e[3]=255&i,e.set(t,4),a=0,i=8;a<n;a++)e.set(r[a],i),i+=r[a].byteLength;return e},t.hdlr=function(e){return t.box(t.types.hdlr,t.HDLR_TYPES[e])},t.mdat=function(e){return t.box(t.types.mdat,e)},t.mdhd=function(e,r){r*=e;var i=Math.floor(r/(z+1)),a=Math.floor(r%(z+1));return t.box(t.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(z+1)),a=Math.floor(r%(z+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,n)},t.sdtp=function(e){var r,i,a=e.samples||[],n=new Uint8Array(4+a.length);for(i=0;i<a.length;i++)r=a[i].flags,n[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return t.box(t.types.sdtp,n)},t.stbl=function(e){return t.box(t.types.stbl,t.stsd(e),t.box(t.types.stts,t.STTS),t.box(t.types.stsc,t.STSC),t.box(t.types.stsz,t.STSZ),t.box(t.types.stco,t.STCO))},t.avc1=function(e){var r,i,a,n=[],o=[];for(r=0;r<e.sps.length;r++)i=e.sps[r],a=i.byteLength,n.push(a>>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r<e.pps.length;r++)i=e.pps[r],a=i.byteLength,o.push(a>>>8&255),o.push(255&a),o=o.concat(Array.prototype.slice.call(i));var s=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(o))),l=e.width,u=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),s,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?e.isAAC||"mp3"!==e.codec?t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,a=e.width,n=e.height,o=Math.floor(i/(z+1)),s=Math.floor(i%(z+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,s>>24,s>>16&255,s>>8&255,255&s,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,255&a,0,0,n>>8&255,255&n,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),a=e.id,n=Math.floor(r/(z+1)),o=Math.floor(r%(z+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,o>>24,o>>16&255,o>>8&255,255&o])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,a,n,o,s,l,u=e.samples||[],d=u.length,h=12+16*d,c=new Uint8Array(h);for(r+=8+h,c.set([0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<d;i++)a=u[i],n=a.duration,o=a.size,s=a.flags,l=a.cts,c.set([n>>>24&255,n>>>16&255,n>>>8&255,255&n,o>>>24&255,o>>>16&255,o>>>8&255,255&o,s.isLeading<<2|s.dependsOn,s.isDependedOn<<6|s.hasRedundancy<<4|s.paddingValue<<1|s.isNonSync,61440&s.degradPrio,15&s.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,c)},t.initSegment=function(e){t.types||t.init();var r,i=t.moov(e);return r=new Uint8Array(t.FTYP.byteLength+i.byteLength),r.set(t.FTYP),r.set(i,t.FTYP.byteLength),r},t}(),q=X,Q=function(){function t(e,r,i,a){T(this,t),this.observer=e,this.config=r,this.typeSupported=i;var n=navigator.userAgent;this.isSafari=a&&a.indexOf("Apple")>-1&&n&&!n.match("CriOS"),this.ISGenerated=!1}return t.prototype.destroy=function(){},t.prototype.resetTimeStamp=function(t){this._initPTS=this._initDTS=t},t.prototype.resetInitSegment=function(){this.ISGenerated=!1},t.prototype.remux=function(t,e,r,i,a,n,o){if(this.ISGenerated||this.generateIS(t,e,a),this.ISGenerated){var s=t.samples.length,l=e.samples.length,u=a,d=a;if(s&&l){var h=(t.samples[0].dts-e.samples[0].dts)/e.inputTimeScale;u+=Math.max(0,h),d+=Math.max(0,-h)}if(s){t.timescale||(w.b.warn("regenerate InitSegment as audio detected"),this.generateIS(t,e,a));var c=this.remuxAudio(t,u,n,o);if(l){var f=void 0;c&&(f=c.endPTS-c.startPTS),e.timescale||(w.b.warn("regenerate InitSegment as video detected"),this.generateIS(t,e,a)),this.remuxVideo(e,d,n,f,o)}}else{var p=void 0;l&&(p=this.remuxVideo(e,d,n,o)),p&&t.codec&&this.remuxEmptyAudio(t,u,n,p)}}r.samples.length&&this.remuxID3(r,a),i.samples.length&&this.remuxText(i,a),this.observer.trigger(S.a.FRAG_PARSED)},t.prototype.generateIS=function(t,e,r){var i,a,n=this.observer,o=t.samples,s=e.samples,l=this.typeSupported,u="audio/mp4",d={},h={tracks:d},c=void 0===this._initPTS;if(c&&(i=a=1/0),t.config&&o.length&&(t.timescale=t.samplerate,w.b.log("audio sampling rate : "+t.samplerate),t.isAAC||(l.mpeg?(u="audio/mpeg",t.codec=""):l.mp3&&(t.codec="mp3")),d.audio={container:u,codec:t.codec,initSegment:!t.isAAC&&l.mpeg?new Uint8Array:q.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(i=a=o[0].pts-t.inputTimeScale*r)),e.sps&&e.pps&&s.length){var f=e.inputTimeScale;e.timescale=f,d.video={container:"video/mp4",codec:e.codec,initSegment:q.initSegment([e]),metadata:{width:e.width,height:e.height}},c&&(i=Math.min(i,s[0].pts-f*r),a=Math.min(a,s[0].dts-f*r),this.observer.trigger(S.a.INIT_PTS_FOUND,{initPTS:i}))}Object.keys(d).length?(n.trigger(S.a.FRAG_PARSING_INIT_SEGMENT,h),this.ISGenerated=!0,c&&(this._initPTS=i,this._initDTS=a)):n.trigger(S.a.ERROR,{type:_.b.MEDIA_ERROR,details:_.a.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},t.prototype.remuxVideo=function(t,e,r,i,a){var n,o,s,l,u,d,h,c=8,f=t.timescale,p=t.samples,g=[],v=p.length,y=this._PTSNormalize,m=this._initDTS,b=this.nextAvcDts,E=this.isSafari;E&&(r|=p.length&&b&&(a&&Math.abs(e-b/f)<.1||Math.abs(p[0].pts-b-m)<f/5)),r||(b=e*f),p.forEach(function(t){t.pts=y(t.pts-m,b),t.dts=y(t.dts-m,b)}),p.sort(function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||(i||t.id-e.id)});var T=p.reduce(function(t,e){return Math.max(Math.min(t,e.pts-e.dts),-18e3)},0);if(T<0){w.b.warn("PTS < DTS detected in video samples, shifting DTS by "+Math.round(T/90)+" ms to overcome this issue");for(var R=0;R<p.length;R++)p[R].dts+=T}var A=p[0];u=Math.max(A.dts,0),l=Math.max(A.pts,0);var L=Math.round((u-b)/90);r&&L&&(L>1?w.b.log("AVC:"+L+" ms hole between fragments detected,filling it"):L<-1&&w.b.log("AVC:"+-L+" ms overlapping between fragments detected"),u=b,p[0].dts=u,l=Math.max(l-L,b),p[0].pts=l,w.b.log("Video/PTS/DTS adjusted: "+Math.round(l/90)+"/"+Math.round(u/90)+",delta:"+L+" ms")),A=p[p.length-1],h=Math.max(A.dts,0),d=Math.max(A.pts,0,h),E&&(n=Math.round((h-u)/(p.length-1)));for(var D=0,k=0,I=0;I<v;I++){for(var O=p[I],C=O.units,P=C.length,x=0,F=0;F<P;F++)x+=C[F].data.length;k+=x,D+=P,O.length=x,O.dts=E?u+I*n:Math.max(O.dts,u),O.pts=Math.max(O.pts,O.dts)}var N=k+4*D+8;try{o=new Uint8Array(N)}catch(t){return void this.observer.trigger(S.a.ERROR,{type:_.b.MUX_ERROR,details:_.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:N,reason:"fail allocating video mdat "+N})}var M=new DataView(o.buffer);M.setUint32(0,N),o.set(q.types.mdat,4);for(var U=0;U<v;U++){for(var B=p[U],G=B.units,H=0,j=void 0,K=0,W=G.length;K<W;K++){var V=G[K],Y=V.data,z=V.data.byteLength;M.setUint32(c,z),c+=4,o.set(Y,c),c+=z,H+=4+z}if(E)j=Math.max(0,n*Math.round((B.pts-B.dts)/n));else{if(U<v-1)n=p[U+1].dts-B.dts;else{var X=this.config,Q=B.dts-p[U>0?U-1:U].dts;if(X.stretchShortVideoTrack){var J=X.maxBufferHole,$=X.maxSeekHole,Z=Math.floor(Math.min(J,$)*f),tt=(i?l+i*f:this.nextAudioPts)-B.pts;tt>Z?(n=tt-Q,n<0&&(n=Q),w.b.log("It is approximately "+tt/90+" ms to the next segment; using duration "+n/90+" ms for the last video frame.")):n=Q}else n=Q}j=Math.round(B.pts-B.dts)}g.push({size:H,duration:n,cts:j,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:B.key?2:1,isNonSync:B.key?0:1}})}this.nextAvcDts=h+n;var et=t.dropped;if(t.len=0,t.nbNalu=0,t.dropped=0,g.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var rt=g[0].flags;rt.dependsOn=2,rt.isNonSync=0}t.samples=g,s=q.moof(t.sequenceNumber++,u,t),t.samples=[];var it={data1:s,data2:o,startPTS:l/f,endPTS:(d+n)/f,startDTS:u/f,endDTS:this.nextAvcDts/f,type:"video",nb:g.length,dropped:et};return this.observer.trigger(S.a.FRAG_PARSING_DATA,it),it},t.prototype.remuxAudio=function(t,e,r,i){var a,n,o,s,l,u,d,h=t.inputTimeScale,c=t.timescale,f=h/c,p=t.isAAC?1024:1152,g=p*f,v=this._PTSNormalize,y=this._initDTS,m=!t.isAAC&&this.typeSupported.mpeg,b=t.samples,E=[],T=this.nextAudioPts;if(r|=b.length&&T&&(i&&Math.abs(e-T/h)<.1||Math.abs(b[0].pts-T-y)<20*g),r||(T=e*h),b.forEach(function(t){t.pts=t.dts=v(t.pts-y,T)}),b.sort(function(t,e){return t.pts-e.pts}),i&&t.isAAC)for(var R=this.config.maxAudioFramesDrift,A=0,L=T;A<b.length;){var D,k=b[A],I=k.pts;D=I-L;var O=Math.abs(1e3*D/h);if(D<=-R*g)w.b.warn("Dropping 1 audio frame @ "+(L/h).toFixed(3)+"s due to "+Math.round(O)+" ms overlap."),b.splice(A,1),t.len-=k.unit.length;else if(D>=R*g&&O<1e4&&L){var C=Math.round(D/g);w.b.warn("Injecting "+C+" audio frame @ "+(L/h).toFixed(3)+"s due to "+Math.round(1e3*D/h)+" ms gap.");for(var P=0;P<C;P++){var x=Math.max(L,0);o=Y.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),o||(w.b.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),o=k.unit.subarray()),b.splice(A,0,{unit:o,pts:x,dts:x}),t.len+=o.length,L+=g,A++}k.pts=k.dts=L,L+=g,A++}else Math.abs(D),k.pts=k.dts=L,L+=g,A++}for(var F=0,N=b.length;F<N;F++){var M=b[F],U=M.unit,B=M.pts;if(void 0!==d)n.duration=Math.round((B-d)/f);else{var G=Math.round(1e3*(B-T)/h),H=0;if(r&&t.isAAC&&G){if(G>0&&G<1e4)H=Math.round((B-T)/g),w.b.log(G+" ms hole between AAC samples detected,filling it"),H>0&&(o=Y.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),o||(o=U.subarray()),t.len+=H*o.length);else if(G<-12){w.b.log("drop overlapping AAC sample, expected/parsed/delta:"+(T/h).toFixed(3)+"s/"+(B/h).toFixed(3)+"s/"+-G+"ms"),t.len-=U.byteLength;continue}B=T}if(u=Math.max(0,B),!(t.len>0))return;var j=m?t.len:t.len+8;a=m?0:8;try{s=new Uint8Array(j)}catch(t){return void this.observer.trigger(S.a.ERROR,{type:_.b.MUX_ERROR,details:_.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:j,reason:"fail allocating audio mdat "+j})}if(!m){new DataView(s.buffer).setUint32(0,j),s.set(q.types.mdat,4)}for(var K=0;K<H;K++)o=Y.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),o||(w.b.log("Unable to get silent frame for given audio codec; duplicating this frame instead."),o=U.subarray()),s.set(o,a),a+=o.byteLength,n={size:o.byteLength,cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},E.push(n)}s.set(U,a);var W=U.byteLength;a+=W,n={size:W,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},E.push(n),d=B}var V=0,z=E.length;if(z>=2&&(V=E[z-2].duration,n.duration=V),z){this.nextAudioPts=T=d+f*V,t.len=0,t.samples=E,l=m?new Uint8Array:q.moof(t.sequenceNumber++,u/f,t),t.samples=[];var X=u/h,Q=T/h,J={data1:l,data2:s,startPTS:X,endPTS:Q,startDTS:X,endDTS:Q,type:"audio",nb:z};return this.observer.trigger(S.a.FRAG_PARSING_DATA,J),J}return null},t.prototype.remuxEmptyAudio=function(t,e,r,i){var a=t.inputTimeScale,n=t.samplerate?t.samplerate:a,o=a/n,s=this.nextAudioPts,l=(void 0!==s?s:i.startDTS*a)+this._initDTS,u=i.endDTS*a+this._initDTS,d=1024*o,h=Math.ceil((u-l)/d),c=Y.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(w.b.warn("remux empty Audio"),!c)return void w.b.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!");for(var f=[],p=0;p<h;p++){var g=l+p*d;f.push({unit:c,pts:g,dts:g}),t.len+=c.length}t.samples=f,this.remuxAudio(t,e,r)},t.prototype.remuxID3=function(t,e){var r,i=t.samples.length,a=t.inputTimeScale,n=this._initPTS,o=this._initDTS;if(i){for(var s=0;s<i;s++)r=t.samples[s],r.pts=(r.pts-n)/a,r.dts=(r.dts-o)/a;this.observer.trigger(S.a.FRAG_PARSING_METADATA,{samples:t.samples})}t.samples=[],e=e},t.prototype.remuxText=function(t,e){t.samples.sort(function(t,e){return t.pts-e.pts});var r,i=t.samples.length,a=t.inputTimeScale,n=this._initPTS;if(i){for(var o=0;o<i;o++)r=t.samples[o],r.pts=(r.pts-n)/a;this.observer.trigger(S.a.FRAG_PARSING_USERDATA,{samples:t.samples})}t.samples=[],e=e},t.prototype._PTSNormalize=function(t,e){var r;if(void 0===e)return t;for(r=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=r;return t},t}(),J=Q,$=function(){function t(e){R(this,t),this.observer=e}return t.prototype.destroy=function(){},t.prototype.resetTimeStamp=function(){},t.prototype.resetInitSegment=function(){},t.prototype.remux=function(t,e,r,i,a,n,o,s){var l=this.observer,u="";t&&(u+="audio"),e&&(u+="video"),l.trigger(S.a.FRAG_PARSING_DATA,{data1:s,startPTS:a,startDTS:a,type:u,nb:1,dropped:0}),l.trigger(S.a.FRAG_PARSED)},t}(),Z=$,tt=function(){function t(e,r,i,a){A(this,t),this.observer=e,this.typeSupported=r,this.config=i,this.vendor=a}return t.prototype.destroy=function(){var t=this.demuxer;t&&t.destroy()},t.prototype.push=function(t,e,r,i,a,n,o,s,l,u,d,h){if(t.byteLength>0&&null!=e&&null!=e.key&&"AES-128"===e.method){var c=this.decrypter;null==c&&(c=this.decrypter=new L.a(this.observer,this.config));var f,p=this;try{f=performance.now()}catch(t){f=Date.now()}c.decrypt(t,e.key.buffer,e.iv.buffer,function(t){var c;try{c=performance.now()}catch(t){c=Date.now()}p.observer.trigger(S.a.FRAG_DECRYPTED,{stats:{tstart:f,tdecrypt:c}}),p.pushDecrypted(new Uint8Array(t),e,new Uint8Array(r),i,a,n,o,s,l,u,d,h)})}else this.pushDecrypted(new Uint8Array(t),e,new Uint8Array(r),i,a,n,o,s,l,u,d,h)},t.prototype.pushDecrypted=function(t,e,r,i,a,n,o,s,l,u,d,h){var c=this.demuxer;if(!c||o&&!this.probe(t)){for(var f=this.observer,p=this.typeSupported,g=this.config,v=[{demux:j,remux:J},{demux:I,remux:J},{demux:W,remux:J},{demux:P,remux:Z}],y=0,m=v.length;y<m;y++){var b=v[y],E=b.demux.probe;if(E(t)){var T=this.remuxer=new b.remux(f,g,p,this.vendor);c=new b.demux(f,T,g,p),this.probe=E;break}}if(!c)return void f.trigger(S.a.ERROR,{type:_.b.MEDIA_ERROR,details:_.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});this.demuxer=c}var R=this.remuxer;(o||s)&&(c.resetInitSegment(r,i,a,u),R.resetInitSegment()),o&&(c.resetTimeStamp(h),R.resetTimeStamp(h)),"function"==typeof c.setDecryptData&&c.setDecryptData(e),c.append(t,n,l,d)},t}();e.a=tt},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){var r=Gt[e];return!!r&&!0===r[t.slice(0,4)]}function o(t,e){return MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function l(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function d(t,e){if(!t)return null;for(var r=null,i=0;i<t.length;i++){var a=t[i];a.id===e&&(r=a)}return r}function h(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function c(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function f(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function p(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function g(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function v(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function y(){if("undefined"!=typeof window)return window.MediaSource||window.WebKitMediaSource}function m(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function b(t,e,r){var i=t[e],a=t[r],n=a.startPTS;isNaN(n)?a.start=r>e?i.start+i.duration:Math.max(i.start-a.duration,0):r>e?(i.duration=n-i.start,i.duration<0&&Ct.b.warn("negative duration computed for frag "+i.sn+",level "+i.level+", there should be some duration drift between playlist and fragment!")):(a.duration=i.start-n,a.duration<0&&Ct.b.warn("negative duration computed for frag "+a.sn+",level "+a.level+", there should be some duration drift between playlist and fragment!"))}function E(t,e,r,i,a,n){var o=r;if(!isNaN(e.startPTS)){var s=Math.abs(e.startPTS-r);isNaN(e.deltaPTS)?e.deltaPTS=s:e.deltaPTS=Math.max(s,e.deltaPTS),o=Math.max(r,e.startPTS),r=Math.min(r,e.startPTS),i=Math.max(i,e.endPTS),a=Math.min(a,e.startDTS),n=Math.max(n,e.endDTS)}var l=r-e.start;e.start=e.startPTS=r,e.maxStartPTS=o,e.endPTS=i,e.startDTS=a,e.endDTS=n,e.duration=i-r;var u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;var d,h,c;for(d=u-t.startSN,h=t.fragments,h[d]=e,c=d;c>0;c--)b(h,c,c-1);for(c=d;c<h.length-1;c++)b(h,c,c+1);return t.PTSKnown=!0,l}function T(t,e){var r,i=Math.max(t.startSN,e.startSN)-e.startSN,a=Math.min(t.endSN,e.endSN)-e.startSN,n=e.startSN-t.startSN,o=t.fragments,s=e.fragments,l=0;if(a<i)return void(e.PTSKnown=!1);for(var u=i;u<=a;u++){var d=o[n+u],h=s[u];h&&d&&(l=d.cc-h.cc,isNaN(d.startPTS)||(h.start=h.startPTS=d.startPTS,h.endPTS=d.endPTS,h.duration=d.duration,h.backtracked=d.backtracked,h.dropped=d.dropped,r=h))}if(l)for(Ct.b.log("discontinuity sliding from playlist, take drift into account"),u=0;u<s.length;u++)s[u].cc+=l;if(r)E(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS);else if(n>=0&&n<o.length){var c=o[n].start;for(u=0;u<s.length;u++)s[u].start+=c}e.PTSKnown=t.PTSKnown}function R(t,e){for(var r=null,i=0;i<t.length;i+=1){var a=t[i];if(a&&a.cc===e){r=a;break}}return r}function A(t,e){return ee.search(t,function(t){return t.cc<e?1:t.cc>e?-1:0})}function S(t,e,r){var i=!1;return e&&e.details&&r&&(r.endCC>r.startCC||t&&t.cc<r.startCC)&&(i=!0),i}function _(t,e){var r=t.fragments,i=e.fragments;if(!i.length||!r.length)return void Ct.b.log("No fragments to align");var a=R(r,i[0].cc);return!a||a&&!a.startPTS?void Ct.b.log("No frag in previous level to align on"):a}function L(t,e){e.fragments.forEach(function(e){if(e){var r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}),e.PTSKnown=!0}function w(t,e,r){if(S(t,e,r)){var i=_(e.details,r);i&&(Ct.b.log("Adjusting PTS using last level due to CC increase within current level"),L(i.start,r))}if(!1===r.PTSKnown&&e&&e.details){var a=e.details.programDateTime,n=r.programDateTime,o=(n-a)/1e3+e.details.fragments[0].start;isNaN(o)||(Ct.b.log("adjusting PTS using programDateTime delta, sliding:"+o.toFixed(3)),L(o,r))}}function D(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function k(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function I(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function O(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function C(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function P(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function x(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function F(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function N(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function M(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function U(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function B(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function G(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function H(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function j(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function K(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function W(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function V(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Y(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function z(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function X(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function q(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function Q(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function J(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function $(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Z(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function tt(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function et(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function rt(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function it(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function at(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new qe,this.regionList=[]}function nt(t){function e(t,e,r,i){return 3600*(0|t)+60*(0|e)+(0|r)+(0|i)/1e3}var r=t.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);return r?r[3]?e(r[1],r[2],r[3].replace(":",""),r[4]):r[1]>59?e(r[1],r[2],0,r[4]):e(0,r[1],r[2],r[4]):null}function ot(){this.values=Object.create(null)}function st(t,e,r,i){var a=i?t.split(i):[t];for(var n in a)if("string"==typeof a[n]){var o=a[n].split(r);if(2===o.length){var s=o[0],l=o[1];e(s,l)}}}function lt(t,e,r){function i(){var e=nt(t);if(null===e)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function a(){t=t.replace(/^\s+/,"")}var n=t;if(a(),e.startTime=i(),a(),"--\x3e"!==t.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);t=t.substr(3),a(),e.endTime=i(),a(),function(t,e){var i=new ot;st(t,function(t,e){switch(t){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===e){i.set(t,r[a].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":var n=e.split(","),o=n[0];i.integer(t,o),i.percent(t,o)&&i.set("snapToLines",!1),i.alt(t,o,["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",Je,"end"]);break;case"position":n=e.split(","),i.percent(t,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",Je,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",Je,"end","left","right"])}},/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");var a=i.get("line","auto");"auto"===a&&-1===Qe.line&&(a=-1),e.line=a,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",Je);var n=i.get("position","auto");"auto"===n&&50===Qe.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function ut(t){return t.replace(/<br(?: \/)?>/gi,"\n")}function dt(t,e,r,i){for(var a,n,o,s,l,u=window.VTTCue||window.TextTrackCue,d=0;d<i.rows.length;d++)if(a=i.rows[d],o=!0,s=0,l="",!a.isEmpty()){for(var h=0;h<a.chars.length;h++)a.chars[h].uchar.match(/\s/)&&o?s++:(l+=a.chars[h].uchar,o=!1);a.cueStartTime=e,e===r&&(r+=1e-4),n=new u(e,r,ut(l.trim())),s>=16?s--:s++,navigator.userAgent.match(/Firefox\//)?n.line=d+1:n.line=d>7?d-2:d+1,n.align="left",n.position=Math.max(0,Math.min(100,s/32*100+(navigator.userAgent.match(/Firefox\//)?50:0))),t.addCue(n)}}function ht(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function ct(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function ft(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function pt(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function gt(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function vt(t){if(t&&t.cues)for(;t.cues.length>0;)t.removeCue(t.cues[0])}function yt(t,e){return t&&t.label===e.name&&!(t.textTrack1||t.textTrack2)}function mt(t,e,r,i){return Math.min(e,i)-Math.max(t,r)}function bt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Et(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function Tt(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function Rt(t){for(var e=[],r=0;r<t.length;r++)"subtitles"===t[r].kind&&e.push(t[r]);return e}function At(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function St(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function _t(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function Lt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var wt={};r.d(wt,"newCue",function(){return dt});var Dt=r(6),kt=r.n(Dt),It=r(1),Ot=r(2),Ct=r(0),Pt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xt=function(){function t(e){i(this,t),this.hls=e,this.onEvent=this.onEvent.bind(this);for(var r=arguments.length,a=Array(r>1?r-1:0),n=1;n<r;n++)a[n-1]=arguments[n];this.handledEvents=a,this.useGenericHandler=!0,this.registerListeners()}return t.prototype.destroy=function(){this.unregisterListeners()},t.prototype.isEventHandler=function(){return"object"===Pt(this.handledEvents)&&this.handledEvents.length&&"function"==typeof this.onEvent},t.prototype.registerListeners=function(){this.isEventHandler()&&this.handledEvents.forEach(function(t){if("hlsEventGeneric"===t)throw new Error("Forbidden event name: "+t);this.hls.on(t,this.onEvent)},this)},t.prototype.unregisterListeners=function(){this.isEventHandler()&&this.handledEvents.forEach(function(t){this.hls.off(t,this.onEvent)},this)},t.prototype.onEvent=function(t,e){this.onEventGeneric(t,e)},t.prototype.onEventGeneric=function(t,e){var r=function(t,e){var r="on"+t.replace("hls","");if("function"!=typeof this[r])throw new Error("Event "+t+" has no generic handler in this "+this.constructor.name+" class (tried "+r+")");return this[r].bind(this,e)};try{r.call(this,t,e).call()}catch(e){Ct.b.error("internal error happened while processing "+t+":"+e.message),this.hls.trigger(It.a.ERROR,{type:Ot.b.OTHER_ERROR,details:Ot.a.INTERNAL_EXCEPTION,fatal:!1,event:t,err:e})}},t}(),Ft=xt,Nt=/^(\d+)x(\d+)$/,Mt=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,Ut=function(){function t(e){a(this,t),"string"==typeof e&&(e=t.parseAttrList(e));for(var r in e)e.hasOwnProperty(r)&&(this[r]=e[r])}return t.prototype.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},t.prototype.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;i<e.length/2;i++)r[i]=parseInt(e.slice(2*i,2*i+2),16);return r}return null},t.prototype.hexadecimalIntegerAsNumber=function(t){var e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e},t.prototype.decimalFloatingPoint=function(t){return parseFloat(this[t])},t.prototype.enumeratedString=function(t){return this[t]},t.prototype.decimalResolution=function(t){var e=Nt.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(Mt.lastIndex=0;null!==(e=Mt.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1]]=i}return r},t}(),Bt=Ut,Gt={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}},Ht=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),jt=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,Kt=/#EXT-X-MEDIA:(.*)/g,Wt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)(\S+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),Vt=/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/,Yt=function(){function t(){u(this,t),this.method=null,this.key=null,this.iv=null,this._uri=null}return Ht(t,[{key:"uri",get:function(){return!this._uri&&this.reluri&&(this._uri=kt.a.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}]),t}(),zt=function(){function t(){u(this,t),this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[]}return t.prototype.createInitializationVector=function(t){for(var e=new Uint8Array(16),r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e},t.prototype.fragmentDecryptdataFromLevelkey=function(t,e){var r=t;return t&&t.method&&t.uri&&!t.iv&&(r=new Yt,r.method=t.method,r.baseuri=t.baseuri,r.reluri=t.reluri,r.iv=this.createInitializationVector(e)),r},t.prototype.cloneObj=function(t){return JSON.parse(JSON.stringify(t))},Ht(t,[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=kt.a.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(t){this._url=t}},{key:"programDateTime",get:function(){return!this._programDateTime&&this.rawProgramDateTime&&(this._programDateTime=new Date(Date.parse(this.rawProgramDateTime))),this._programDateTime}},{key:"byteRange",get:function(){if(!this._byteRange){var t=this._byteRange=[];if(this.rawByteRange){var e=this.rawByteRange.split("@",2);if(1===e.length){var r=this.lastByteRangeEndOffset;t[0]=r||0}else t[0]=parseInt(e[1]);t[1]=parseInt(e[0])+t[0]}}return this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}}]),t}(),Xt=function(t){function e(r){u(this,e);var i=s(this,t.call(this,r,It.a.MANIFEST_LOADING,It.a.LEVEL_LOADING,It.a.AUDIO_TRACK_LOADING,It.a.SUBTITLE_TRACK_LOADING));return i.loaders={},i}return l(e,t),e.prototype.destroy=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={},Ft.prototype.destroy.call(this)},e.prototype.onManifestLoading=function(t){this.load(t.url,{type:"manifest"})},e.prototype.onLevelLoading=function(t){this.load(t.url,{type:"level",level:t.level,id:t.id})},e.prototype.onAudioTrackLoading=function(t){this.load(t.url,{type:"audioTrack",id:t.id})},e.prototype.onSubtitleTrackLoading=function(t){this.load(t.url,{type:"subtitleTrack",id:t.id})},e.prototype.load=function(t,e){var r=this.loaders[e.type];if(r){var i=r.context;if(i&&i.url===t)return void Ct.b.trace("playlist request ongoing");Ct.b.warn("abort previous loader for type:"+e.type),r.abort()}var a=this.hls.config,n=void 0,o=void 0,s=void 0,l=void 0;"manifest"===e.type?(n=a.manifestLoadingMaxRetry,o=a.manifestLoadingTimeOut,s=a.manifestLoadingRetryDelay,l=a.manifestLoadingMaxRetryTimeout):(n=a.levelLoadingMaxRetry,o=a.levelLoadingTimeOut,s=a.levelLoadingRetryDelay,l=a.levelLoadingMaxRetryTimeout,Ct.b.log("loading playlist for "+e.type+" "+(e.level||e.id))),r=this.loaders[e.type]=e.loader=void 0!==a.pLoader?new a.pLoader(a):new a.loader(a),e.url=t,e.responseType="";var u=void 0,d=void 0;u={timeout:o,maxRetry:n,retryDelay:s,maxRetryDelay:l},d={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},r.load(e,u,d)},e.prototype.resolve=function(t,e){return kt.a.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},e.prototype.parseMasterPlaylist=function(t,e){var r=[],i=void 0;for(jt.lastIndex=0;null!=(i=jt.exec(t));){var a={},o=a.attrs=new Bt(i[1]);a.url=this.resolve(i[2],e);var s=o.decimalResolution("RESOLUTION");s&&(a.width=s.width,a.height=s.height),a.bitrate=o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),a.name=o.NAME,function(t,e){["video","audio"].forEach(function(r){var i=t.filter(function(t){return n(t,r)});if(i.length){var a=i.filter(function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)});e[r+"Codec"]=a.length>0?a[0]:i[0],t=t.filter(function(t){return-1===i.indexOf(t)})}}),e.unknownCodecs=t}([].concat((o.CODECS||"").split(/[ ,]+/)),a),a.videoCodec&&-1!==a.videoCodec.indexOf("avc1")&&(a.videoCodec=this.avc1toavcoti(a.videoCodec)),r.push(a)}return r},e.prototype.parseMasterPlaylistMedia=function(t,e,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],a=void 0,n=[],o=0;for(Kt.lastIndex=0;null!==(a=Kt.exec(t));){var s={},l=new Bt(a[1]);if(l.TYPE===r){if(s.groupId=l["GROUP-ID"],s.name=l.NAME,s.type=r,s.default="YES"===l.DEFAULT,s.autoselect="YES"===l.AUTOSELECT,s.forced="YES"===l.FORCED,l.URI&&(s.url=this.resolve(l.URI,e)),s.lang=l.LANGUAGE,s.name||(s.name=s.lang),i.length){var u=d(i,s.groupId);s.audioCodec=u?u.codec:i[0].codec}s.id=o++,n.push(s)}}return n},e.prototype.avc1toavcoti=function(t){var e,r=t.split(".");return r.length>2?(e=r.shift()+".",e+=parseInt(r.shift()).toString(16),e+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):e=t,e},e.prototype.parseLevelPlaylist=function(t,e,r,i){var a,n,o=0,s=0,l={type:null,version:null,url:e,fragments:[],live:!0,startSN:0},u=new Yt,d=0,h=null,c=new zt;for(Wt.lastIndex=0;null!==(a=Wt.exec(t));){var f=a[1];if(f){c.duration=parseFloat(f);var p=(" "+a[2]).slice(1);c.title=p||null,c.tagList.push(p?["INF",f,p]:["INF",f])}else if(a[3]){if(!isNaN(c.duration)){var g=o++;c.type=i,c.start=s,c.levelkey=u,c.sn=g,c.level=r,c.cc=d,c.baseurl=e,c.relurl=(" "+a[3]).slice(1),l.fragments.push(c),h=c,s+=c.duration,c=new zt}}else if(a[4]){if(c.rawByteRange=(" "+a[4]).slice(1),h){var v=h.byteRangeEndOffset;v&&(c.lastByteRangeEndOffset=v)}}else if(a[5])c.rawProgramDateTime=(" "+a[5]).slice(1),c.tagList.push(["PROGRAM-DATE-TIME",c.rawProgramDateTime]),void 0===l.programDateTime&&(l.programDateTime=new Date(new Date(Date.parse(a[5]))-1e3*s));else{for(a=a[0].match(Vt),n=1;n<a.length&&void 0===a[n];n++);var y=(" "+a[n+1]).slice(1),m=(" "+a[n+2]).slice(1);switch(a[n]){case"#":c.tagList.push(m?[y,m]:[y]);break;case"PLAYLIST-TYPE":l.type=y.toUpperCase();break;case"MEDIA-SEQUENCE":o=l.startSN=parseInt(y);break;case"TARGETDURATION":l.targetduration=parseFloat(y);break;case"VERSION":l.version=parseInt(y);break;case"EXTM3U":break;case"ENDLIST":l.live=!1;break;case"DIS":d++,c.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":d=parseInt(y);break;case"KEY":var b=y,E=new Bt(b),T=E.enumeratedString("METHOD"),R=E.URI,A=E.hexadecimalInteger("IV");T&&(u=new Yt,R&&["AES-128","SAMPLE-AES"].indexOf(T)>=0&&(u.method=T,u.baseuri=e,u.reluri=R,u.key=null,u.iv=A));break;case"START":var S=y,_=new Bt(S),L=_.decimalFloatingPoint("TIME-OFFSET");isNaN(L)||(l.startTimeOffset=L);break;case"MAP":var w=new Bt(y);c.relurl=w.URI,c.rawByteRange=w.BYTERANGE,c.baseurl=e,c.level=r,c.type=i,c.sn="initSegment",l.initSegment=c,c=new zt;break;default:Ct.b.warn("line parsed but not handled: "+a)}}}return c=h,c&&!c.relurl&&(l.fragments.pop(),s-=c.duration),l.totalduration=s,l.averagetargetduration=s/l.fragments.length,l.endSN=o-1,l.startCC=l.fragments[0]?l.fragments[0].cc:0,l.endCC=d,l},e.prototype.loadsuccess=function(t,e,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=t.data,n=t.url,o=r.type,s=r.id,l=r.level,u=this.hls;if(this.loaders[o]=void 0,void 0!==n&&0!==n.indexOf("data:")||(n=r.url),e.tload=performance.now(),0===a.indexOf("#EXTM3U"))if(a.indexOf("#EXTINF:")>0){var d="audioTrack"!==o&&"subtitleTrack"!==o,h=isNaN(l)?isNaN(s)?0:s:l,c=this.parseLevelPlaylist(a,n,h,"audioTrack"===o?"audio":"subtitleTrack"===o?"subtitle":"main");c.tload=e.tload,"manifest"===o&&u.trigger(It.a.MANIFEST_LOADED,{levels:[{url:n,details:c}],audioTracks:[],url:n,stats:e,networkDetails:i}),e.tparsed=performance.now(),c.targetduration?d?u.trigger(It.a.LEVEL_LOADED,{details:c,level:l||0,id:s||0,stats:e,networkDetails:i}):"audioTrack"===o?u.trigger(It.a.AUDIO_TRACK_LOADED,{details:c,id:s,stats:e,networkDetails:i}):"subtitleTrack"===o&&u.trigger(It.a.SUBTITLE_TRACK_LOADED,{details:c,id:s,stats:e,networkDetails:i}):u.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:Ot.a.MANIFEST_PARSING_ERROR,fatal:!0,url:n,reason:"invalid targetduration",networkDetails:i})}else{var f=this.parseMasterPlaylist(a,n);if(f.length){var p=f.map(function(t){return{id:t.attrs.AUDIO,codec:t.audioCodec}}),g=this.parseMasterPlaylistMedia(a,n,"AUDIO",p),v=this.parseMasterPlaylistMedia(a,n,"SUBTITLES");if(g.length){var y=!1;g.forEach(function(t){t.url||(y=!0)}),!1===y&&f[0].audioCodec&&!f[0].attrs.AUDIO&&(Ct.b.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main"}))}u.trigger(It.a.MANIFEST_LOADED,{levels:f,audioTracks:g,subtitles:v,url:n,stats:e,networkDetails:i})}else u.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:Ot.a.MANIFEST_PARSING_ERROR,fatal:!0,url:n,reason:"no level found in manifest",networkDetails:i})}else u.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:Ot.a.MANIFEST_PARSING_ERROR,fatal:!0,url:n,reason:"no EXTM3U delimiter",networkDetails:i})},e.prototype.loaderror=function(t,e){var r,i,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=e.loader;switch(e.type){case"manifest":r=Ot.a.MANIFEST_LOAD_ERROR,i=!0;break;case"level":r=Ot.a.LEVEL_LOAD_ERROR,i=!1;break;case"audioTrack":r=Ot.a.AUDIO_TRACK_LOAD_ERROR,i=!1}n&&(n.abort(),this.loaders[e.type]=void 0),this.hls.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:r,fatal:i,url:n.url,loader:n,response:t,context:e,networkDetails:a})},e.prototype.loadtimeout=function(t,e){var r,i,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=e.loader;switch(e.type){case"manifest":r=Ot.a.MANIFEST_LOAD_TIMEOUT,i=!0;break;case"level":r=Ot.a.LEVEL_LOAD_TIMEOUT,i=!1;break;case"audioTrack":r=Ot.a.AUDIO_TRACK_LOAD_TIMEOUT,i=!1}n&&(n.abort(),this.loaders[e.type]=void 0),this.hls.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:r,fatal:i,url:n.url,loader:n,context:e,networkDetails:a})},e}(Ft),qt=Xt,Qt=function(t){function e(r){h(this,e);var i=c(this,t.call(this,r,It.a.FRAG_LOADING));return i.loaders={},i}return f(e,t),e.prototype.destroy=function(){var t=this.loaders;for(var e in t){var r=t[e];r&&r.destroy()}this.loaders={},Ft.prototype.destroy.call(this)},e.prototype.onFragLoading=function(t){var e=t.frag,r=e.type,i=this.loaders[r],a=this.hls.config;e.loaded=0,i&&(Ct.b.warn("abort previous fragment loader for type:"+r),i.abort()),i=this.loaders[r]=e.loader=void 0!==a.fLoader?new a.fLoader(a):new a.loader(a);var n=void 0,o=void 0,s=void 0;n={url:e.url,frag:e,responseType:"arraybuffer",progressData:!1};var l=e.byteRangeStartOffset,u=e.byteRangeEndOffset;isNaN(l)||isNaN(u)||(n.rangeStart=l,n.rangeEnd=u),o={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout},s={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},i.load(n,o,s)},e.prototype.loadsuccess=function(t,e,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=t.data,n=r.frag;n.loader=void 0,this.loaders[n.type]=void 0,this.hls.trigger(It.a.FRAG_LOADED,{payload:a,frag:n,stats:e,networkDetails:i})},e.prototype.loaderror=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=e.loader;i&&i.abort(),this.loaders[e.type]=void 0,this.hls.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:Ot.a.FRAG_LOAD_ERROR,fatal:!1,frag:e.frag,response:t,networkDetails:r})},e.prototype.loadtimeout=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=e.loader;i&&i.abort(),this.loaders[e.type]=void 0,this.hls.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:Ot.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e.frag,networkDetails:r})},e.prototype.loadprogress=function(t,e,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=e.frag;a.loaded=t.loaded,this.hls.trigger(It.a.FRAG_LOAD_PROGRESS,{frag:a,stats:t,networkDetails:i})},e}(Ft),Jt=Qt,$t=function(t){function e(r){p(this,e);var i=g(this,t.call(this,r,It.a.KEY_LOADING));return i.loaders={},i.decryptkey=null,i.decrypturl=null,i}return v(e,t),e.prototype.destroy=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={},Ft.prototype.destroy.call(this)},e.prototype.onKeyLoading=function(t){var e=t.frag,r=e.type,i=this.loaders[r],a=e.decryptdata,n=a.uri;if(n!==this.decrypturl||null===this.decryptkey){var o=this.hls.config;i&&(Ct.b.warn("abort previous key loader for type:"+r),i.abort()),e.loader=this.loaders[r]=new o.loader(o),this.decrypturl=n,this.decryptkey=null;var s=void 0,l=void 0,u=void 0;s={url:n,frag:e,responseType:"arraybuffer"},l={timeout:o.fragLoadingTimeOut,maxRetry:o.fragLoadingMaxRetry,retryDelay:o.fragLoadingRetryDelay,maxRetryDelay:o.fragLoadingMaxRetryTimeout},u={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},e.loader.load(s,l,u)}else this.decryptkey&&(a.key=this.decryptkey,this.hls.trigger(It.a.KEY_LOADED,{frag:e}))},e.prototype.loadsuccess=function(t,e,r){var i=r.frag;this.decryptkey=i.decryptdata.key=new Uint8Array(t.data),i.loader=void 0,this.loaders[i.type]=void 0,this.hls.trigger(It.a.KEY_LOADED,{frag:i})},e.prototype.loaderror=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),this.loaders[e.type]=void 0,this.hls.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:Ot.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:t})},e.prototype.loadtimeout=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),this.loaders[e.type]=void 0,this.hls.trigger(It.a.ERROR,{type:Ot.b.NETWORK_ERROR,details:Ot.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},e}(Ft),Zt=$t,te={search:function(t,e){for(var r=0,i=t.length-1,a=null,n=null;r<=i;){a=(r+i)/2|0,n=t[a];var o=e(n);if(o>0)r=a+1;else{if(!(o<0))return n;i=a-1}}return null}},ee=te,re={isBuffered:function(t,e){if(t)for(var r=t.buffered,i=0;i<r.length;i++)if(e>=r.start(i)&&e<=r.end(i))return!0;return!1},bufferInfo:function(t,e,r){if(t){var i,a=t.buffered,n=[];for(i=0;i<a.length;i++)n.push({start:a.start(i),end:a.end(i)});return this.bufferedInfo(n,e,r)}return{len:0,start:e,end:e,nextStart:void 0}},bufferedInfo:function(t,e,r){var i,a,n,o,s,l=[];for(t.sort(function(t,e){var r=t.start-e.start;return r||e.end-t.end}),s=0;s<t.length;s++){var u=l.length;if(u){var d=l[u-1].end;t[s].start-d<r?t[s].end>d&&(l[u-1].end=t[s].end):l.push(t[s])}else l.push(t[s])}for(s=0,i=0,a=n=e;s<l.length;s++){var h=l[s].start,c=l[s].end;if(e+r>=h&&e<c)a=h,n=c,i=n-e;else if(e+r<h){o=h;break}}return{len:i,start:a,end:n,nextStart:o}}},ie=re,ae=r(7),ne=r(5),oe=r.n(ne),se=r(9),le=r.n(se),ue=y(),de=function(){function t(e,r){m(this,t),this.hls=e,this.id=r;var i=this.observer=new oe.a,a=e.config;i.trigger=function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),a=1;a<e;a++)r[a-1]=arguments[a];i.emit.apply(i,[t,t].concat(r))},i.off=function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),a=1;a<e;a++)r[a-1]=arguments[a];i.removeListener.apply(i,[t].concat(r))};var n=function(t,r){r=r||{},r.frag=this.frag,r.id=this.id,e.trigger(t,r)}.bind(this);i.on(It.a.FRAG_DECRYPTED,n),i.on(It.a.FRAG_PARSING_INIT_SEGMENT,n),i.on(It.a.FRAG_PARSING_DATA,n),i.on(It.a.FRAG_PARSED,n),i.on(It.a.ERROR,n),i.on(It.a.FRAG_PARSING_METADATA,n),i.on(It.a.FRAG_PARSING_USERDATA,n),i.on(It.a.INIT_PTS_FOUND,n);var o={mp4:ue.isTypeSupported("video/mp4"),mpeg:ue.isTypeSupported("audio/mpeg"),mp3:ue.isTypeSupported('audio/mp4; codecs="mp3"')},s=navigator.vendor;if(a.enableWorker&&"undefined"!=typeof Worker){Ct.b.log("demuxing in webworker");var l=void 0;try{l=this.w=le()(10),this.onwmsg=this.onWorkerMessage.bind(this),l.addEventListener("message",this.onwmsg),l.onerror=function(t){e.trigger(It.a.ERROR,{type:Ot.b.OTHER_ERROR,details:Ot.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",err:{message:t.message+" ("+t.filename+":"+t.lineno+")"}})},l.postMessage({cmd:"init",typeSupported:o,vendor:s,id:r,config:JSON.stringify(a)})}catch(t){Ct.b.error("error while initializing DemuxerWorker, fallback on DemuxerInline"),l&&URL.revokeObjectURL(l.objectURL),this.demuxer=new ae.a(i,o,a,s),this.w=void 0}}else this.demuxer=new ae.a(i,o,a,s)}return t.prototype.destroy=function(){var t=this.w;if(t)t.removeEventListener("message",this.onwmsg),t.terminate(),this.w=null;else{var e=this.demuxer;e&&(e.destroy(),this.demuxer=null)}var r=this.observer;r&&(r.removeAllListeners(),this.observer=null)},t.prototype.push=function(t,e,r,i,a,n,o,s){var l=this.w,u=isNaN(a.startDTS)?a.start:a.startDTS,d=a.decryptdata,h=this.frag,c=!(h&&a.cc===h.cc),f=!(h&&a.level===h.level),p=h&&a.sn===h.sn+1,g=!f&&p;if(c&&Ct.b.log(this.id+":discontinuity detected"),f&&Ct.b.log(this.id+":switch detected"),this.frag=a,l)l.postMessage({cmd:"demux",data:t,decryptdata:d,initSegment:e,audioCodec:r,videoCodec:i,timeOffset:u,discontinuity:c,trackSwitch:f,contiguous:g,duration:n,accurateTimeOffset:o,defaultInitPTS:s},t instanceof ArrayBuffer?[t]:[]);else{var v=this.demuxer;v&&v.push(t,d,e,r,i,u,c,f,g,n,o,s)}},t.prototype.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":URL.revokeObjectURL(this.w.objectURL);break;case It.a.FRAG_PARSING_DATA:e.data.data1=new Uint8Array(e.data1),e.data2&&(e.data.data2=new Uint8Array(e.data2));default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},t}(),he=de,ce={toString:function(t){for(var e="",r=t.length,i=0;i<r;i++)e+="["+t.start(i).toFixed(3)+","+t.end(i).toFixed(3)+"]";return e}},fe=ce,pe=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),ge={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_LEVEL:"WAITING_LEVEL",PARSING:"PARSING",PARSED:"PARSED",BUFFER_FLUSHING:"BUFFER_FLUSHING",ENDED:"ENDED",ERROR:"ERROR"},ve=function(t){function e(r){D(this,e);var i=k(this,t.call(this,r,It.a.MEDIA_ATTACHED,It.a.MEDIA_DETACHING,It.a.MANIFEST_LOADING,It.a.MANIFEST_PARSED,It.a.LEVEL_LOADED,It.a.KEY_LOADED,It.a.FRAG_LOADED,It.a.FRAG_LOAD_EMERGENCY_ABORTED,It.a.FRAG_PARSING_INIT_SEGMENT,It.a.FRAG_PARSING_DATA,It.a.FRAG_PARSED,It.a.ERROR,It.a.AUDIO_TRACK_SWITCHING,It.a.AUDIO_TRACK_SWITCHED,It.a.BUFFER_CREATED,It.a.BUFFER_APPENDED,It.a.BUFFER_FLUSHED));return i.config=r.config,i.audioCodecSwap=!1,i.ticks=0,i._state=ge.STOPPED,i.ontick=i.tick.bind(i),i}return I(e,t),e.prototype.destroy=function(){this.stopLoad(),this.timer&&(clearInterval(this.timer),this.timer=null),Ft.prototype.destroy.call(this),this.state=ge.STOPPED},e.prototype.startLoad=function(t){if(this.levels){var e=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.timer||(this.timer=setInterval(this.ontick,100)),this.level=-1,this.fragLoadError=0,!this.startFragRequested){var i=r.startLevel;-1===i&&(i=0,this.bitrateTest=!0),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}e>0&&-1===t&&(Ct.b.log("override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=ge.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this.forceStartLoad=!0,this.state=ge.STOPPED},e.prototype.stopLoad=function(){var t=this.fragCurrent;t&&(t.loader&&t.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=ge.STOPPED,this.forceStartLoad=!1},e.prototype.tick=function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},e.prototype.doTick=function(){switch(this.state){case ge.ERROR:break;case ge.BUFFER_FLUSHING:this.fragLoadError=0;break;case ge.IDLE:this._doTickIdle();break;case ge.WAITING_LEVEL:var t=this.levels[this.level];t&&t.details&&(this.state=ge.IDLE);break;case ge.FRAG_LOADING_WAITING_RETRY:var e=performance.now(),r=this.retryDate;(!r||e>=r||this.media&&this.media.seeking)&&(Ct.b.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=ge.IDLE);break;case ge.ERROR:case ge.STOPPED:case ge.FRAG_LOADING:case ge.PARSING:case ge.PARSED:case ge.ENDED:}this._checkBuffer(),this._checkFragmentChanged()},e.prototype._doTickIdle=function(){var t=this.hls,e=t.config,r=this.media;if(void 0!==this.levelLastLoaded&&(r||!this.startFragRequested&&e.startFragPrefetch)){var i=void 0;i=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var a=t.nextLoadLevel,n=this.levels[a];if(n){var o=n.bitrate,s=void 0;s=o?Math.max(8*e.maxBufferSize/o,e.maxBufferLength):e.maxBufferLength,s=Math.min(s,e.maxMaxBufferLength);var l=ie.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,e.maxBufferHole),u=l.len;if(!(u>=s)){Ct.b.trace("buffer length of "+u.toFixed(3)+" is below max of "+s.toFixed(3)+". checking for more payload ..."),this.level=t.nextLoadLevel=a;var d=n.details;if(void 0===d||d.live&&this.levelLastLoaded!==a)return void(this.state=ge.WAITING_LEVEL);var h=this.fragPrevious;if(!d.live&&h&&!h.backtracked&&h.sn===d.endSN&&!l.nextStart){if(Math.min(r.duration,h.start+h.duration)-Math.max(l.end,h.start)<=Math.max(.2,h.duration)){var c={};return this.altAudio&&(c.type="video"),this.hls.trigger(It.a.BUFFER_EOS,c),void(this.state=ge.ENDED)}}this._fetchPayloadOrEos(i,l,d)}}}},e.prototype._fetchPayloadOrEos=function(t,e,r){var i=this.fragPrevious,a=this.level,n=r.fragments,o=n.length;if(0!==o){var s=n[0].start,l=n[o-1].start+n[o-1].duration,u=e.end,d=void 0;if(r.initSegment&&!r.initSegment.data)d=r.initSegment;else if(r.live){var h=this.config.initialLiveManifestSize;if(o<h)return void Ct.b.warn("Can not start playback of a level, reason: not enough fragments "+o+" < "+h);if(null===(d=this._ensureFragmentAtLivePoint(r,u,s,l,i,n,o)))return}else u<s&&(d=n[0]);d||(d=this._findFragment(s,i,o,n,u,l,r)),d&&this._loadFragmentOrKey(d,a,r,t,u)}},e.prototype._ensureFragmentAtLivePoint=function(t,e,r,i,a,n,o){var s=this.hls.config,l=this.media,u=void 0,d=void 0!==s.liveMaxLatencyDuration?s.liveMaxLatencyDuration:s.liveMaxLatencyDurationCount*t.targetduration;if(e<Math.max(r-s.maxFragLookUpTolerance,i-d)){var h=this.liveSyncPosition=this.computeLivePosition(r,t);Ct.b.log("buffer end: "+e.toFixed(3)+" is located too far from the end of live sliding playlist, reset currentTime to : "+h.toFixed(3)),e=h,l&&l.readyState&&l.duration>h&&(l.currentTime=h),this.nextLoadPosition=h}if(t.PTSKnown&&e>i&&l&&l.readyState)return null;if(this.startFragRequested&&!t.PTSKnown){if(a){var c=a.sn+1;if(c>=t.startSN&&c<=t.endSN){var f=n[c-t.startSN];a.cc===f.cc&&(u=f,Ct.b.log("live playlist, switching playlist, load frag with next SN: "+u.sn))}u||(u=ee.search(n,function(t){return a.cc-t.cc}))&&Ct.b.log("live playlist, switching playlist, load frag with same CC: "+u.sn)}u||(u=n[Math.min(o-1,Math.round(o/2))],Ct.b.log("live playlist, switching playlist, unknown, load middle frag : "+u.sn))}return u},e.prototype._findFragment=function(t,e,r,i,a,n,o){var s=this.hls.config,l=void 0,u=void 0,d=s.maxFragLookUpTolerance,h=e?i[e.sn-i[0].sn+1]:void 0,c=function(t){var e=Math.min(d,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-e<=a?1:t.start-e>a&&t.start?-1:0};if(a<n?(a>n-d&&(d=0),u=h&&!c(h)?h:ee.search(i,c)):u=i[r-1],u){l=u;var f=l.sn-o.startSN,p=e&&l.level===e.level,g=i[f-1],v=i[f+1];if(e&&l.sn===e.sn)if(p&&!l.backtracked)if(l.sn<o.endSN){var y=e.deltaPTS;y&&y>s.maxBufferHole&&e.dropped&&f?(l=g,Ct.b.warn("SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this"),e.loadCounter--):(l=v,Ct.b.log("SN just loaded, load next one: "+l.sn))}else l=null;else l.backtracked&&(v&&v.backtracked?(Ct.b.warn("Already backtracked from fragment "+v.sn+", will not backtrack to fragment "+l.sn+". Loading fragment "+v.sn),l=v):(Ct.b.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),l.dropped=0,g?(g.loadCounter&&g.loadCounter--,l=g,l.backtracked=!0):f&&(l=null)))}return l},e.prototype._loadFragmentOrKey=function(t,e,r,i,a){var n=this.hls,o=n.config;if(!t.decryptdata||null==t.decryptdata.uri||null!=t.decryptdata.key){if(Ct.b.log("Loading "+t.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+e+", currentTime:"+i.toFixed(3)+",bufferEnd:"+a.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,t.loadCounter){t.loadCounter++;var s=o.fragLoadingLoopThreshold;if(t.loadCounter>s&&Math.abs(this.fragLoadIdx-t.loadIdx)<s)return void n.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.FRAG_LOOP_LOADING_ERROR,fatal:!1,frag:t})}else t.loadCounter=1;return t.loadIdx=this.fragLoadIdx,t.autoLevel=n.autoLevelEnabled,t.bitrateTest=this.bitrateTest,this.fragCurrent=t,this.startFragRequested=!0,isNaN(t.sn)||t.bitrateTest||(this.nextLoadPosition=t.start+t.duration),n.trigger(It.a.FRAG_LOADING,{frag:t}),this.demuxer||(this.demuxer=new he(n,"main")),void(this.state=ge.FRAG_LOADING)}Ct.b.log("Loading key for "+t.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+e),this.state=ge.KEY_LOADING,n.trigger(It.a.KEY_LOADING,{frag:t})},e.prototype.getBufferedFrag=function(t){return ee.search(this._bufferedFrags,function(e){return t<e.startPTS?-1:t>e.endPTS?1:0})},e.prototype.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.endPTS+.5):null},e.prototype._checkFragmentChanged=function(){var t,e,r=this.media;if(r&&r.readyState&&!1===r.seeking&&(e=r.currentTime,e>r.playbackRate*this.lastCurrentTime&&(this.lastCurrentTime=e),ie.isBuffered(r,e)?t=this.getBufferedFrag(e):ie.isBuffered(r,e+.1)&&(t=this.getBufferedFrag(e+.1)),t)){var i=t;if(i!==this.fragPlaying){this.hls.trigger(It.a.FRAG_CHANGED,{frag:i});var a=i.level;this.fragPlaying&&this.fragPlaying.level===a||this.hls.trigger(It.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=i}}},e.prototype.immediateLevelSwitch=function(){if(Ct.b.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var t=this.media,e=void 0;t?(e=t.paused,t.pause()):e=!0,this.previouslyPaused=e}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},e.prototype.immediateLevelSwitchEnd=function(){var t=this.media;t&&t.buffered.length&&(this.immediateSwitch=!1,ie.isBuffered(t,t.currentTime)&&(t.currentTime-=1e-4),this.previouslyPaused||t.play())},e.prototype.nextLevelSwitch=function(){var t=this.media;if(t&&t.readyState){var e=void 0,r=void 0,i=void 0;if(void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),r=this.getBufferedFrag(t.currentTime),r&&r.startPTS>1&&this.flushMainBuffer(0,r.startPTS-1),t.paused)e=0;else{var a=this.hls.nextLoadLevel,n=this.levels[a],o=this.fragLastKbps;e=o&&this.fragCurrent?this.fragCurrent.duration*n.bitrate/(1e3*o)+1:0}if((i=this.getBufferedFrag(t.currentTime+e))&&(i=this.followingBufferedFrag(i))){var s=this.fragCurrent;s&&s.loader&&s.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(i.maxStartPTS,Number.POSITIVE_INFINITY)}}},e.prototype.flushMainBuffer=function(t,e){this.state=ge.BUFFER_FLUSHING;var r={startOffset:t,endOffset:e};this.altAudio&&(r.type="video"),this.hls.trigger(It.a.BUFFER_FLUSHING,r)},e.prototype.onMediaAttached=function(t){var e=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),this.onvended=this.onMediaEnded.bind(this),e.addEventListener("seeking",this.onvseeking),e.addEventListener("seeked",this.onvseeked),e.addEventListener("ended",this.onvended);var r=this.config;this.levels&&r.autoStartLoad&&this.hls.startLoad(r.startPosition)},e.prototype.onMediaDetaching=function(){var t=this.media;t&&t.ended&&(Ct.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var e=this.levels;e&&e.forEach(function(t){t.details&&t.details.fragments.forEach(function(t){t.loadCounter=void 0,t.backtracked=void 0})}),t&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("seeked",this.onvseeked),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()},e.prototype.onMediaSeeking=function(){var t=this.media,e=t?t.currentTime:void 0,r=this.config;isNaN(e)||Ct.b.log("media seeking to "+e.toFixed(3));var i=this.mediaBuffer?this.mediaBuffer:t,a=ie.bufferInfo(i,e,this.config.maxBufferHole);if(this.state===ge.FRAG_LOADING){var n=this.fragCurrent;if(0===a.len&&n){var o=r.maxFragLookUpTolerance,s=n.start-o,l=n.start+n.duration+o;e<s||e>l?(n.loader&&(Ct.b.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),n.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=ge.IDLE):Ct.b.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===ge.ENDED&&(0===a.len&&(this.fragPrevious=0),this.state=ge.IDLE);t&&(this.lastCurrentTime=e),this.state!==ge.FRAG_LOADING&&void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*r.fragLoadingLoopThreshold),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=e),this.tick()},e.prototype.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:void 0;isNaN(e)||Ct.b.log("media seeked to "+e.toFixed(3)),this.tick()},e.prototype.onMediaEnded=function(){Ct.b.log("media ended"),this.startPosition=this.lastCurrentTime=0},e.prototype.onManifestLoading=function(){Ct.b.log("trigger BUFFER_RESET"),this.hls.trigger(It.a.BUFFER_RESET),this._bufferedFrags=[],this.stalled=!1,this.startPosition=this.lastCurrentTime=0},e.prototype.onManifestParsed=function(t){var e,r=!1,i=!1;t.levels.forEach(function(t){(e=t.audioCodec)&&(-1!==e.indexOf("mp4a.40.2")&&(r=!0),-1!==e.indexOf("mp4a.40.5")&&(i=!0))}),this.audioCodecSwitch=r&&i,this.audioCodecSwitch&&Ct.b.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1;var a=this.config;(a.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(a.startPosition)},e.prototype.onLevelLoaded=function(t){var e=t.details,r=t.level,i=this.levels[this.levelLastLoaded],a=this.levels[r],n=e.totalduration,o=0;if(Ct.b.log("level "+r+" loaded ["+e.startSN+","+e.endSN+"],duration:"+n),e.live){var s=a.details;s&&e.fragments.length>0?(T(s,e),o=e.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(o,s),e.PTSKnown&&!isNaN(o)?Ct.b.log("live playlist sliding:"+o.toFixed(3)):(Ct.b.log("live playlist - outdated PTS, unknown sliding"),w(this.fragPrevious,i,e))):(Ct.b.log("live playlist - first load, unknown sliding"),e.PTSKnown=!1,w(this.fragPrevious,i,e))}else e.PTSKnown=!1;if(a.details=e,this.levelLastLoaded=r,this.hls.trigger(It.a.LEVEL_UPDATED,{details:e,level:r}),!1===this.startFragRequested){if(-1===this.startPosition||-1===this.lastCurrentTime){var l=e.startTimeOffset;isNaN(l)?e.live?(this.startPosition=this.computeLivePosition(o,e),Ct.b.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(l<0&&(Ct.b.log("negative start time offset "+l+", count from end of last fragment"),l=o+n+l),Ct.b.log("start time offset found in playlist, adjust startPosition to "+l),this.startPosition=l),this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===ge.WAITING_LEVEL&&(this.state=ge.IDLE),this.tick()},e.prototype.onKeyLoaded=function(){this.state===ge.KEY_LOADING&&(this.state=ge.IDLE,this.tick())},e.prototype.onFragLoaded=function(t){var e=this.fragCurrent,r=t.frag;if(this.state===ge.FRAG_LOADING&&e&&"main"===r.type&&r.level===e.level&&r.sn===e.sn){var i=t.stats,a=this.levels[e.level],n=a.details;if(Ct.b.log("Loaded "+e.sn+" of ["+n.startSN+" ,"+n.endSN+"],level "+e.level),this.bitrateTest=!1,this.stats=i,!0===r.bitrateTest&&this.hls.nextLoadLevel)this.state=ge.IDLE,this.startFragRequested=!1,i.tparsed=i.tbuffered=performance.now(),this.hls.trigger(It.a.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=ge.IDLE,i.tparsed=i.tbuffered=performance.now(),n.initSegment.data=t.payload,this.hls.trigger(It.a.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.tick();else{this.state=ge.PARSING;var o=n.totalduration,s=e.level,l=e.sn,u=this.config.defaultAudioCodec||a.audioCodec;this.audioCodecSwap&&(Ct.b.log("swapping playlist audio codec"),void 0===u&&(u=this.lastAudioCodec),u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,Ct.b.log("Parsing "+l+" of ["+n.startSN+" ,"+n.endSN+"],level "+s+", cc "+e.cc);var d=this.demuxer;d||(d=this.demuxer=new he(this.hls,"main"));var h=this.media,c=h&&h.seeking,f=!c&&(n.PTSKnown||!n.live),p=n.initSegment?n.initSegment.data:[];d.push(t.payload,p,u,a.videoCodec,e,o,f,void 0)}}this.fragLoadError=0},e.prototype.onFragParsingInitSegment=function(t){var e=this.fragCurrent,r=t.frag;if(e&&"main"===t.id&&r.sn===e.sn&&r.level===e.level&&this.state===ge.PARSING){var i,a,n=t.tracks;if(n.audio&&this.altAudio&&delete n.audio,a=n.audio){var o=this.levels[this.level].audioCodec,s=navigator.userAgent.toLowerCase();o&&this.audioCodecSwap&&(Ct.b.log("swapping playlist audio codec"),o=-1!==o.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==a.metadata.channelCount&&-1===s.indexOf("firefox")&&(o="mp4a.40.5"),-1!==s.indexOf("android")&&"audio/mpeg"!==a.container&&(o="mp4a.40.2",Ct.b.log("Android: force audio codec to "+o)),a.levelCodec=o,a.id=t.id}a=n.video,a&&(a.levelCodec=this.levels[this.level].videoCodec,a.id=t.id),this.hls.trigger(It.a.BUFFER_CODECS,n);for(i in n){a=n[i],Ct.b.log("main track:"+i+",container:"+a.container+",codecs[level/parsed]=["+a.levelCodec+"/"+a.codec+"]");var l=a.initSegment;l&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(It.a.BUFFER_APPENDING,{type:i,data:l,parent:"main",content:"initSegment"}))}this.tick()}},e.prototype.onFragParsingData=function(t){var e=this,r=this.fragCurrent,i=t.frag;if(r&&"main"===t.id&&i.sn===r.sn&&i.level===r.level&&("audio"!==t.type||!this.altAudio)&&this.state===ge.PARSING){var a=this.levels[this.level],n=r;if(isNaN(t.endPTS)&&(t.endPTS=t.startPTS+r.duration,t.endDTS=t.startDTS+r.duration),Ct.b.log("Parsed "+t.type+",PTS:["+t.startPTS.toFixed(3)+","+t.endPTS.toFixed(3)+"],DTS:["+t.startDTS.toFixed(3)+"/"+t.endDTS.toFixed(3)+"],nb:"+t.nb+",dropped:"+(t.dropped||0)),"video"===t.type)if(n.dropped=t.dropped,n.dropped)if(n.backtracked)Ct.b.warn("Already backtracked on this fragment, appending with the gap");else{var o=a.details;if(!o||n.sn!==o.startSN)return Ct.b.warn("missing video frame(s), backtracking fragment"),n.backtracked=!0,this.nextLoadPosition=t.startPTS,this.state=ge.IDLE,this.fragPrevious=n,void this.tick();Ct.b.warn("missing video frame(s) on first frag, appending with gap")}else n.backtracked=!1;var s=E(a.details,n,t.startPTS,t.endPTS,t.startDTS,t.endDTS),l=this.hls;l.trigger(It.a.LEVEL_PTS_UPDATED,{details:a.details,level:this.level,drift:s,type:t.type,start:t.startPTS,end:t.endPTS}),[t.data1,t.data2].forEach(function(r){r&&r.length&&e.state===ge.PARSING&&(e.appended=!0,e.pendingBuffering=!0,l.trigger(It.a.BUFFER_APPENDING,{type:t.type,data:r,parent:"main",content:"data"}))}),this.tick()}},e.prototype.onFragParsed=function(t){var e=this.fragCurrent,r=t.frag;e&&"main"===t.id&&r.sn===e.sn&&r.level===e.level&&this.state===ge.PARSING&&(this.stats.tparsed=performance.now(),this.state=ge.PARSED,this._checkAppendedParsed())},e.prototype.onAudioTrackSwitching=function(t){var e=!!t.url,r=t.id;if(!e){if(this.mediaBuffer!==this.media){Ct.b.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i.loader&&(Ct.b.log("switching to main audio track, cancel main fragment load"),i.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=ge.IDLE}var a=this.hls;a.trigger(It.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),a.trigger(It.a.AUDIO_TRACK_SWITCHED,{id:r}),this.altAudio=!1}},e.prototype.onAudioTrackSwitched=function(t){var e=t.id,r=!!this.hls.audioTracks[e].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(Ct.b.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()},e.prototype.onBufferCreated=function(t){var e=t.tracks,r=void 0,i=void 0,a=!1;for(var n in e){var o=e[n];"main"===o.id?(i=n,r=o,"video"===n&&(this.videoBuffer=e[n].buffer)):a=!0}a&&r?(Ct.b.log("alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},e.prototype.onBufferAppended=function(t){if("main"===t.parent){var e=this.state;e!==ge.PARSING&&e!==ge.PARSED||(this.pendingBuffering=t.pending>0,this._checkAppendedParsed())}},e.prototype._checkAppendedParsed=function(){if(!(this.state!==ge.PARSED||this.appended&&this.pendingBuffering)){var t=this.fragCurrent;if(t){var e=this.mediaBuffer?this.mediaBuffer:this.media;Ct.b.log("main buffered : "+fe.toString(e.buffered));var r=this._bufferedFrags.filter(function(t){return ie.isBuffered(e,(t.startPTS+t.endPTS)/2)});r.push(t),this._bufferedFrags=r.sort(function(t,e){return t.startPTS-e.startPTS}),this.fragPrevious=t;var i=this.stats;i.tbuffered=performance.now(),this.fragLastKbps=Math.round(8*i.total/(i.tbuffered-i.tfirst)),this.hls.trigger(It.a.FRAG_BUFFERED,{stats:i,frag:t,id:"main"}),this.state=ge.IDLE}this.tick()}},e.prototype.onError=function(t){var e=t.frag||this.fragCurrent;if(!e||"main"===e.type){var r=!!this.media&&ie.isBuffered(this.media,this.media.currentTime)&&ie.isBuffered(this.media,this.media.currentTime+.5);switch(t.details){case Ot.a.FRAG_LOAD_ERROR:case Ot.a.FRAG_LOAD_TIMEOUT:case Ot.a.KEY_LOAD_ERROR:case Ot.a.KEY_LOAD_TIMEOUT:if(!t.fatal)if(this.fragLoadError+1<=this.config.fragLoadingMaxRetry){var i=Math.min(Math.pow(2,this.fragLoadError)*this.config.fragLoadingRetryDelay,this.config.fragLoadingMaxRetryTimeout);e.loadCounter=0,Ct.b.warn("mediaController: frag loading failed, retry in "+i+" ms"),this.retryDate=performance.now()+i,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=ge.FRAG_LOADING_WAITING_RETRY}else Ct.b.error("mediaController: "+t.details+" reaches max retry, redispatch as fatal ..."),t.fatal=!0,this.state=ge.ERROR;break;case Ot.a.FRAG_LOOP_LOADING_ERROR:t.fatal||(r?(this._reduceMaxBufferLength(e.duration),this.state=ge.IDLE):e.autoLevel&&0!==e.level||(t.fatal=!0,this.state=ge.ERROR));break;case Ot.a.LEVEL_LOAD_ERROR:case Ot.a.LEVEL_LOAD_TIMEOUT:this.state!==ge.ERROR&&(t.fatal?(this.state=ge.ERROR,Ct.b.warn("streamController: "+t.details+",switch to "+this.state+" state ...")):t.levelRetry||this.state!==ge.WAITING_LEVEL||(this.state=ge.IDLE));break;case Ot.a.BUFFER_FULL_ERROR:"main"!==t.parent||this.state!==ge.PARSING&&this.state!==ge.PARSED||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=ge.IDLE):(Ct.b.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}},e.prototype._reduceMaxBufferLength=function(t){var e=this.config;e.maxMaxBufferLength>=t&&(e.maxMaxBufferLength/=2,Ct.b.warn("main:reduce max buffer length to "+e.maxMaxBufferLength+"s"),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*e.fragLoadingLoopThreshold))},e.prototype._checkBuffer=function(){var t=this.media,e=this.config;if(t&&t.readyState){var r=t.currentTime,i=this.mediaBuffer?this.mediaBuffer:t,a=i.buffered;if(!this.loadedmetadata&&a.length){this.loadedmetadata=!0;var n=t.seeking?r:this.startPosition,o=ie.isBuffered(i,n),s=a.start(0),l=!o&&Math.abs(n-s)<e.maxSeekHole;(r!==n||l)&&(Ct.b.log("target start position:"+n),l&&(n=s,Ct.b.log("target start position not buffered, seek to buffered.start(0) "+n)),Ct.b.log("adjust currentTime from "+r+" to "+n),t.currentTime=n)}else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var u=ie.bufferInfo(t,r,0),d=!(t.paused||t.ended||0===t.buffered.length),h=r!==this.lastCurrentTime;if(h)this.stallReported&&(Ct.b.warn("playback not stuck anymore @"+r+", after "+Math.round(performance.now()-this.stalled)+"ms"),this.stallReported=!1),this.stalled=void 0,this.nudgeRetry=0;else if(d){var c=performance.now(),f=this.hls;if(this.stalled){var p=c-this.stalled,g=u.len,v=this.nudgeRetry||0;if(g<=.5&&p>1e3*e.lowBufferWatchdogPeriod){this.stallReported||(this.stallReported=!0,Ct.b.warn("playback stalling in low buffer @"+r),f.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:g}));var y=u.nextStart,m=y-r;if(y&&m<e.maxSeekHole&&m>0){this.nudgeRetry=++v;var b=v*e.nudgeOffset;Ct.b.log("adjust currentTime from "+t.currentTime+" to next buffered @ "+y+" + nudge "+b),t.currentTime=y+b,this.stalled=void 0,f.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.BUFFER_SEEK_OVER_HOLE,fatal:!1,hole:y+b-r})}}else if(g>.5&&p>1e3*e.highBufferWatchdogPeriod)if(this.stallReported||(this.stallReported=!0,Ct.b.warn("playback stalling in high buffer @"+r),f.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:g})),this.stalled=void 0,this.nudgeRetry=++v,v<e.nudgeMaxRetry){var E=t.currentTime,T=E+v*e.nudgeOffset;Ct.b.log("adjust currentTime from "+E+" to "+T),t.currentTime=T,f.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.BUFFER_NUDGE_ON_STALL,fatal:!1})}else Ct.b.error("still stuck in high buffer @"+r+" after "+e.nudgeMaxRetry+", raise fatal error"),f.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.BUFFER_STALLED_ERROR,fatal:!0})}else this.stalled=c,this.stallReported=!1}}}},e.prototype.onFragLoadEmergencyAborted=function(){this.state=ge.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},e.prototype.onBufferFlushed=function(){var t=this.mediaBuffer?this.mediaBuffer:this.media;this._bufferedFrags=this._bufferedFrags.filter(function(e){return ie.isBuffered(t,(e.startPTS+e.endPTS)/2)}),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.state=ge.IDLE,this.fragPrevious=null},e.prototype.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},e.prototype.computeLivePosition=function(t,e){var r=void 0!==this.config.liveSyncDuration?this.config.liveSyncDuration:this.config.liveSyncDurationCount*e.targetduration;return t+Math.max(0,e.totalduration-r)},pe(e,[{key:"state",set:function(t){if(this.state!==t){var e=this.state;this._state=t,Ct.b.log("main stream:"+e+"->"+t),this.hls.trigger(It.a.STREAM_STATE_TRANSITION,{previousState:e,nextState:t})}},get:function(){return this._state}},{key:"currentLevel",get:function(){var t=this.media;if(t){var e=this.getBufferedFrag(t.currentTime);if(e)return e.level}return-1}},{key:"nextBufferedFrag",get:function(){var t=this.media;return t?this.followingBufferedFrag(this.getBufferedFrag(t.currentTime)):null}},{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"liveSyncPosition",get:function(){return this._liveSyncPosition},set:function(t){this._liveSyncPosition=t}}]),e}(Ft),ye=ve,me=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),be=function(t){function e(r){O(this,e);var i=C(this,t.call(this,r,It.a.MANIFEST_LOADED,It.a.LEVEL_LOADED,It.a.FRAG_LOADED,It.a.ERROR));return i._manualLevel=-1,i.timer=null,i}return P(e,t),e.prototype.destroy=function(){this.cleanTimer(),this._manualLevel=-1},e.prototype.cleanTimer=function(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)},e.prototype.startLoad=function(){var t=this._levels;this.canload=!0,this.levelRetryCount=0,t&&t.forEach(function(t){t.loadError=0;var e=t.details;e&&e.live&&(t.details=void 0)}),this.timer&&this.tick()},e.prototype.stopLoad=function(){this.canload=!1},e.prototype.onManifestLoaded=function(t){var e=[],r=void 0,i={},a=null,n=!1,s=!1,l=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),u=[];if(t.levels.forEach(function(t){t.loadError=0,t.fragmentError=!1,n=n||!!t.videoCodec,s=s||!!t.audioCodec||!(!t.attrs||!t.attrs.AUDIO),!0===l&&t.audioCodec&&-1!==t.audioCodec.indexOf("mp4a.40.34")&&(t.audioCodec=void 0),a=i[t.bitrate],void 0===a?(t.url=[t.url],t.urlId=0,i[t.bitrate]=t,e.push(t)):a.url.push(t.url)}),!0===n&&!0===s&&(e=e.filter(function(t){return!!t.videoCodec})),e=e.filter(function(t){var e=t.audioCodec,r=t.videoCodec;return(!e||o(e))&&(!r||o(r))}),t.audioTracks&&(u=t.audioTracks.filter(function(t){return!t.audioCodec||o(t.audioCodec,"audio")})),e.length){r=e[0].bitrate,e.sort(function(t,e){return t.bitrate-e.bitrate}),this._levels=e;for(var d=0;d<e.length;d++)if(e[d].bitrate===r){this._firstLevel=d,Ct.b.log("manifest loaded,"+e.length+" level(s) found, first bitrate:"+r);break}this.hls.trigger(It.a.MANIFEST_PARSED,{levels:e,audioTracks:u,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:n,altAudio:u.length>0})}else this.hls.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:this.hls.url,reason:"no level with compatible codecs found in manifest"})},e.prototype.setLevelInternal=function(t){var e=this._levels,r=this.hls;if(t>=0&&t<e.length){if(this.cleanTimer(),this._level!==t){Ct.b.log("switching to level "+t),this._level=t;var i=e[t];i.level=t,r.trigger(It.a.LEVEL_SWITCH,i),r.trigger(It.a.LEVEL_SWITCHING,i)}var a=e[t],n=a.details;if(!n||!0===n.live){var o=a.urlId;r.trigger(It.a.LEVEL_LOADING,{url:a.url[o],level:t,id:o})}}else r.trigger(It.a.ERROR,{type:Ot.b.OTHER_ERROR,details:Ot.a.LEVEL_SWITCH_ERROR,level:t,fatal:!1,reason:"invalid level idx"})},e.prototype.onError=function(t){var e=this;if(!0===t.fatal)return void(t.type===Ot.b.NETWORK_ERROR&&this.cleanTimer());var r=t.details,i=!1,a=!1,n=void 0,o=void 0,s=this.hls.config;switch(r){case Ot.a.FRAG_LOAD_ERROR:case Ot.a.FRAG_LOAD_TIMEOUT:case Ot.a.FRAG_LOOP_LOADING_ERROR:case Ot.a.KEY_LOAD_ERROR:case Ot.a.KEY_LOAD_TIMEOUT:n=t.frag.level,a=!0;break;case Ot.a.LEVEL_LOAD_ERROR:case Ot.a.LEVEL_LOAD_TIMEOUT:n=t.context.level,i=!0;break;case Ot.a.REMUX_ALLOC_ERROR:n=t.level}if(void 0!==n)if(o=this._levels[n],o.loadError++,o.fragmentError=a,!0===a){var l=o.url.length;l>1&&o.loadError<l?(o.urlId=(o.urlId+1)%l,o.details=void 0,Ct.b.warn("level controller,"+r+" for level "+n+": switching to redundant stream id "+o.urlId)):-1===this._manualLevel&&0!==n?(Ct.b.warn("level controller,"+r+": switch-down for next fragment"),this.hls.nextAutoLevel=n-1):(Ct.b.warn("level controller, "+r+": reload a fragment"),this._level=void 0)}else if(!0===i)if(this.levelRetryCount+1<=s.levelLoadingMaxRetry){var u=Math.min(Math.pow(2,this.levelRetryCount)*s.levelLoadingRetryDelay,s.levelLoadingMaxRetryTimeout);this.timer=setTimeout(function(){return e.tick()},u),t.levelRetry=!0,this.levelRetryCount++,Ct.b.warn("level controller,"+r+", retry in "+u+" ms, current retry count is "+this.levelRetryCount)}else Ct.b.error("cannot recover "+r+" error"),this._level=void 0,this.cleanTimer(),t.fatal=!0},e.prototype.onFragLoaded=function(t){var e=t.frag;if(void 0!==e&&"main"===e.type){var r=this._levels[e.level];void 0!==r&&(r.fragmentError=!1,r.loadError=0,this.levelRetryCount=0)}},e.prototype.onLevelLoaded=function(t){var e=this,r=t.level;if(r===this._level){var i=this._levels[r];!1===i.fragmentError&&(i.loadError=0,this.levelRetryCount=0);var a=t.details;if(a.live){var n=1e3*(a.averagetargetduration?a.averagetargetduration:a.targetduration),o=i.details;o&&a.endSN===o.endSN&&(n/=2,Ct.b.log("same live playlist, reload twice faster")),n-=performance.now()-t.stats.trequest,n=Math.max(1e3,Math.round(n)),Ct.b.log("live playlist, reload in "+n+" ms"),this.timer=setTimeout(function(){return e.tick()},n)}else this.cleanTimer()}},e.prototype.tick=function(){var t=this._level;if(void 0!==t&&this.canload){var e=this._levels[t];if(e&&e.url){var r=e.urlId;this.hls.trigger(It.a.LEVEL_LOADING,{url:e.url[r],level:t,id:r})}}},me(e,[{key:"levels",get:function(){return this._levels}},{key:"level",get:function(){return this._level},set:function(t){var e=this._levels;e&&(t=Math.min(t,e.length-1),this._level===t&&void 0!==e[t].details||this.setLevelInternal(t))}},{key:"manualLevel",get:function(){return this._manualLevel},set:function(t){this._manualLevel=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this._manualLevel?this._manualLevel:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this._manualLevel&&(this.hls.nextAutoLevel=t)}}]),e}(Ft),Ee=be,Te=r(3),Re=function(t){function e(r){x(this,e);var i=F(this,t.call(this,r,It.a.MEDIA_ATTACHED,It.a.MEDIA_DETACHING,It.a.FRAG_PARSING_METADATA));return i.id3Track=void 0,i.media=void 0,i}return N(e,t),e.prototype.destroy=function(){Ft.prototype.destroy.call(this)},e.prototype.onMediaAttached=function(t){this.media=t.media,this.media},e.prototype.onMediaDetaching=function(){this.media=void 0},e.prototype.onFragParsingMetadata=function(t){var e=t.frag,r=t.samples;this.id3Track||(this.id3Track=this.media.addTextTrack("metadata","id3"),this.id3Track.mode="hidden");for(var i=window.WebKitDataCue||window.VTTCue||window.TextTrackCue,a=0;a<r.length;a++){var n=Te.a.getID3Frames(r[a].data);if(n){var o=r[a].pts,s=a<r.length-1?r[a+1].pts:e.endPTS;o===s&&(s+=1e-4);for(var l=0;l<n.length;l++){var u=n[l];if(!Te.a.isTimeStampFrame(u)){var d=new i(o,s,"");d.value=u,this.id3Track.addCue(d)}}}}},e}(Ft),Ae=Re,Se=function(){function t(e){M(this,t),this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=0,this.totalWeight_=0}return t.prototype.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},t.prototype.getTotalWeight=function(){return this.totalWeight_},t.prototype.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);return this.estimate_/t}return this.estimate_},t}(),_e=Se,Le=function(){function t(e,r,i,a){U(this,t),this.hls=e,this.defaultEstimate_=a,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new _e(r),this.fast_=new _e(i)}return t.prototype.sample=function(t,e){t=Math.max(t,this.minDelayMs_);var r=8e3*e/t,i=t/1e3;this.fast_.sample(i,r),this.slow_.sample(i,r)},t.prototype.canEstimate=function(){var t=this.fast_;return t&&t.getTotalWeight()>=this.minWeight_},t.prototype.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.prototype.destroy=function(){},t}(),we=Le,De=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),ke=function(t){function e(r){B(this,e);var i=G(this,t.call(this,r,It.a.FRAG_LOADING,It.a.FRAG_LOADED,It.a.FRAG_BUFFERED,It.a.ERROR));return i.lastLoadedFragLevel=0,i._nextAutoLevel=-1,i.hls=r,i.timer=null,i._bwEstimator=null,i.onCheck=i._abandonRulesCheck.bind(i),i}return H(e,t),e.prototype.destroy=function(){this.clearTimer(),Ft.prototype.destroy.call(this)},e.prototype.onFragLoading=function(t){var e=t.frag;if("main"===e.type){if(this.timer||(this.timer=setInterval(this.onCheck,100)),!this._bwEstimator){var r=this.hls,i=t.frag.level,a=r.levels[i].details.live,n=r.config,o=void 0,s=void 0;a?(o=n.abrEwmaFastLive,s=n.abrEwmaSlowLive):(o=n.abrEwmaFastVoD,s=n.abrEwmaSlowVoD),this._bwEstimator=new we(r,s,o,n.abrEwmaDefaultEstimate)}this.fragCurrent=e}},e.prototype._abandonRulesCheck=function(){var t=this.hls,e=t.media,r=this.fragCurrent,i=r.loader,a=t.minAutoLevel;if(!i||i.stats&&i.stats.aborted)return Ct.b.warn("frag loader destroy or aborted, disarm abandonRules"),void this.clearTimer();var n=i.stats;if(e&&n&&(!e.paused&&0!==e.playbackRate||!e.readyState)&&r.autoLevel&&r.level){var o=performance.now()-n.trequest,s=Math.abs(e.playbackRate);if(o>500*r.duration/s){var l=t.levels,u=Math.max(1,n.bw?n.bw/8:1e3*n.loaded/o),d=l[r.level],h=d.realBitrate?Math.max(d.realBitrate,d.bitrate):d.bitrate,c=n.total?n.total:Math.max(n.loaded,Math.round(r.duration*h/8)),f=e.currentTime,p=(c-n.loaded)/u,g=(ie.bufferInfo(e,f,t.config.maxBufferHole).end-f)/s;if(g<2*r.duration/s&&p>g){var v=void 0,y=void 0;for(y=r.level-1;y>a;y--){var m=l[y].realBitrate?Math.max(l[y].realBitrate,l[y].bitrate):l[y].bitrate;if((v=r.duration*m/(6.4*u))<g)break}v<p&&(Ct.b.warn("loading too slow, abort fragment loading and switch to level "+y+":fragLoadedDelay["+y+"]<fragLoadedDelay["+(r.level-1)+"];bufferStarvationDelay:"+v.toFixed(1)+"<"+p.toFixed(1)+":"+g.toFixed(1)),t.nextLoadLevel=y,this._bwEstimator.sample(o,n.loaded),i.abort(),this.clearTimer(),t.trigger(It.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,stats:n}))}}}},e.prototype.onFragLoaded=function(t){var e=t.frag;if("main"===e.type&&!isNaN(e.sn)){if(this.clearTimer(),this.lastLoadedFragLevel=e.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var r=this.hls.levels[e.level],i=(r.loaded?r.loaded.bytes:0)+t.stats.loaded,a=(r.loaded?r.loaded.duration:0)+t.frag.duration;r.loaded={bytes:i,duration:a},r.realBitrate=Math.round(8*i/a)}if(t.frag.bitrateTest){var n=t.stats;n.tparsed=n.tbuffered=n.tload,this.onFragBuffered(t)}}},e.prototype.onFragBuffered=function(t){var e=t.stats,r=t.frag;if(!(!0===e.aborted||1!==r.loadCounter||"main"!==r.type||isNaN(r.sn)||r.bitrateTest&&e.tload!==e.tbuffered)){var i=e.tparsed-e.trequest;Ct.b.log("latency/loading/parsing/append/kbps:"+Math.round(e.tfirst-e.trequest)+"/"+Math.round(e.tload-e.tfirst)+"/"+Math.round(e.tparsed-e.tload)+"/"+Math.round(e.tbuffered-e.tparsed)+"/"+Math.round(8*e.loaded/(e.tbuffered-e.trequest))),this._bwEstimator.sample(i,e.loaded),e.bwEstimate=this._bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}},e.prototype.onError=function(t){switch(t.details){case Ot.a.FRAG_LOAD_ERROR:case Ot.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},e.prototype.clearTimer=function(){clearInterval(this.timer),this.timer=null},e.prototype._findBestLevel=function(t,e,r,i,a,n,o,s,l){for(var u=a;u>=i;u--){var d=l[u],h=d.details,c=h?h.totalduration/h.fragments.length:e,f=!!h&&h.live,p=void 0;p=u<=t?o*r:s*r;var g=l[u].realBitrate?Math.max(l[u].realBitrate,l[u].bitrate):l[u].bitrate,v=g*c/p;if(Ct.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+u+"/"+Math.round(p)+"/"+g+"/"+c+"/"+n+"/"+v),p>g&&(!v||f&&!this.bitrateTestDelay||v<n))return u}return-1},De(e,[{key:"nextAutoLevel",get:function(){var t=this._nextAutoLevel,e=this._bwEstimator;if(!(-1===t||e&&e.canEstimate()))return t;var r=this._nextABRAutoLevel;return-1!==t&&(r=Math.min(t,r)),r},set:function(t){this._nextAutoLevel=t}},{key:"_nextABRAutoLevel",get:function(){var t=this.hls,e=t.maxAutoLevel,r=t.levels,i=t.config,a=t.minAutoLevel,n=t.media,o=this.lastLoadedFragLevel,s=this.fragCurrent?this.fragCurrent.duration:0,l=n?n.currentTime:0,u=n&&0!==n.playbackRate?Math.abs(n.playbackRate):1,d=this._bwEstimator?this._bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,h=(ie.bufferInfo(n,l,i.maxBufferHole).end-l)/u,c=this._findBestLevel(o,s,d,a,e,h,i.abrBandWidthFactor,i.abrBandWidthUpFactor,r);if(c>=0)return c;Ct.b.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var f=s?Math.min(s,i.maxStarvationDelay):i.maxStarvationDelay,p=i.abrBandWidthFactor,g=i.abrBandWidthUpFactor;if(0===h){var v=this.bitrateTestDelay;if(v){f=(s?Math.min(s,i.maxLoadingDelay):i.maxLoadingDelay)-v,Ct.b.trace("bitrate test took "+Math.round(1e3*v)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*f)+" ms"),p=g=1}}return c=this._findBestLevel(o,s,d,a,e,h+f,p,g,r),Math.max(c,0)}}]),e}(Ft),Ie=ke,Oe=y(),Ce=function(t){function e(r){j(this,e);var i=K(this,t.call(this,r,It.a.MEDIA_ATTACHING,It.a.MEDIA_DETACHING,It.a.MANIFEST_PARSED,It.a.BUFFER_RESET,It.a.BUFFER_APPENDING,It.a.BUFFER_CODECS,It.a.BUFFER_EOS,It.a.BUFFER_FLUSHING,It.a.LEVEL_PTS_UPDATED,It.a.LEVEL_UPDATED));return i._msDuration=null,i._levelDuration=null,i.onsbue=i.onSBUpdateEnd.bind(i),i.onsbe=i.onSBUpdateError.bind(i),i.pendingTracks={},i.tracks={},i}return W(e,t),e.prototype.destroy=function(){Ft.prototype.destroy.call(this)},e.prototype.onLevelPtsUpdated=function(t){var e=t.type,r=this.tracks.audio;if("audio"===e&&r&&"audio/mpeg"===r.container){var i=this.sourceBuffer.audio;if(Math.abs(i.timestampOffset-t.start)>.1){var a=i.updating;try{i.abort()}catch(t){a=!0,Ct.b.warn("can not abort audio buffer: "+t)}a?this.audioTimestampOffset=t.start:(Ct.b.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+t.start),i.timestampOffset=t.start)}}},e.prototype.onManifestParsed=function(t){var e=t.audio,r=t.video||t.levels.length&&t.audio,i=0;t.altAudio&&(e||r)&&(i=(e?1:0)+(r?1:0),Ct.b.log(i+" sourceBuffer(s) expected")),this.sourceBufferNb=i},e.prototype.onMediaAttaching=function(t){var e=this.media=t.media;if(e){var r=this.mediaSource=new Oe;this.onmso=this.onMediaSourceOpen.bind(this),this.onmse=this.onMediaSourceEnded.bind(this),this.onmsc=this.onMediaSourceClose.bind(this),r.addEventListener("sourceopen",this.onmso),r.addEventListener("sourceended",this.onmse),r.addEventListener("sourceclose",this.onmsc),e.src=URL.createObjectURL(r)}},e.prototype.onMediaDetaching=function(){Ct.b.log("media source detaching");var t=this.mediaSource;if(t){if("open"===t.readyState)try{t.endOfStream()}catch(t){Ct.b.warn("onMediaDetaching:"+t.message+" while calling endOfStream")}t.removeEventListener("sourceopen",this.onmso),t.removeEventListener("sourceended",this.onmse),t.removeEventListener("sourceclose",this.onmsc),this.media&&(URL.revokeObjectURL(this.media.src),this.media.removeAttribute("src"),this.media.load()),this.mediaSource=null,this.media=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(It.a.MEDIA_DETACHED)},e.prototype.onMediaSourceOpen=function(){Ct.b.log("media source opened"),this.hls.trigger(It.a.MEDIA_ATTACHED,{media:this.media});var t=this.mediaSource;t&&t.removeEventListener("sourceopen",this.onmso),this.checkPendingTracks()},e.prototype.checkPendingTracks=function(){var t=this.pendingTracks,e=Object.keys(t).length;e&&(this.sourceBufferNb<=e||0===this.sourceBufferNb)&&(this.createSourceBuffers(t),this.pendingTracks={},this.doAppending())},e.prototype.onMediaSourceClose=function(){Ct.b.log("media source closed")},e.prototype.onMediaSourceEnded=function(){Ct.b.log("media source ended")},e.prototype.onSBUpdateEnd=function(){if(this.audioTimestampOffset){var t=this.sourceBuffer.audio;Ct.b.warn("change mpeg audio timestamp offset from "+t.timestampOffset+" to "+this.audioTimestampOffset),t.timestampOffset=this.audioTimestampOffset,delete this.audioTimestampOffset}this._needsFlush&&this.doFlush(),this._needsEos&&this.checkEos(),this.appending=!1;var e=this.parent,r=this.segments.reduce(function(t,r){return r.parent===e?t+1:t},0);this.hls.trigger(It.a.BUFFER_APPENDED,{parent:e,pending:r}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()},e.prototype.onSBUpdateError=function(t){Ct.b.error("sourceBuffer error:",t),this.hls.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.BUFFER_APPENDING_ERROR,fatal:!1})},e.prototype.onBufferReset=function(){var t=this.sourceBuffer;for(var e in t){var r=t[e];try{this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this.onsbue),r.removeEventListener("error",this.onsbe)}catch(t){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0},e.prototype.onBufferCodecs=function(t){if(0===Object.keys(this.sourceBuffer).length){for(var e in t)this.pendingTracks[e]=t[e];var r=this.mediaSource;r&&"open"===r.readyState&&this.checkPendingTracks()}},e.prototype.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;for(var i in t)if(!e[i]){var a=t[i],n=a.levelCodec||a.codec,o=a.container+";codecs="+n;Ct.b.log("creating sourceBuffer("+o+")");try{var s=e[i]=r.addSourceBuffer(o);s.addEventListener("updateend",this.onsbue),s.addEventListener("error",this.onsbe),this.tracks[i]={codec:n,container:a.container},a.buffer=s}catch(t){Ct.b.error("error while trying to add sourceBuffer:"+t.message),this.hls.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:t,mimeType:o})}}this.hls.trigger(It.a.BUFFER_CREATED,{tracks:t})},e.prototype.onBufferAppending=function(t){this._needsFlush||(this.segments?this.segments.push(t):this.segments=[t],this.doAppending())},e.prototype.onBufferAppendFail=function(t){Ct.b.error("sourceBuffer error:",t.event),this.hls.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.BUFFER_APPENDING_ERROR,fatal:!1})},e.prototype.onBufferEos=function(t){var e=this.sourceBuffer,r=t.type;for(var i in e)r&&i!==r||e[i].ended||(e[i].ended=!0,Ct.b.log(i+" sourceBuffer now EOS"));this.checkEos()},e.prototype.checkEos=function(){var t=this.sourceBuffer,e=this.mediaSource;if(!e||"open"!==e.readyState)return void(this._needsEos=!1);for(var r in t){var i=t[r];if(!i.ended)return;if(i.updating)return void(this._needsEos=!0)}Ct.b.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{e.endOfStream()}catch(t){Ct.b.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1},e.prototype.onBufferFlushing=function(t){this.flushRange.push({start:t.startOffset,end:t.endOffset,type:t.type}),this.flushBufferCounter=0,this.doFlush()},e.prototype.onLevelUpdated=function(t){var e=t.details;0!==e.fragments.length&&(this._levelDuration=e.totalduration+e.fragments[0].start,this.updateMediaElementDuration())},e.prototype.updateMediaElementDuration=function(){var t=this.media,e=this.mediaSource,r=this.sourceBuffer,i=this._levelDuration;if(null!==i&&t&&e&&r&&0!==t.readyState&&"open"===e.readyState){for(var a in r)if(r[a].updating)return;null===this._msDuration&&(this._msDuration=e.duration);var n=t.duration;(i>this._msDuration&&i>n||n===1/0||isNaN(n))&&(Ct.b.log("Updating mediasource duration to "+i.toFixed(3)),this._msDuration=e.duration=i)}},e.prototype.doFlush=function(){for(;this.flushRange.length;){var t=this.flushRange[0];if(!this.flushBuffer(t.start,t.end,t.type))return void(this._needsFlush=!0);this.flushRange.shift(),this.flushBufferCounter=0}if(0===this.flushRange.length){this._needsFlush=!1;var e=0,r=this.sourceBuffer;try{for(var i in r)e+=r[i].buffered.length}catch(t){Ct.b.error("error while accessing sourceBuffer.buffered")}this.appended=e,this.hls.trigger(It.a.BUFFER_FLUSHED)}},e.prototype.doAppending=function(){var t=this.hls,e=this.sourceBuffer,r=this.segments;if(Object.keys(e).length){if(this.media.error)return this.segments=[],void Ct.b.error("trying to append although a media error occured, flush segment and abort");if(this.appending)return;if(r&&r.length){var i=r.shift();try{var a=i.type,n=e[a];n?n.updating?r.unshift(i):(n.ended=!1,this.parent=i.parent,n.appendBuffer(i.data),this.appendError=0,this.appended++,this.appending=!0):this.onSBUpdateEnd()}catch(e){Ct.b.error("error while trying to append buffer:"+e.message),r.unshift(i);var o={type:Ot.b.MEDIA_ERROR,parent:i.parent};if(22===e.code)return this.segments=[],o.details=Ot.a.BUFFER_FULL_ERROR,o.fatal=!1,void t.trigger(It.a.ERROR,o);if(this.appendError?this.appendError++:this.appendError=1,o.details=Ot.a.BUFFER_APPEND_ERROR,this.appendError>t.config.appendErrorMaxRetry)return Ct.b.log("fail "+t.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],o.fatal=!0,void t.trigger(It.a.ERROR,o);o.fatal=!1,t.trigger(It.a.ERROR,o)}}}},e.prototype.flushBuffer=function(t,e,r){var i,a,n,o,s,l,u=this.sourceBuffer;if(Object.keys(u).length){if(Ct.b.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+t+"/"+e),this.flushBufferCounter<this.appended){for(var d in u)if(!r||d===r){if(i=u[d],i.ended=!1,i.updating)return Ct.b.warn("cannot flush, sb updating in progress"),!1;try{for(a=0;a<i.buffered.length;a++)if(n=i.buffered.start(a),o=i.buffered.end(a),-1!==navigator.userAgent.toLowerCase().indexOf("firefox")&&e===Number.POSITIVE_INFINITY?(s=t,l=e):(s=Math.max(n,t),l=Math.min(o,e)),Math.min(l,o)-s>.5)return this.flushBufferCounter++,Ct.b.log("flush "+d+" ["+s+","+l+"], of ["+n+","+o+"], pos:"+this.media.currentTime),i.remove(s,l),!1}catch(t){Ct.b.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else Ct.b.warn("abort flushing too many retries");Ct.b.log("buffer flushed")}return!0},e}(Ft),Pe=Ce,xe=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),Fe=function(t){function e(r){return V(this,e),Y(this,t.call(this,r,It.a.FPS_DROP_LEVEL_CAPPING,It.a.MEDIA_ATTACHING,It.a.MANIFEST_PARSED))}return z(e,t),e.prototype.destroy=function(){this.hls.config.capLevelToPlayerSize&&(this.media=this.restrictedLevels=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer)))},e.prototype.onFpsDropLevelCapping=function(t){e.isLevelAllowed(t.droppedLevel,this.restrictedLevels)&&this.restrictedLevels.push(t.droppedLevel)},e.prototype.onMediaAttaching=function(t){this.media=t.media instanceof HTMLVideoElement?t.media:null},e.prototype.onManifestParsed=function(t){var e=this.hls;this.restrictedLevels=[],e.config.capLevelToPlayerSize&&(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.levels=t.levels,e.firstLevel=this.getMaxLevel(t.firstLevel),clearInterval(this.timer),this.timer=setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},e.prototype.detectPlayerSize=function(){if(this.media){var t=this.levels?this.levels.length:0;if(t){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t-1),e.autoLevelCapping>this.autoLevelCapping&&e.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},e.prototype.getMaxLevel=function(t){var r=this;if(!this.levels)return-1;var i=this.levels.filter(function(i,a){return e.isLevelAllowed(a,r.restrictedLevels)&&a<=t});return e.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)},e.isLevelAllowed=function(t){return-1===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).indexOf(t)},e.getMaxLevelByMediaSize=function(t,e,r){if(!t||t&&!t.length)return-1;for(var i=t.length-1,a=0;a<t.length;a+=1){var n=t[a];if((n.width>=e||n.height>=r)&&function(t,e){return!e||(t.width!==e.width||t.height!==e.height)}(n,t[a+1])){i=a;break}}return i},xe(e,[{key:"mediaWidth",get:function(){var t=void 0,r=this.media;return r&&(t=r.width||r.clientWidth||r.offsetWidth,t*=e.contentScaleFactor),t}},{key:"mediaHeight",get:function(){var t=void 0,r=this.media;return r&&(t=r.height||r.clientHeight||r.offsetHeight,t*=e.contentScaleFactor),t}}],[{key:"contentScaleFactor",get:function(){var t=1;try{t=window.devicePixelRatio}catch(t){}return t}}]),e}(Ft),Ne=Fe,Me=function(t){function e(r){return X(this,e),q(this,t.call(this,r,It.a.MEDIA_ATTACHING))}return Q(e,t),e.prototype.destroy=function(){this.timer&&clearInterval(this.timer),this.isVideoPlaybackQualityAvailable=!1},e.prototype.onMediaAttaching=function(t){var e=this.hls.config;if(e.capLevelOnFPSDrop){"function"==typeof(this.video=t.media instanceof HTMLVideoElement?t.media:null).getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),clearInterval(this.timer),this.timer=setInterval(this.checkFPSInterval.bind(this),e.fpsDroppedMonitoringPeriod)}},e.prototype.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var a=i-this.lastTime,n=r-this.lastDroppedFrames,o=e-this.lastDecodedFrames,s=1e3*n/a,l=this.hls;if(l.trigger(It.a.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:r}),s>0&&n>l.config.fpsDroppedMonitoringThreshold*o){var u=l.currentLevel;Ct.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(It.a.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,l.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.prototype.checkFPSInterval=function(){var t=this.video;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},e}(Ft),Ue=Me,Be=function(){function t(e){J(this,t),e&&e.xhrSetup&&(this.xhrSetup=e.xhrSetup)}return t.prototype.destroy=function(){this.abort(),this.loader=null},t.prototype.abort=function(){var t=this.loader;t&&4!==t.readyState&&(this.stats.aborted=!0,t.abort()),window.clearTimeout(this.requestTimeout),this.requestTimeout=null,window.clearTimeout(this.retryTimeout),this.retryTimeout=null},t.prototype.load=function(t,e,r){this.context=t,this.config=e,this.callbacks=r,this.stats={trequest:performance.now(),retry:0},this.retryDelay=e.retryDelay,this.loadInternal()},t.prototype.loadInternal=function(){var t,e=this.context;t=this.loader=new XMLHttpRequest;var r=this.stats;r.tfirst=0,r.loaded=0;var i=this.xhrSetup;try{if(i)try{i(t,e.url)}catch(r){t.open("GET",e.url,!0),i(t,e.url)}t.readyState||t.open("GET",e.url,!0)}catch(r){return void this.callbacks.onError({code:t.status,text:r.message},e,t)}e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),this.config.timeout),t.send()},t.prototype.readystatechange=function(t){var e=t.currentTarget,r=e.readyState,i=this.stats,a=this.context,n=this.config;if(!i.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(performance.now(),i.trequest)),4===r){var o=e.status;if(o>=200&&o<300){i.tload=Math.max(i.tfirst,performance.now());var s=void 0,l=void 0;"arraybuffer"===a.responseType?(s=e.response,l=s.byteLength):(s=e.responseText,l=s.length),i.loaded=i.total=l;var u={url:e.responseURL,data:s};this.callbacks.onSuccess(u,i,a,e)}else i.retry>=n.maxRetry||o>=400&&o<499?(Ct.b.error(o+" while loading "+a.url),this.callbacks.onError({code:o,text:e.statusText},a,e)):(Ct.b.warn(o+" while loading "+a.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,n.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),n.timeout)},t.prototype.loadtimeout=function(){Ct.b.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context,null)},t.prototype.loadprogress=function(t){var e=t.currentTarget,r=this.stats;r.loaded=t.loaded,t.lengthComputable&&(r.total=t.total);var i=this.callbacks.onProgress;i&&i(r,this.context,null,e)},t}(),Ge=Be,He=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),je=function(t){function e(r){$(this,e);var i=Z(this,t.call(this,r,It.a.MANIFEST_LOADING,It.a.MANIFEST_PARSED,It.a.AUDIO_TRACK_LOADED,It.a.ERROR));return i.ticks=0,i.ontick=i.tick.bind(i),i}return tt(e,t),e.prototype.destroy=function(){this.cleanTimer(),Ft.prototype.destroy.call(this)},e.prototype.cleanTimer=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},e.prototype.tick=function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},e.prototype.doTick=function(){this.updateTrack(this.trackId)},e.prototype.onError=function(t){t.fatal&&t.type===Ot.b.NETWORK_ERROR&&this.cleanTimer()},e.prototype.onManifestLoading=function(){this.tracks=[],this.trackId=-1},e.prototype.onManifestParsed=function(t){var e=this,r=t.audioTracks||[],i=!1;this.tracks=r,this.hls.trigger(It.a.AUDIO_TRACKS_UPDATED,{audioTracks:r});var a=0;r.forEach(function(t){if(t.default&&!i)return e.audioTrack=a,void(i=!0);a++}),!1===i&&r.length&&(Ct.b.log("no default audio track defined, use first audio track as default"),this.audioTrack=0)},e.prototype.onAudioTrackLoaded=function(t){t.id<this.tracks.length&&(Ct.b.log("audioTrack "+t.id+" loaded"),this.tracks[t.id].details=t.details,t.details.live&&!this.timer&&(this.timer=setInterval(this.ontick,1e3*t.details.targetduration)),!t.details.live&&this.timer&&this.cleanTimer())},e.prototype.setAudioTrackInternal=function(t){if(t>=0&&t<this.tracks.length){this.cleanTimer(),this.trackId=t,Ct.b.log("switching to audioTrack "+t);var e=this.tracks[t],r=this.hls,i=e.type,a=e.url,n={id:t,type:i,url:a};r.trigger(It.a.AUDIO_TRACK_SWITCH,n),r.trigger(It.a.AUDIO_TRACK_SWITCHING,n);var o=e.details;!a||void 0!==o&&!0!==o.live||(Ct.b.log("(re)loading playlist for audioTrack "+t),r.trigger(It.a.AUDIO_TRACK_LOADING,{url:a,id:t}))}},e.prototype.updateTrack=function(t){if(t>=0&&t<this.tracks.length){this.cleanTimer(),this.trackId=t,Ct.b.log("updating audioTrack "+t);var e=this.tracks[t],r=e.url,i=e.details;!r||void 0!==i&&!0!==i.live||(Ct.b.log("(re)loading playlist for audioTrack "+t),this.hls.trigger(It.a.AUDIO_TRACK_LOADING,{url:r,id:t}))}},He(e,[{key:"audioTracks",get:function(){return this.tracks}},{key:"audioTrack",get:function(){return this.trackId},set:function(t){this.trackId===t&&void 0!==this.tracks[t].details||this.setAudioTrackInternal(t)}}]),e}(Ft),Ke=je,We=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),Ve={STOPPED:"STOPPED",STARTING:"STARTING",IDLE:"IDLE",PAUSED:"PAUSED",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",BUFFER_FLUSHING:"BUFFER_FLUSHING",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS"},Ye=function(t){function e(r){et(this,e);var i=rt(this,t.call(this,r,It.a.MEDIA_ATTACHED,It.a.MEDIA_DETACHING,It.a.AUDIO_TRACKS_UPDATED,It.a.AUDIO_TRACK_SWITCHING,It.a.AUDIO_TRACK_LOADED,It.a.KEY_LOADED,It.a.FRAG_LOADED,It.a.FRAG_PARSING_INIT_SEGMENT,It.a.FRAG_PARSING_DATA,It.a.FRAG_PARSED,It.a.ERROR,It.a.BUFFER_CREATED,It.a.BUFFER_APPENDED,It.a.BUFFER_FLUSHED,It.a.INIT_PTS_FOUND));return i.config=r.config,i.audioCodecSwap=!1,i.ticks=0,i._state=Ve.STOPPED,i.ontick=i.tick.bind(i),i.initPTS=[],i.waitingFragment=null,i.videoTrackCC=null,i}return it(e,t),e.prototype.destroy=function(){this.stopLoad(),this.timer&&(clearInterval(this.timer),this.timer=null),Ft.prototype.destroy.call(this),this.state=Ve.STOPPED},e.prototype.onInitPtsFound=function(t){var e=t.id,r=t.frag.cc,i=t.initPTS;"main"===e&&(this.initPTS[r]=i,this.videoTrackCC=r,Ct.b.log("InitPTS for cc:"+r+" found from video track:"+i),this.state===Ve.WAITING_INIT_PTS&&this.tick())},e.prototype.startLoad=function(t){if(this.tracks){var e=this.lastCurrentTime;this.stopLoad(),this.timer||(this.timer=setInterval(this.ontick,100)),this.fragLoadError=0,e>0&&-1===t?(Ct.b.log("audio:override startPosition with lastCurrentTime @"+e.toFixed(3)),this.state=Ve.IDLE):(this.lastCurrentTime=this.startPosition?this.startPosition:t,this.state=Ve.STARTING),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=t,this.state=Ve.STOPPED},e.prototype.stopLoad=function(){var t=this.fragCurrent;t&&(t.loader&&t.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=Ve.STOPPED},e.prototype.tick=function(){1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(this.tick,1),this.ticks=0)},e.prototype.doTick=function(){var t,e,r,i=this.hls,a=i.config;switch(this.state){case Ve.ERROR:case Ve.PAUSED:case Ve.BUFFER_FLUSHING:break;case Ve.STARTING:this.state=Ve.WAITING_TRACK,this.loadedmetadata=!1;break;case Ve.IDLE:var n=this.tracks;if(!n)break;if(!this.media&&(this.startFragRequested||!a.startFragPrefetch))break;if(this.loadedmetadata)t=this.media.currentTime;else if(void 0===(t=this.nextLoadPosition))break;var o=this.mediaBuffer?this.mediaBuffer:this.media,s=this.videoBuffer?this.videoBuffer:this.media,l=ie.bufferInfo(o,t,a.maxBufferHole),u=ie.bufferInfo(s,t,a.maxBufferHole),d=l.len,h=l.end,c=this.fragPrevious,f=Math.max(a.maxBufferLength,u.len),p=this.audioSwitch,g=this.trackId;if((d<f||p)&&g<n.length){if(void 0===(r=n[g].details)){this.state=Ve.WAITING_TRACK;break}if(!p&&!r.live&&c&&c.sn===r.endSN&&(!this.media.seeking||this.media.duration-h<c.duration/2)){this.hls.trigger(It.a.BUFFER_EOS,{type:"audio"}),this.state=Ve.ENDED;break}var v=r.fragments,y=v.length,m=v[0].start,b=v[y-1].start+v[y-1].duration,E=void 0;if(p)if(r.live&&!r.PTSKnown)Ct.b.log("switching audiotrack, live stream, unknown PTS,load first fragment"),h=0;else if(h=t,r.PTSKnown&&t<m){if(!(l.end>m||l.nextStart))return;Ct.b.log("alt audio track ahead of main track, seek to start of alt audio track"),this.media.currentTime=m+.05}if(r.initSegment&&!r.initSegment.data)E=r.initSegment;else if(h<=m){if(E=v[0],null!==this.videoTrackCC&&E.cc!==this.videoTrackCC&&(E=A(v,this.videoTrackCC)),r.live&&E.loadIdx&&E.loadIdx===this.fragLoadIdx){var T=l.nextStart?l.nextStart:m;return Ct.b.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(T+.05)),void(this.media.currentTime=T+.05)}}else{var R=void 0,S=a.maxFragLookUpTolerance,_=c?v[c.sn-v[0].sn+1]:void 0,L=function(t){var e=Math.min(S,t.duration);return t.start+t.duration-e<=h?1:t.start-e>h&&t.start?-1:0};h<b?(h>b-S&&(S=0),R=_&&!L(_)?_:ee.search(v,L)):R=v[y-1],R&&(E=R,m=R.start,c&&E.level===c.level&&E.sn===c.sn&&(E.sn<r.endSN?(E=v[E.sn+1-r.startSN],Ct.b.log("SN just loaded, load next one: "+E.sn)):E=null))}if(E)if(E.decryptdata&&null!=E.decryptdata.uri&&null==E.decryptdata.key)Ct.b.log("Loading key for "+E.sn+" of ["+r.startSN+" ,"+r.endSN+"],track "+g),this.state=Ve.KEY_LOADING,i.trigger(It.a.KEY_LOADING,{frag:E});else{if(Ct.b.log("Loading "+E.sn+", cc: "+E.cc+" of ["+r.startSN+" ,"+r.endSN+"],track "+g+", currentTime:"+t+",bufferEnd:"+h.toFixed(3)),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,E.loadCounter){E.loadCounter++;var w=a.fragLoadingLoopThreshold;if(E.loadCounter>w&&Math.abs(this.fragLoadIdx-E.loadIdx)<w)return void i.trigger(It.a.ERROR,{type:Ot.b.MEDIA_ERROR,details:Ot.a.FRAG_LOOP_LOADING_ERROR,fatal:!1,frag:E})}else E.loadCounter=1;E.loadIdx=this.fragLoadIdx,this.fragCurrent=E,this.startFragRequested=!0,isNaN(E.sn)||(this.nextLoadPosition=E.start+E.duration),i.trigger(It.a.FRAG_LOADING,{frag:E}),this.state=Ve.FRAG_LOADING}}break;case Ve.WAITING_TRACK:e=this.tracks[this.trackId],e&&e.details&&(this.state=Ve.IDLE);break;case Ve.FRAG_LOADING_WAITING_RETRY:var D=performance.now(),k=this.retryDate;o=this.media;var I=o&&o.seeking;(!k||D>=k||I)&&(Ct.b.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=Ve.IDLE);break;case Ve.WAITING_INIT_PTS:var O=this.videoTrackCC;if(void 0===this.initPTS[O])break;var C=this.waitingFragment;if(C){var P=C.frag.cc;O!==P?(e=this.tracks[this.trackId],e.details&&e.details.live&&(Ct.b.warn("Waiting fragment CC ("+P+") does not match video track CC ("+O+")"),this.waitingFragment=null,this.state=Ve.IDLE)):(this.state=Ve.FRAG_LOADING,this.onFragLoaded(this.waitingFragment),this.waitingFragment=null)}else this.state=Ve.IDLE;break;case Ve.STOPPED:case Ve.FRAG_LOADING:case Ve.PARSING:case Ve.PARSED:case Ve.ENDED:}},e.prototype.onMediaAttached=function(t){var e=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),e.addEventListener("seeking",this.onvseeking),e.addEventListener("ended",this.onvended);var r=this.config;this.tracks&&r.autoStartLoad&&this.startLoad(r.startPosition)},e.prototype.onMediaDetaching=function(){var t=this.media;t&&t.ended&&(Ct.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var e=this.tracks;e&&e.forEach(function(t){t.details&&t.details.fragments.forEach(function(t){t.loadCounter=void 0})}),t&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1,this.stopLoad()},e.prototype.onMediaSeeking=function(){this.state===Ve.ENDED&&(this.state=Ve.IDLE),this.media&&(this.lastCurrentTime=this.media.currentTime),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.tick()},e.prototype.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},e.prototype.onAudioTracksUpdated=function(t){Ct.b.log("audio tracks updated"),this.tracks=t.audioTracks},e.prototype.onAudioTrackSwitching=function(t){var e=!!t.url;this.trackId=t.id,this.fragCurrent=null,this.state=Ve.PAUSED,this.waitingFragment=null,e?this.timer||(this.timer=setInterval(this.ontick,100)):this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),e&&(this.audioSwitch=!0,this.state=Ve.IDLE,void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold)),this.tick()},e.prototype.onAudioTrackLoaded=function(t){var e=t.details,r=t.id,i=this.tracks[r],a=e.totalduration,n=0;if(Ct.b.log("track "+r+" loaded ["+e.startSN+","+e.endSN+"],duration:"+a),e.live){var o=i.details;o&&e.fragments.length>0?(T(o,e),n=e.fragments[0].start,e.PTSKnown?Ct.b.log("live audio playlist sliding:"+n.toFixed(3)):Ct.b.log("live audio playlist - outdated PTS, unknown sliding")):(e.PTSKnown=!1,Ct.b.log("live audio playlist - first load, unknown sliding"))}else e.PTSKnown=!1;if(i.details=e,!this.startFragRequested){if(-1===this.startPosition){var s=e.startTimeOffset;isNaN(s)?this.startPosition=0:(Ct.b.log("start time offset found in playlist, adjust startPosition to "+s),this.startPosition=s)}this.nextLoadPosition=this.startPosition}this.state===Ve.WAITING_TRACK&&(this.state=Ve.IDLE),this.tick()},e.prototype.onKeyLoaded=function(){this.state===Ve.KEY_LOADING&&(this.state=Ve.IDLE,this.tick())},e.prototype.onFragLoaded=function(t){var e=this.fragCurrent,r=t.frag;if(this.state===Ve.FRAG_LOADING&&e&&"audio"===r.type&&r.level===e.level&&r.sn===e.sn){var i=this.tracks[this.trackId],a=i.details,n=a.totalduration,o=e.level,s=e.sn,l=e.cc,u=this.config.defaultAudioCodec||i.audioCodec||"mp4a.40.2",d=this.stats=t.stats;if("initSegment"===s)this.state=Ve.IDLE,d.tparsed=d.tbuffered=performance.now(),a.initSegment.data=t.payload,this.hls.trigger(It.a.FRAG_BUFFERED,{stats:d,frag:e,id:"audio"}),this.tick();else{this.state=Ve.PARSING,this.appended=!1,this.demuxer||(this.demuxer=new he(this.hls,"audio"));var h=this.initPTS[l],c=a.initSegment?a.initSegment.data:[];if(a.initSegment||void 0!==h){this.pendingBuffering=!0,Ct.b.log("Demuxing "+s+" of ["+a.startSN+" ,"+a.endSN+"],track "+o);this.demuxer.push(t.payload,c,u,null,e,n,!1,h)}else Ct.b.log("unknown video PTS for continuity counter "+l+", waiting for video PTS before demuxing audio frag "+s+" of ["+a.startSN+" ,"+a.endSN+"],track "+o),this.waitingFragment=t,this.state=Ve.WAITING_INIT_PTS}}this.fragLoadError=0},e.prototype.onFragParsingInitSegment=function(t){var e=this.fragCurrent,r=t.frag;if(e&&"audio"===t.id&&r.sn===e.sn&&r.level===e.level&&this.state===Ve.PARSING){var i=t.tracks,a=void 0;if(i.video&&delete i.video,a=i.audio){a.levelCodec=a.codec,a.id=t.id,this.hls.trigger(It.a.BUFFER_CODECS,i),Ct.b.log("audio track:audio,container:"+a.container+",codecs[level/parsed]=["+a.levelCodec+"/"+a.codec+"]");var n=a.initSegment;if(n){var o={type:"audio",data:n,parent:"audio",content:"initSegment"};this.audioSwitch?this.pendingData=[o]:(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(It.a.BUFFER_APPENDING,o))}this.tick()}}},e.prototype.onFragParsingData=function(t){var e=this,r=this.fragCurrent,i=t.frag;if(r&&"audio"===t.id&&"audio"===t.type&&i.sn===r.sn&&i.level===r.level&&this.state===Ve.PARSING){var a=this.trackId,n=this.tracks[a],o=this.hls;isNaN(t.endPTS)&&(t.endPTS=t.startPTS+r.duration,t.endDTS=t.startDTS+r.duration),Ct.b.log("parsed "+t.type+",PTS:["+t.startPTS.toFixed(3)+","+t.endPTS.toFixed(3)+"],DTS:["+t.startDTS.toFixed(3)+"/"+t.endDTS.toFixed(3)+"],nb:"+t.nb),E(n.details,r,t.startPTS,t.endPTS);var s=this.audioSwitch,l=this.media,u=!1;if(s&&l)if(l.readyState){var d=l.currentTime;Ct.b.log("switching audio track : currentTime:"+d),d>=t.startPTS&&(Ct.b.log("switching audio track : flushing all audio"),this.state=Ve.BUFFER_FLUSHING,o.trigger(It.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),u=!0,this.audioSwitch=!1,o.trigger(It.a.AUDIO_TRACK_SWITCHED,{id:a}))}else this.audioSwitch=!1,o.trigger(It.a.AUDIO_TRACK_SWITCHED,{id:a});var h=this.pendingData;this.audioSwitch||([t.data1,t.data2].forEach(function(e){e&&e.length&&h.push({type:t.type,data:e,parent:"audio",content:"data"})}),!u&&h.length&&(h.forEach(function(t){e.state===Ve.PARSING&&(e.pendingBuffering=!0,e.hls.trigger(It.a.BUFFER_APPENDING,t))}),this.pendingData=[],this.appended=!0)),this.tick()}},e.prototype.onFragParsed=function(t){var e=this.fragCurrent,r=t.frag;e&&"audio"===t.id&&r.sn===e.sn&&r.level===e.level&&this.state===Ve.PARSING&&(this.stats.tparsed=performance.now(),this.state=Ve.PARSED,this._checkAppendedParsed())},e.prototype.onBufferCreated=function(t){var e=t.tracks.audio;e&&(this.mediaBuffer=e.buffer,this.loadedmetadata=!0),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer)},e.prototype.onBufferAppended=function(t){if("audio"===t.parent){var e=this.state;e!==Ve.PARSING&&e!==Ve.PARSED||(this.pendingBuffering=t.pending>0,this._checkAppendedParsed())}},e.prototype._checkAppendedParsed=function(){if(!(this.state!==Ve.PARSED||this.appended&&this.pendingBuffering)){var t=this.fragCurrent,e=this.stats,r=this.hls;if(t){this.fragPrevious=t,e.tbuffered=performance.now(),r.trigger(It.a.FRAG_BUFFERED,{stats:e,frag:t,id:"audio"});var i=this.mediaBuffer?this.mediaBuffer:this.media;Ct.b.log("audio buffered : "+fe.toString(i.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(It.a.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=Ve.IDLE}this.tick()}},e.prototype.onError=function(t){var e=t.frag;if(!e||"audio"===e.type)switch(t.details){case Ot.a.FRAG_LOAD_ERROR:case Ot.a.FRAG_LOAD_TIMEOUT:if(!t.fatal){var r=this.fragLoadError;r?r++:r=1;var i=this.config;if(r<=i.fragLoadingMaxRetry){this.fragLoadError=r,e.loadCounter=0;var a=Math.min(Math.pow(2,r-1)*i.fragLoadingRetryDelay,i.fragLoadingMaxRetryTimeout);Ct.b.warn("audioStreamController: frag loading failed, retry in "+a+" ms"),this.retryDate=performance.now()+a,this.state=Ve.FRAG_LOADING_WAITING_RETRY}else Ct.b.error("audioStreamController: "+t.details+" reaches max retry, redispatch as fatal ..."),t.fatal=!0,this.state=Ve.ERROR}break;case Ot.a.FRAG_LOOP_LOADING_ERROR:case Ot.a.AUDIO_TRACK_LOAD_ERROR:case Ot.a.AUDIO_TRACK_LOAD_TIMEOUT:case Ot.a.KEY_LOAD_ERROR:case Ot.a.KEY_LOAD_TIMEOUT:this.state!==Ve.ERROR&&(this.state=t.fatal?Ve.ERROR:Ve.IDLE,Ct.b.warn("audioStreamController: "+t.details+" while loading frag,switch to "+this.state+" state ..."));break;case Ot.a.BUFFER_FULL_ERROR:if("audio"===t.parent&&(this.state===Ve.PARSING||this.state===Ve.PARSED)){var n=this.mediaBuffer,o=this.media.currentTime;if(n&&ie.isBuffered(n,o)&&ie.isBuffered(n,o+.5)){var s=this.config;s.maxMaxBufferLength>=s.maxBufferLength&&(s.maxMaxBufferLength/=2,Ct.b.warn("audio:reduce max buffer length to "+s.maxMaxBufferLength+"s"),this.fragLoadIdx+=2*s.fragLoadingLoopThreshold),this.state=Ve.IDLE}else Ct.b.warn("buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=Ve.BUFFER_FLUSHING,this.hls.trigger(It.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}},e.prototype.onBufferFlushed=function(){var t=this,e=this.pendingData;e&&e.length?(Ct.b.log("appending pending audio data on Buffer Flushed"),e.forEach(function(e){t.hls.trigger(It.a.BUFFER_APPENDING,e)}),this.appended=!0,this.pendingData=[],this.state=Ve.PARSED):(this.state=Ve.IDLE,this.fragPrevious=null,this.tick())},We(e,[{key:"state",set:function(t){if(this.state!==t){var e=this.state;this._state=t,Ct.b.log("audio stream:"+e+"->"+t)}},get:function(){return this._state}}]),e}(Ft),ze=Ye,Xe=function(){function t(t){return"string"==typeof t&&(!!n[t.toLowerCase()]&&t.toLowerCase())}function e(t){return"string"==typeof t&&(!!o[t.toLowerCase()]&&t.toLowerCase())}function r(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)t[i]=r[i]}return t}function i(i,n,o){var s=this,l=function(){if("undefined"!=typeof navigator)return/MSIE\s8\.0/.test(navigator.userAgent)}(),u={};l?s=document.createElement("custom"):u.enumerable=!0,s.hasBeenReset=!1;var d="",h=!1,c=i,f=n,p=o,g=null,v="",y=!0,m="auto",b="start",E=50,T="middle",R=50,A="middle";if(Object.defineProperty(s,"id",r({},u,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(s,"pauseOnExit",r({},u,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(s,"startTime",r({},u,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"endTime",r({},u,{get:function(){return f},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");f=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"text",r({},u,{get:function(){return p},set:function(t){p=""+t,this.hasBeenReset=!0}})),Object.defineProperty(s,"region",r({},u,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"vertical",r({},u,{get:function(){return v},set:function(e){var r=t(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");v=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"snapToLines",r({},u,{get:function(){return y},set:function(t){y=!!t,this.hasBeenReset=!0}})),Object.defineProperty(s,"line",r({},u,{get:function(){return m},set:function(t){if("number"!=typeof t&&t!==a)throw new SyntaxError("An invalid number or illegal string was specified.");m=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"lineAlign",r({},u,{get:function(){return b},set:function(t){var r=e(t);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");b=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"position",r({},u,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"positionAlign",r({},u,{get:function(){return T},set:function(t){var r=e(t);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");T=r,this.hasBeenReset=!0}})),Object.defineProperty(s,"size",r({},u,{get:function(){return R},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");R=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"align",r({},u,{get:function(){return A},set:function(t){var r=e(t);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");A=r,this.hasBeenReset=!0}})),s.displayState=void 0,l)return s}if("undefined"!=typeof window&&window.VTTCue)return window.VTTCue;var a="auto",n={"":!0,lr:!0,rl:!0},o={start:!0,middle:!0,end:!0,left:!0,right:!0};return i.prototype.getCueAsHTML=function(){return window.WebVTT.convertCueToDOMTree(window,this.text)},i}(),qe=function(){return{decode:function(t){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}};ot.prototype={set:function(t,e){this.get(t)||""===e||(this.values[t]=e)},get:function(t,e,r){return r?this.has(t)?this.values[t]:e[r]:this.has(t)?this.values[t]:e},has:function(t){return t in this.values},alt:function(t,e,r){for(var i=0;i<r.length;++i)if(e===r[i]){this.set(t,e);break}},integer:function(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))},percent:function(t,e){return!!(e.match(/^([\d]{1,3})(\.[\d]*)?%$/)&&(e=parseFloat(e))>=0&&e<=100)&&(this.set(t,e),!0)}};var Qe=new Xe(0,0,0),Je="middle"===Qe.align?"middle":"center";at.prototype={parse:function(t){function e(){var t=r.buffer,e=0;for(t=ut(t);e<t.length&&"\r"!==t[e]&&"\n"!==t[e];)++e;var i=t.substr(0,e);return"\r"===t[e]&&++e,"\n"===t[e]&&++e,r.buffer=t.substr(e),i}var r=this;t&&(r.buffer+=r.decoder.decode(t,{stream:!0}));try{var i;if("INITIAL"===r.state){if(!/\r\n|\n/.test(r.buffer))return this;i=e();var a=i.match(/^()?WEBVTT([ \t].*)?$/);if(!a||!a[0])throw new Error("Malformed WebVTT signature.");r.state="HEADER"}for(var n=!1;r.buffer;){if(!/\r\n|\n/.test(r.buffer))return this;switch(n?n=!1:i=e(),r.state){case"HEADER":/:/.test(i)?function(t){st(t,function(t,e){switch(t){case"Region":console.log("parse region",e)}},/:/)}(i):i||(r.state="ID");continue;case"NOTE":i||(r.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){r.state="NOTE";break}if(!i)continue;if(r.cue=new Xe(0,0,""),r.state="CUE",-1===i.indexOf("--\x3e")){r.cue.id=i;continue}case"CUE":try{lt(i,r.cue,r.regionList)}catch(t){r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":var o=-1!==i.indexOf("--\x3e");if(!i||o&&(n=!0)){r.oncue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}r.cue.text&&(r.cue.text+="\n"),r.cue.text+=i;continue;case"BADCUE":i||(r.state="ID");continue}}}catch(t){"CUETEXT"===r.state&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state="INITIAL"===r.state?"BADWEBVTT":"BADCUE"}return this},flush:function(){var t=this;try{if(t.buffer+=t.decoder.decode(),(t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state)throw new Error("Malformed WebVTT signature.")}catch(t){throw t}return t.onflush&&t.onflush(),this}};var $e=at,Ze={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},tr=function(t){var e=t;return Ze.hasOwnProperty(t)&&(e=Ze[t]),String.fromCharCode(e)},er=15,rr=100,ir={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ar={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nr={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},or={25:2,26:4,29:6,30:8,31:10,27:13,28:15},sr=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],lr={verboseFilter:{DATA:3,DEBUG:3,INFO:2,WARNING:2,TEXT:1,ERROR:0},time:null,verboseLevel:0,setTime:function(t){this.time=t},log:function(t,e){var r=this.verboseFilter[t];this.verboseLevel>=r&&console.log(this.time+" ["+t+"] "+e)}},ur=function(t){for(var e=[],r=0;r<t.length;r++)e.push(t[r].toString(16));return e},dr=function(){function t(e,r,i,a,n){ht(this,t),this.foreground=e||"white",this.underline=r||!1,this.italics=i||!1,this.background=a||"black",this.flash=n||!1}return t.prototype.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},t.prototype.setStyles=function(t){for(var e=["foreground","underline","italics","background","flash"],r=0;r<e.length;r++){var i=e[r];t.hasOwnProperty(i)&&(this[i]=t[i])}},t.prototype.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},t.prototype.equals=function(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash},t.prototype.copy=function(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash},t.prototype.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},t}(),hr=function(){function t(e,r,i,a,n,o){ht(this,t),this.uchar=e||" ",this.penState=new dr(r,i,a,n,o)}return t.prototype.reset=function(){this.uchar=" ",this.penState.reset()},t.prototype.setChar=function(t,e){this.uchar=t,this.penState.copy(e)},t.prototype.setPenState=function(t){this.penState.copy(t)},t.prototype.equals=function(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)},t.prototype.copy=function(t){this.uchar=t.uchar,this.penState.copy(t.penState)},t.prototype.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},t}(),cr=function(){function t(){ht(this,t),this.chars=[];for(var e=0;e<rr;e++)this.chars.push(new hr);this.pos=0,this.currPenState=new dr}return t.prototype.equals=function(t){for(var e=!0,r=0;r<rr;r++)if(!this.chars[r].equals(t.chars[r])){e=!1;break}return e},t.prototype.copy=function(t){for(var e=0;e<rr;e++)this.chars[e].copy(t.chars[e])},t.prototype.isEmpty=function(){for(var t=!0,e=0;e<rr;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t},t.prototype.setCursor=function(t){this.pos!==t&&(this.pos=t),this.pos<0?(lr.log("ERROR","Negative cursor position "+this.pos),this.pos=0):this.pos>rr&&(lr.log("ERROR","Too large cursor position "+this.pos),this.pos=rr)},t.prototype.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var r=this.pos+1;r<e+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(e)},t.prototype.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},t.prototype.insertChar=function(t){t>=144&&this.backSpace();var e=tr(t);if(this.pos>=rr)return void lr.log("ERROR","Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!");this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1)},t.prototype.clearFromPos=function(t){var e;for(e=t;e<rr;e++)this.chars[e].reset()},t.prototype.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},t.prototype.clearToEndOfRow=function(){this.clearFromPos(this.pos)},t.prototype.getTextString=function(){for(var t=[],e=!0,r=0;r<rr;r++){var i=this.chars[r].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")},t.prototype.setPenStyles=function(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)},t}(),fr=function(){function t(){ht(this,t),this.rows=[];for(var e=0;e<er;e++)this.rows.push(new cr);this.currRow=er-1,this.nrRollUpRows=null,this.reset()}return t.prototype.reset=function(){for(var t=0;t<er;t++)this.rows[t].clear();this.currRow=er-1},t.prototype.equals=function(t){for(var e=!0,r=0;r<er;r++)if(!this.rows[r].equals(t.rows[r])){e=!1;break}return e},t.prototype.copy=function(t){for(var e=0;e<er;e++)this.rows[e].copy(t.rows[e])},t.prototype.isEmpty=function(){for(var t=!0,e=0;e<er;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t},t.prototype.backSpace=function(){this.rows[this.currRow].backSpace()},t.prototype.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},t.prototype.insertChar=function(t){this.rows[this.currRow].insertChar(t)},t.prototype.setPen=function(t){this.rows[this.currRow].setPenStyles(t)},t.prototype.moveCursor=function(t){this.rows[this.currRow].moveCursor(t)},t.prototype.setCursor=function(t){lr.log("INFO","setCursor: "+t),this.rows[this.currRow].setCursor(t)},t.prototype.setPAC=function(t){lr.log("INFO","pacData = "+JSON.stringify(t));var e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(var r=0;r<er;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){var n=a.rows[i].cueStartTime;if(n&&n<lr.time)for(var o=0;o<this.nrRollUpRows;o++)this.rows[e-this.nrRollUpRows+o+1].copy(a.rows[i+o])}}this.currRow=e;var s=this.rows[this.currRow];if(null!==t.indent){var l=t.indent,u=Math.max(l-1,0);s.setCursor(t.indent),t.color=s.chars[u].penState.foreground}var d={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(d)},t.prototype.setBkgData=function(t){lr.log("INFO","bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)},t.prototype.setRollUpRows=function(t){this.nrRollUpRows=t},t.prototype.rollUp=function(){if(null===this.nrRollUpRows)return void lr.log("DEBUG","roll_up but nrRollUpRows not set yet");lr.log("TEXT",this.getDisplayText());var t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),lr.log("INFO","Rolling up")},t.prototype.getDisplayText=function(t){t=t||!1;for(var e=[],r="",i=-1,a=0;a<er;a++){var n=this.rows[a].getTextString();n&&(i=a+1,t?e.push("Row "+i+": '"+n+"'"):e.push(n.trim()))}return e.length>0&&(r=t?"["+e.join(" | ")+"]":e.join("\n")),r},t.prototype.getTextAndFormat=function(){return this.rows},t}(),pr=function(){function t(e,r){ht(this,t),this.chNr=e,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new fr,this.nonDisplayedMemory=new fr,this.lastOutputScreen=new fr,this.currRollUpRow=this.displayedMemory.rows[er-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}return t.prototype.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.currRollUpRow=this.displayedMemory.rows[er-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.lastCueEndTime=null},t.prototype.getHandler=function(){return this.outputFilter},t.prototype.setHandler=function(t){this.outputFilter=t},t.prototype.setPAC=function(t){this.writeScreen.setPAC(t)},t.prototype.setBkgData=function(t){this.writeScreen.setBkgData(t)},t.prototype.setMode=function(t){t!==this.mode&&(this.mode=t,lr.log("INFO","MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)},t.prototype.insertChars=function(t){for(var e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";lr.log("INFO",r+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(lr.log("TEXT","DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())},t.prototype.ccRCL=function(){lr.log("INFO","RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},t.prototype.ccBS=function(){lr.log("INFO","BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},t.prototype.ccAOF=function(){},t.prototype.ccAON=function(){},t.prototype.ccDER=function(){lr.log("INFO","DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},t.prototype.ccRU=function(t){lr.log("INFO","RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)},t.prototype.ccFON=function(){lr.log("INFO","FON - Flash On"),this.writeScreen.setPen({flash:!0})},t.prototype.ccRDC=function(){lr.log("INFO","RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},t.prototype.ccTR=function(){lr.log("INFO","TR"),this.setMode("MODE_TEXT")},t.prototype.ccRTD=function(){lr.log("INFO","RTD"),this.setMode("MODE_TEXT")},t.prototype.ccEDM=function(){lr.log("INFO","EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},t.prototype.ccCR=function(){lr.log("CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},t.prototype.ccENM=function(){lr.log("INFO","ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},t.prototype.ccEOC=function(){if(lr.log("INFO","EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,lr.log("TEXT","DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)},t.prototype.ccTO=function(t){lr.log("INFO","TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)},t.prototype.ccMIDROW=function(t){var e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{var r=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[r]}lr.log("INFO","MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)},t.prototype.outputDataUpdate=function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=lr.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue&&(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),!0===t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue()),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))},t.prototype.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}(),gr=function(){function t(e,r,i){ht(this,t),this.field=e||1,this.outputs=[r,i],this.channels=[new pr(1,r),new pr(2,i)],this.currChNr=-1,this.lastCmdA=null,this.lastCmdB=null,this.bufferedData=[],this.startTime=null,this.lastTime=null,this.dataCounters={padding:0,char:0,cmd:0,other:0}}return t.prototype.getHandler=function(t){return this.channels[t].getHandler()},t.prototype.setHandler=function(t,e){this.channels[t].setHandler(e)},t.prototype.addData=function(t,e){var r,i,a,n=!1;this.lastTime=t,lr.setTime(t);for(var o=0;o<e.length;o+=2)if(i=127&e[o],a=127&e[o+1],0!==i||0!==a){if(lr.log("DATA","["+ur([e[o],e[o+1]])+"] -> ("+ur([i,a])+")"),r=this.parseCmd(i,a),r||(r=this.parseMidrow(i,a)),r||(r=this.parsePAC(i,a)),r||(r=this.parseBackgroundAttributes(i,a)),!r&&(n=this.parseChars(i,a)))if(this.currChNr&&this.currChNr>=0){var s=this.channels[this.currChNr-1];s.insertChars(n)}else lr.log("WARNING","No channel found yet. TEXT-MODE?");r?this.dataCounters.cmd+=2:n?this.dataCounters.char+=2:(this.dataCounters.other+=2,lr.log("WARNING","Couldn't parse cleaned data "+ur([i,a])+" orig: "+ur([e[o],e[o+1]])))}else this.dataCounters.padding+=2},t.prototype.parseCmd=function(t,e){var r=null,i=(20===t||28===t)&&32<=e&&e<=47,a=(23===t||31===t)&&33<=e&&e<=35;if(!i&&!a)return!1;if(t===this.lastCmdA&&e===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,lr.log("DEBUG","Repeated command ("+ur([t,e])+") is dropped"),!0;r=20===t||23===t?1:2;var n=this.channels[r-1];return 20===t||28===t?32===e?n.ccRCL():33===e?n.ccBS():34===e?n.ccAOF():35===e?n.ccAON():36===e?n.ccDER():37===e?n.ccRU(2):38===e?n.ccRU(3):39===e?n.ccRU(4):40===e?n.ccFON():41===e?n.ccRDC():42===e?n.ccTR():43===e?n.ccRTD():44===e?n.ccEDM():45===e?n.ccCR():46===e?n.ccENM():47===e&&n.ccEOC():n.ccTO(e-32),this.lastCmdA=t,this.lastCmdB=e,this.currChNr=r,!0},t.prototype.parseMidrow=function(t,e){var r=null;if((17===t||25===t)&&32<=e&&e<=47){if((r=17===t?1:2)!==this.currChNr)return lr.log("ERROR","Mismatch channel in midrow parsing"),!1;return this.channels[r-1].ccMIDROW(e),lr.log("DEBUG","MIDROW ("+ur([t,e])+")"),!0}return!1},t.prototype.parsePAC=function(t,e){var r=null,i=null,a=(17<=t&&t<=23||25<=t&&t<=31)&&64<=e&&e<=127,n=(16===t||24===t)&&64<=e&&e<=95;if(!a&&!n)return!1;if(t===this.lastCmdA&&e===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,!0;r=t<=23?1:2,i=64<=e&&e<=95?1===r?ir[t]:nr[t]:1===r?ar[t]:or[t];var o=this.interpretPAC(i,e);return this.channels[r-1].setPAC(o),this.lastCmdA=t,this.lastCmdB=e,this.currChNr=r,!0},t.prototype.interpretPAC=function(t,e){var r=e,i={color:null,italics:!1,indent:null,underline:!1,row:t};return r=e>95?e-96:e-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},t.prototype.parseChars=function(t,e){var r=null,i=null,a=null;if(t>=25?(r=2,a=t-8):(r=1,a=t),17<=a&&a<=19){var n=e;n=17===a?e+80:18===a?e+112:e+144,lr.log("INFO","Special char '"+tr(n)+"' in channel "+r),i=[n]}else 32<=t&&t<=127&&(i=0===e?[t]:[t,e]);if(i){var o=ur(i);lr.log("DEBUG","Char codes = "+o.join(",")),this.lastCmdA=null,this.lastCmdB=null}return i},t.prototype.parseBackgroundAttributes=function(t,e){var r,i,a,n,o=(16===t||24===t)&&32<=e&&e<=47,s=(23===t||31===t)&&45<=e&&e<=47;return!(!o&&!s)&&(r={},16===t||24===t?(i=Math.floor((e-32)/2),r.background=sr[i],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0)),a=t<24?1:2,n=this.channels[a-1],n.setBkgData(r),this.lastCmdA=null,this.lastCmdB=null,!0)},t.prototype.reset=function(){for(var t=0;t<this.channels.length;t++)this.channels[t]&&this.channels[t].reset();this.lastCmdA=null,this.lastCmdB=null},t.prototype.cueSplitAtTime=function(t){for(var e=0;e<this.channels.length;e++)this.channels[e]&&this.channels[e].cueSplitAtTime(t)},t}(),vr=gr,yr=function(){function t(e,r){ct(this,t),this.timelineController=e,this.track=r,this.startTime=null,this.endTime=null,this.screen=null}return t.prototype.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues("textTrack"+this.track,this.startTime,this.endTime,this.screen),this.startTime=null)},t.prototype.newCue=function(t,e,r){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=r,this.timelineController.createCaptionsTrack(this.track)},t}(),mr=yr,br=function(t,e,r){return t.substr(r||0,e.length)===e},Er=function(t){var e=parseInt(t.substr(-3)),r=parseInt(t.substr(-6,2)),i=parseInt(t.substr(-9,2)),a=t.length>9?parseInt(t.substr(0,t.indexOf(":"))):0;return isNaN(e)||isNaN(r)||isNaN(i)||isNaN(a)?-1:(e+=1e3*r,e+=6e4*i,e+=36e5*a)},Tr=function(t){for(var e=5381,r=t.length;r;)e=33*e^t.charCodeAt(--r);return(e>>>0).toString()},Rr=function(t,e,r){var i=t[e],a=t[i.prevCC];if(!a||!a.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;a&&a.new;)t.ccOffset+=i.start-a.start,i.new=!1,i=a,a=t[i.prevCC];t.presentationOffset=r},Ar={parse:function(t,e,r,i,a,n){var o=/\r\n|\n\r|\n|\r/g,s=Object(Te.b)(new Uint8Array(t)).trim().replace(o,"\n").split("\n"),l="00:00.000",u=0,d=0,h=0,c=[],f=void 0,p=!0,g=new $e;g.oncue=function(t){var e=r[i],a=r.ccOffset;e&&e.new&&(void 0!==d?a=r.ccOffset=e.start:Rr(r,i,h)),h&&(a=h+r.ccOffset-r.presentationOffset),t.startTime+=a-d,t.endTime+=a-d,t.id=Tr(t.startTime.toString())+Tr(t.endTime.toString())+Tr(t.text),t.text=decodeURIComponent(encodeURIComponent(t.text)),t.endTime>0&&c.push(t)},g.onparsingerror=function(t){f=t},g.onflush=function(){if(f&&n)return void n(f);a(c)},s.forEach(function(t){if(p){if(br(t,"X-TIMESTAMP-MAP=")){p=!1,t.substr(16).split(",").forEach(function(t){br(t,"LOCAL:")?l=t.substr(6):br(t,"MPEGTS:")&&(u=parseInt(t.substr(7)))});try{e=e<0?e+8589934592:e,u-=e,d=Er(l)/1e3,h=u/9e4,-1===d&&(f=new Error("Malformed X-TIMESTAMP-MAP: "+t))}catch(e){f=new Error("Malformed X-TIMESTAMP-MAP: "+t)}return}""===t&&(p=!1)}g.parse(t+"\n")}),g.flush()}},Sr=Ar,_r=function(t){function e(r){ft(this,e);var i=pt(this,t.call(this,r,It.a.MEDIA_ATTACHING,It.a.MEDIA_DETACHING,It.a.FRAG_PARSING_USERDATA,It.a.FRAG_DECRYPTED,It.a.MANIFEST_LOADING,It.a.MANIFEST_LOADED,It.a.FRAG_LOADED,It.a.LEVEL_SWITCHING,It.a.INIT_PTS_FOUND));if(i.hls=r,i.config=r.config,i.enabled=!0,i.Cues=r.config.cueHandler,i.textTracks=[],i.tracks=[],i.unparsedVttFrags=[],i.initPTS=void 0,i.cueRanges=[],i.config.enableCEA708Captions){var a=new mr(i,1),n=new mr(i,2);i.cea608Parser=new vr(0,a,n)}return i}return gt(e,t),e.prototype.addCues=function(t,e,r,i){for(var a=this.cueRanges,n=!1,o=a.length;o--;){var s=a[o],l=mt(s[0],s[1],e,r);if(l>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],r),n=!0,l/(r-e)>.5))return}n||a.push([e,r]),this.Cues.newCue(this[t],e,r,i)},e.prototype.onInitPtsFound=function(t){var e=this;void 0===this.initPTS&&(this.initPTS=t.initPTS),this.unparsedVttFrags.length&&(this.unparsedVttFrags.forEach(function(t){e.onFragLoaded(t)}),this.unparsedVttFrags=[])},e.prototype.getExistingTrack=function(t){var e=this.media;if(e)for(var r=0;r<e.textTracks.length;r++){var i=e.textTracks[r],a="textTrack"+t;if(!0===i[a])return i}return null},e.prototype.sendAddTrackEvent=function(t,e){var r=null;try{r=new window.Event("addtrack")}catch(t){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)},e.prototype.createCaptionsTrack=function(t){var e="textTrack"+t;if(!this[e]){var r=this.getExistingTrack(t);if(r)this[e]=r,vt(this[e]),this.sendAddTrackEvent(this[e],this.media);else{var i=this.createTextTrack("captions",this.config["captionsTextTrack"+t+"Label"],this.config.captionsTextTrack1LanguageCode);i&&(i[e]=!0,this[e]=i)}}},e.prototype.createTextTrack=function(t,e,r){var i=this.media;if(i)return i.addTextTrack(t,e,r)},e.prototype.destroy=function(){Ft.prototype.destroy.call(this)},e.prototype.onMediaAttaching=function(t){this.media=t.media,this._cleanTracks()},e.prototype.onMediaDetaching=function(){vt(this.textTrack1),vt(this.textTrack2)},e.prototype.onManifestLoading=function(){this.lastSn=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0},this._cleanTracks()},e.prototype._cleanTracks=function(){var t=this.media;if(t){var e=t.textTracks;if(e)for(var r=0;r<e.length;r++)vt(e[r])}},e.prototype.onManifestLoaded=function(t){var e=this;if(this.textTracks=[],this.unparsedVttFrags=this.unparsedVttFrags||[],this.initPTS=void 0,this.cueRanges=[],this.config.enableWebVTT){this.tracks=t.subtitles||[];var r=this.media?this.media.textTracks:[];this.tracks.forEach(function(t,i){var a=void 0;if(i<r.length){var n=r[i];yt(n,t)&&(a=n)}a||(a=e.createTextTrack("subtitles",t.name,t.lang)),a.mode=t.default?"showing":"hidden",e.textTracks.push(a)})}},e.prototype.onLevelSwitching=function(){this.enabled="NONE"!==this.hls.currentLevel.closedCaptions},e.prototype.onFragLoaded=function(t){var e=t.frag,r=t.payload;if("main"===e.type){var i=e.sn;if(i!==this.lastSn+1){var a=this.cea608Parser;a&&a.reset()}this.lastSn=i}else if("subtitle"===e.type)if(r.byteLength){if(void 0===this.initPTS)return void this.unparsedVttFrags.push(t);var n=e.decryptdata;null!=n&&null!=n.key&&"AES-128"===n.method||this._parseVTTs(e,r)}else this.hls.trigger(It.a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e})},e.prototype._parseVTTs=function(t,e){var r=this.vttCCs;r[t.cc]||(r[t.cc]={start:t.start,prevCC:this.prevCC,new:!0},this.prevCC=t.cc);var i=this.textTracks,a=this.hls;Sr.parse(e,this.initPTS,r,t.cc,function(e){var r=i[t.trackId];e.forEach(function(t){if(!r.cues.getCueById(t.id))try{r.addCue(t)}catch(i){var e=new window.TextTrackCue(t.startTime,t.endTime,t.text);e.id=t.id,r.addCue(e)}}),a.trigger(It.a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},function(e){Ct.b.log("Failed to parse VTT cue: "+e),a.trigger(It.a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t})})},e.prototype.onFragDecrypted=function(t){var e=t.payload,r=t.frag;if("subtitle"===r.type){if(void 0===this.initPTS)return void this.unparsedVttFrags.push(t);this._parseVTTs(r,e)}},e.prototype.onFragParsingUserdata=function(t){if(this.enabled&&this.config.enableCEA708Captions)for(var e=0;e<t.samples.length;e++){var r=this.extractCea608Data(t.samples[e].bytes);this.cea608Parser.addData(t.samples[e].pts,r)}},e.prototype.extractCea608Data=function(t){for(var e,r,i,a,n,o=31&t[0],s=2,l=[],u=0;u<o;u++)e=t[s++],r=127&t[s++],i=127&t[s++],a=0!=(4&e),n=3&e,0===r&&0===i||a&&0===n&&(l.push(r),l.push(i));return l},e}(Ft),Lr=_r,wr=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),Dr=function(t){function e(r){bt(this,e);var i=Et(this,t.call(this,r,It.a.MEDIA_ATTACHED,It.a.MEDIA_DETACHING,It.a.MANIFEST_LOADING,It.a.MANIFEST_LOADED,It.a.SUBTITLE_TRACK_LOADED));return i.tracks=[],i.trackId=-1,i.media=void 0,i.subtitleDisplay=!1,i}return Tt(e,t),e.prototype._onTextTracksChanged=function(){if(this.media){for(var t=-1,e=Rt(this.media.textTracks),r=0;r<e.length;r++)"showing"===e[r].mode&&(t=r);this.subtitleTrack=t}},e.prototype.destroy=function(){Ft.prototype.destroy.call(this)},e.prototype.onMediaAttached=function(t){var e=this;this.media=t.media,this.media&&(void 0!==this.queuedDefaultTrack&&(this.subtitleTrack=this.queuedDefaultTrack,delete this.queuedDefaultTrack),this.trackChangeListener=this._onTextTracksChanged.bind(this),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.subtitlePollingInterval=setInterval(function(){e.trackChangeListener()},500):this.media.textTracks.addEventListener("change",this.trackChangeListener))},e.prototype.onMediaDetaching=function(){this.media&&(this.useTextTrackPolling?clearInterval(this.subtitlePollingInterval):this.media.textTracks.removeEventListener("change",this.trackChangeListener),this.media=void 0)},e.prototype.onManifestLoading=function(){this.tracks=[],this.trackId=-1},e.prototype.onManifestLoaded=function(t){var e=this,r=t.subtitles||[];this.tracks=r,this.trackId=-1,this.hls.trigger(It.a.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:r}),r.forEach(function(t){t.default&&(e.media?e.subtitleTrack=t.id:e.queuedDefaultTrack=t.id)})},e.prototype.onTick=function(){var t=this.trackId,e=this.tracks[t];if(e){var r=e.details;void 0!==r&&!0!==r.live||(Ct.b.log("(re)loading playlist for subtitle track "+t),this.hls.trigger(It.a.SUBTITLE_TRACK_LOADING,{url:e.url,id:t}))}},e.prototype.onSubtitleTrackLoaded=function(t){var e=this;t.id<this.tracks.length&&(Ct.b.log("subtitle track "+t.id+" loaded"),this.tracks[t.id].details=t.details,t.details.live&&!this.timer&&(this.timer=setInterval(function(){e.onTick()},1e3*t.details.targetduration,this)),!t.details.live&&this.timer&&(clearInterval(this.timer),this.timer=null))},e.prototype.setSubtitleTrackInternal=function(t){if(!(t<-1||t>=this.tracks.length)){this.timer&&(clearInterval(this.timer),this.timer=null);var e=Rt(this.media.textTracks);if(-1!==this.trackId&&this.subtitleDisplay&&(e[this.trackId].mode="hidden"),this.trackId=t,Ct.b.log("switching to subtitle track "+t),this.hls.trigger(It.a.SUBTITLE_TRACK_SWITCH,{id:t}),-1!==t){var r=this.tracks[t];this.subtitleDisplay&&(e[t].mode="showing");var i=r.details;void 0!==i&&!0!==i.live||(Ct.b.log("(re)loading playlist for subtitle track "+t),this.hls.trigger(It.a.SUBTITLE_TRACK_LOADING,{url:r.url,id:t}))}}},wr(e,[{key:"subtitleTracks",get:function(){return this.tracks}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(t){this.trackId!==t&&this.setSubtitleTrackInternal(t)}}]),e}(Ft),kr=Dr,Ir=r(4),Or={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING"},Cr=function(t){function e(r){At(this,e);var i=St(this,t.call(this,r,It.a.MEDIA_ATTACHED,It.a.ERROR,It.a.KEY_LOADED,It.a.FRAG_LOADED,It.a.SUBTITLE_TRACKS_UPDATED,It.a.SUBTITLE_TRACK_SWITCH,It.a.SUBTITLE_TRACK_LOADED,It.a.SUBTITLE_FRAG_PROCESSED));return i.config=r.config,i.vttFragSNsProcessed={},i.vttFragQueues=void 0,i.currentlyProcessing=null,i.state=Or.STOPPED,i.currentTrackId=-1,i.ticks=0,i.decrypter=new Ir.a(r.observer,r.config),i}return _t(e,t),e.prototype.destroy=function(){Ft.prototype.destroy.call(this),this.state=Or.STOPPED},e.prototype.clearVttFragQueues=function(){var t=this;this.vttFragQueues={},this.tracks.forEach(function(e){t.vttFragQueues[e.id]=[]})},e.prototype.nextFrag=function(){if(null===this.currentlyProcessing&&this.currentTrackId>-1&&this.vttFragQueues[this.currentTrackId].length){var t=this.currentlyProcessing=this.vttFragQueues[this.currentTrackId].shift();this.fragCurrent=t,this.hls.trigger(It.a.FRAG_LOADING,{frag:t}),this.state=Or.FRAG_LOADING}},e.prototype.onSubtitleFragProcessed=function(t){t.success&&this.vttFragSNsProcessed[t.frag.trackId].push(t.frag.sn),this.currentlyProcessing=null,this.state=Or.IDLE,this.nextFrag()},e.prototype.onMediaAttached=function(){this.state=Or.IDLE},e.prototype.onError=function(t){var e=t.frag;e&&"subtitle"!==e.type||this.currentlyProcessing&&(this.currentlyProcessing=null,this.nextFrag())},e.prototype.tick=function(){var t=this;1===++this.ticks&&(this.doTick(),this.ticks>1&&setTimeout(function(){t.tick()},1),this.ticks=0)},e.prototype.doTick=function(){var t=this;switch(this.state){case Or.IDLE:var e=this.tracks,r=this.currentTrackId,i=this.vttFragSNsProcessed[r],a=this.vttFragQueues[r],n=this.currentlyProcessing?this.currentlyProcessing.sn:-1,o=function(t){return i.indexOf(t.sn)>-1},s=function(t){return a.some(function(e){return e.sn===t.sn})};if(!e)break;var l;if(r<e.length&&(l=e[r].details),void 0===l)break;l.fragments.forEach(function(e){o(e)||e.sn===n||s(e)||(e.decryptdata&&null!=e.decryptdata.uri&&null==e.decryptdata.key?(Ct.b.log("Loading key for "+e.sn),t.state=Or.KEY_LOADING,t.hls.trigger(It.a.KEY_LOADING,{frag:e})):(e.trackId=r,a.push(e),t.nextFrag()))})}},e.prototype.onSubtitleTracksUpdated=function(t){var e=this;Ct.b.log("subtitle tracks updated"),this.tracks=t.subtitleTracks,this.clearVttFragQueues(),this.vttFragSNsProcessed={},this.tracks.forEach(function(t){e.vttFragSNsProcessed[t.id]=[]})},e.prototype.onSubtitleTrackSwitch=function(t){this.currentTrackId=t.id,this.clearVttFragQueues()},e.prototype.onSubtitleTrackLoaded=function(){this.tick()},e.prototype.onKeyLoaded=function(){this.state===Or.KEY_LOADING&&(this.state=Or.IDLE,this.tick())},e.prototype.onFragLoaded=function(t){var e=this.fragCurrent,r=t.frag.decryptdata,i=t.frag,a=this.hls;if(this.state===Or.FRAG_LOADING&&e&&"subtitle"===t.frag.type&&e.sn===t.frag.sn&&t.payload.byteLength>0&&null!=r&&null!=r.key&&"AES-128"===r.method){var n;try{n=performance.now()}catch(t){n=Date.now()}this.decrypter.decrypt(t.payload,r.key.buffer,r.iv.buffer,function(t){var e;try{e=performance.now()}catch(t){e=Date.now()}a.trigger(It.a.FRAG_DECRYPTED,{frag:i,payload:t,stats:{tstart:n,tdecrypt:e}})})}},e}(Ft),Pr=Cr,xr={autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,initialLiveManifestSize:1,maxBufferLength:30,maxBufferSize:6e7,maxBufferHole:.5,maxSeekHole:2,lowBufferWatchdogPeriod:.5,highBufferWatchdogPeriod:3,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxMaxBufferLength:600,enableWorker:!0,enableSoftwareAES:!0,manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,startLevel:void 0,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,fragLoadingLoopThreshold:3,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Ge,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,fetchSetup:void 0,abrController:Ie,bufferController:Pe,capLevelController:Ne,fpsController:Ue,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0};xr.subtitleStreamController=Pr,xr.subtitleTrackController=kr,xr.timelineController=Lr,xr.cueHandler=wt,xr.enableCEA708Captions=!0,xr.enableWebVTT=!0,xr.captionsTextTrack1Label="English",xr.captionsTextTrack1LanguageCode="en",xr.captionsTextTrack2Label="Spanish",xr.captionsTextTrack2LanguageCode="es",xr.audioStreamController=ze,xr.audioTrackController=Ke;var Fr=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),Nr=function(){function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Lt(this,t);var i=t.DefaultConfig;if((r.liveSyncDurationCount||r.liveMaxLatencyDurationCount)&&(r.liveSyncDuration||r.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");for(var a in i)a in r||(r[a]=i[a]);if(void 0!==r.liveMaxLatencyDurationCount&&r.liveMaxLatencyDurationCount<=r.liveSyncDurationCount)throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');if(void 0!==r.liveMaxLatencyDuration&&(r.liveMaxLatencyDuration<=r.liveSyncDuration||void 0===r.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');Object(Ct.a)(r.debug),this.config=r,this._autoLevelCapping=-1;var n=this.observer=new oe.a;n.trigger=function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];n.emit.apply(n,[t,t].concat(r))},n.off=function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];n.removeListener.apply(n,[t].concat(r))},this.on=n.on.bind(n),this.off=n.off.bind(n),this.trigger=n.trigger.bind(n);var o=this.abrController=new r.abrController(this),s=new r.bufferController(this),l=new r.capLevelController(this),u=new r.fpsController(this),d=new qt(this),h=new Jt(this),c=new Zt(this),f=new Ae(this),p=this.levelController=new Ee(this),g=this.streamController=new ye(this),v=[p,g],y=r.audioStreamController;y&&v.push(new y(this)),this.networkControllers=v;var m=[d,h,c,o,s,l,u,f];if(y=r.audioTrackController){var b=new y(this);this.audioTrackController=b,m.push(b)}if(y=r.subtitleTrackController){var E=new y(this);this.subtitleTrackController=E,m.push(E)}[r.subtitleStreamController,r.timelineController].forEach(function(t){t&&m.push(new t(e))}),this.coreComponents=m}return t.isSupported=function(){var t=y(),e=window.SourceBuffer||window.WebKitSourceBuffer,r=t&&"function"==typeof t.isTypeSupported&&t.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove;return r&&i},Fr(t,null,[{key:"version",get:function(){return"0.8.7"}},{key:"Events",get:function(){return It.a}},{key:"ErrorTypes",get:function(){return Ot.b}},{key:"ErrorDetails",get:function(){return Ot.a}},{key:"DefaultConfig",get:function(){return t.defaultConfig?t.defaultConfig:xr},set:function(e){t.defaultConfig=e}}]),t.prototype.destroy=function(){Ct.b.log("destroy"),this.trigger(It.a.DESTROYING),this.detachMedia(),this.coreComponents.concat(this.networkControllers).forEach(function(t){t.destroy()}),this.url=null,this.observer.removeAllListeners(),this._autoLevelCapping=-1},t.prototype.attachMedia=function(t){Ct.b.log("attachMedia"),this.media=t,this.trigger(It.a.MEDIA_ATTACHING,{media:t})},t.prototype.detachMedia=function(){Ct.b.log("detachMedia"),this.trigger(It.a.MEDIA_DETACHING),this.media=null},t.prototype.loadSource=function(t){t=kt.a.buildAbsoluteURL(window.location.href,t,{alwaysNormalize:!0}),Ct.b.log("loadSource:"+t),this.url=t,this.trigger(It.a.MANIFEST_LOADING,{url:t})},t.prototype.startLoad=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;Ct.b.log("startLoad("+t+")"),this.networkControllers.forEach(function(e){e.startLoad(t)})},t.prototype.stopLoad=function(){Ct.b.log("stopLoad"),this.networkControllers.forEach(function(t){t.stopLoad()})},t.prototype.swapAudioCodec=function(){Ct.b.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.prototype.recoverMediaError=function(){Ct.b.log("recoverMediaError");var t=this.media;this.detachMedia(),this.attachMedia(t)},Fr(t,[{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){Ct.b.log("set currentLevel:"+t),this.loadLevel=t,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){Ct.b.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){Ct.b.log("set loadLevel:"+t),this.levelController.manualLevel=t}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(t){this.levelController.nextLoadLevel=t}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(t){Ct.b.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(t){Ct.b.log("set startLevel:"+t);var e=this;-1!==t&&(t=Math.max(t,e.minAutoLevel)),e.levelController.startLevel=t}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(t){Ct.b.log("set autoLevelCapping:"+t),this._autoLevelCapping=t}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){for(var t=this,e=t.levels,r=t.config.minAutoBitrate,i=e?e.length:0,a=0;a<i;a++){if((e[a].realBitrate?Math.max(e[a].realBitrate,e[a].bitrate):e[a].bitrate)>r)return a}return 0}},{key:"maxAutoLevel",get:function(){var t=this,e=t.levels,r=t.autoLevelCapping;return-1===r&&e&&e.length?e.length-1:r}},{key:"nextAutoLevel",get:function(){var t=this;return Math.min(Math.max(t.abrController.nextAutoLevel,t.minAutoLevel),t.maxAutoLevel)},set:function(t){var e=this;e.abrController.nextAutoLevel=Math.max(e.minAutoLevel,t)}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"liveSyncPosition",get:function(){return this.streamController.liveSyncPosition}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}}]),t}();e.default=Nr},function(t,e,r){function i(t){function e(i){if(r[i])return r[i].exports;var a=r[i]={i:i,l:!1,exports:{}};return t[i].call(a.exports,a,a.exports,e),a.l=!0,a.exports}var r={};e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="/",e.oe=function(t){throw console.error(t),t};var i=e(e.s=ENTRY_MODULE);return i.default||i}function a(t){return(t+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function n(t){var e=[],r=t.toString(),i=r.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!i)return e;for(var n,o=i[1],s=new RegExp("(\\\\n|\\W)"+a(o)+"\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\w|/|@]+).*?\\)","g");n=s.exec(r);)e.push(n[3]);return e}function o(t,e){for(var r=[e],i=[],a={};r.length;){var o=r.pop();if(!a[o]&&t[o]){a[o]=!0,i.push(o);var s=n(t[o]);r=r.concat(s)}}return i}t.exports=function(t,e){e=e||{};var a=r.m,n=e.all?Object.keys(a):o(a,t),s="("+i.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+n.map(function(t){return JSON.stringify(t)+": "+a[t].toString()}).join(",")+"})(self);",l=new window.Blob([s],{type:"text/javascript"});if(e.bare)return l;var u=window.URL||window.webkitURL||window.mozURL||window.msURL,d=u.createObjectURL(l),h=new window.Worker(d);return h.objectURL=d,h}},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=r(7),a=r(1),n=r(0),o=r(5),s=r.n(o),l=function(t){var e=new s.a;e.trigger=function(t){for(var r=arguments.length,i=Array(r>1?r-1:0),a=1;a<r;a++)i[a-1]=arguments[a];e.emit.apply(e,[t,t].concat(i))},e.off=function(t){for(var r=arguments.length,i=Array(r>1?r-1:0),a=1;a<r;a++)i[a-1]=arguments[a];e.removeListener.apply(e,[t].concat(i))};var r=function(e,r){t.postMessage({event:e,data:r})};t.addEventListener("message",function(a){var o=a.data;switch(o.cmd){case"init":var s=JSON.parse(o.config);t.demuxer=new i.a(e,o.typeSupported,s,o.vendor);try{Object(n.a)(!0===s.debug)}catch(t){console.warn("demuxerWorker: unable to enable logs")}r("init",null);break;case"demux":t.demuxer.push(o.data,o.decryptdata,o.initSegment,o.audioCodec,o.videoCodec,o.timeOffset,o.discontinuity,o.trackSwitch,o.contiguous,o.duration,o.accurateTimeOffset,o.defaultInitPTS)}}),e.on(a.a.FRAG_DECRYPTED,r),e.on(a.a.FRAG_PARSING_INIT_SEGMENT,r),e.on(a.a.FRAG_PARSED,r),e.on(a.a.ERROR,r),e.on(a.a.FRAG_PARSING_METADATA,r),e.on(a.a.FRAG_PARSING_USERDATA,r),e.on(a.a.INIT_PTS_FOUND,r),e.on(a.a.FRAG_PARSING_DATA,function(e,r){var i=[],a={event:e,data:r};r.data1&&(a.data1=r.data1.buffer,i.push(r.data1.buffer),delete r.data1),r.data2&&(a.data2=r.data2.buffer,i.push(r.data2.buffer),delete r.data2),t.postMessage(a,i)})};e.default=l}]).default}); \ No newline at end of file From bd67b1a2729e5ae9f06d3214ca8ed59e72adc4cf Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Thu, 16 Nov 2017 13:38:51 +0100 Subject: [PATCH 02/19] Minor VideoDash comment patch --- src/display/video/VideoDash.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/display/video/VideoDash.js b/src/display/video/VideoDash.js index e17c2cee..2f2209f8 100644 --- a/src/display/video/VideoDash.js +++ b/src/display/video/VideoDash.js @@ -833,7 +833,7 @@ FORGE.VideoDash.prototype._getCurrentVideoElementProperty = function(property, d /** * Create instance of the dash.js Media Player. - * @method FORGE.VideoDash#_instanciateDashMediaPlayer + * @method FORGE.VideoDash#_initDashMediaPlayer * @private */ FORGE.VideoDash.prototype._initDashMediaPlayer = function() From 8ca9d6f8a1980ade447a5fc47e56727e8995d3c6 Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Thu, 16 Nov 2017 13:39:02 +0100 Subject: [PATCH 03/19] Add HLS video format --- src/display/video/VideoFormat.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/display/video/VideoFormat.js b/src/display/video/VideoFormat.js index 1003245a..4dc16792 100644 --- a/src/display/video/VideoFormat.js +++ b/src/display/video/VideoFormat.js @@ -12,6 +12,13 @@ FORGE.VideoFormat = {}; */ FORGE.VideoFormat.DASH = "dash"; +/** + * @name FORGE.VideoFormat.HLS + * @type {string} + * @const + */ +FORGE.VideoFormat.HLS = "hls"; + /** * @name FORGE.VideoFormat.HTML5 * @type {string} From 8d0aac176f13e86bca77d280284c178e75f9da41 Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Thu, 16 Nov 2017 13:39:50 +0100 Subject: [PATCH 04/19] Add HLS video format to render classes --- src/display/DisplayList.js | 1 + src/media/Media.js | 6 +++++- src/plugin/PluginObjectFactory.js | 6 +++++- src/render/RenderManager.js | 2 +- src/render/background/BackgroundMeshRenderer.js | 2 +- src/render/background/BackgroundRenderer.js | 2 +- src/render/background/BackgroundShaderRenderer.js | 2 +- 7 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/display/DisplayList.js b/src/display/DisplayList.js index 207a5128..c61c6156 100644 --- a/src/display/DisplayList.js +++ b/src/display/DisplayList.js @@ -186,6 +186,7 @@ FORGE.DisplayList.types = "TextField", "Button", "VideoDash", + "VideoHls", "VideoHTML5", "Canvas", "Sprite", diff --git a/src/media/Media.js b/src/media/Media.js index 2773e2e2..964d0cec 100644 --- a/src/media/Media.js +++ b/src/media/Media.js @@ -129,7 +129,7 @@ FORGE.Media.prototype._parseConfig = function(config) return; } - // Warning : UID is not registered and applied to the FORGE.Image|FORGE.VideoHTML5|FORGE.VideoDash objects for registration + // Warning : UID is not registered and applied to the FORGE.Image|FORGE.VideoHTML5|FORGE.VideoDash|FORGE.VideoHls objects for registration this._uid = config.uid; this._options = (typeof config.options !== "undefined") ? config.options : null; @@ -247,6 +247,10 @@ FORGE.Media.prototype._parseConfig = function(config) { this._displayObject = new FORGE.VideoDash(this._viewer, this._uid); } + else if (typeof source.streaming !== "undefined" && source.streaming.toLowerCase() === FORGE.VideoFormat.HLS) + { + this._displayObject = new FORGE.VideoHls(this._viewer, this._uid); + } else { var scene = this._viewer.story.scene; diff --git a/src/plugin/PluginObjectFactory.js b/src/plugin/PluginObjectFactory.js index f2115235..38081275 100644 --- a/src/plugin/PluginObjectFactory.js +++ b/src/plugin/PluginObjectFactory.js @@ -235,7 +235,7 @@ FORGE.PluginObjectFactory.prototype.button = function(config) * @param {string=} streaming - The video streaming format. Can be "HTML5" or "DASH". * @param {string=} qualityMode - The video quality mode. Can be "auto" or "manual". * @param {boolean=} ambisonic - 3D sound including ambisonics. For "HTML5" video only. - * @return {(FORGE.VideoHTML5|FORGE.VideoDash)} Returns the created FORGE.Video object. + * @return {(FORGE.VideoHTML5|FORGE.VideoDash|FORGE.VideoHls)} Returns the created FORGE.Video object. */ FORGE.PluginObjectFactory.prototype.video = function(key, config, streaming, qualityMode, ambisonic) { @@ -245,6 +245,10 @@ FORGE.PluginObjectFactory.prototype.video = function(key, config, streaming, qua { video = new FORGE.VideoDash(this._viewer, key, config, qualityMode); } + else if(typeof streaming !== "undefined" && streaming.toLowerCase() === FORGE.VideoFormat.HLS) + { + video = new FORGE.VideoHls(this._viewer, key, config, qualityMode); + } else { video = new FORGE.VideoHTML5(this._viewer, key, config, qualityMode, ambisonic); diff --git a/src/render/RenderManager.js b/src/render/RenderManager.js index 4f3de080..2caba804 100644 --- a/src/render/RenderManager.js +++ b/src/render/RenderManager.js @@ -274,7 +274,7 @@ FORGE.RenderManager.prototype._setupMedia = function() media.onLoadComplete.addOnce(this._mediaLoadCompleteHandler, this); // If media is a video, listen to the quality change event - if (FORGE.Utils.isTypeOf(media.displayObject, ["VideoHTML5", "VideoDash"])) + if (FORGE.Utils.isTypeOf(media.displayObject, ["VideoHTML5", "VideoDash", "VideoHls"])) { media.displayObject.onQualityChange.add(this._mediaQualityChangeHandler, this); } diff --git a/src/render/background/BackgroundMeshRenderer.js b/src/render/background/BackgroundMeshRenderer.js index b5567487..d4758bdd 100644 --- a/src/render/background/BackgroundMeshRenderer.js +++ b/src/render/background/BackgroundMeshRenderer.js @@ -159,7 +159,7 @@ FORGE.BackgroundMeshRenderer.prototype._setDisplayObject = function(displayObjec this._texture = new THREE.Texture(); this._texture.image = displayObject.element; } - else if (FORGE.Utils.isTypeOf(displayObject, ["VideoHTML5", "VideoDash"])) + else if (FORGE.Utils.isTypeOf(displayObject, ["VideoHTML5", "VideoDash", "VideoHls"])) { // Evil hack from Hell // Reduce texture size for big videos on safari diff --git a/src/render/background/BackgroundRenderer.js b/src/render/background/BackgroundRenderer.js index 512fa7ea..e4a78916 100644 --- a/src/render/background/BackgroundRenderer.js +++ b/src/render/background/BackgroundRenderer.js @@ -136,7 +136,7 @@ FORGE.BackgroundRenderer.prototype._updateTexture = function() // doesn't refresh when there is no texture or texture container and when a video as WebGL texture is paused if (this._texture === null || this._textureCanvas === null || this._textureContext === null || typeof this._displayObject === "undefined" || this._displayObject === null || - this._displayObject.element === null || (FORGE.Utils.isTypeOf(this._displayObject, ["VideoHTML5", "VideoDash"]) === true && this._displayObject.playing === false)) + this._displayObject.element === null || (FORGE.Utils.isTypeOf(this._displayObject, ["VideoHTML5", "VideoDash", "VideoHls"]) === true && this._displayObject.playing === false)) { return; } diff --git a/src/render/background/BackgroundShaderRenderer.js b/src/render/background/BackgroundShaderRenderer.js index a5cbd4c2..fdb39358 100644 --- a/src/render/background/BackgroundShaderRenderer.js +++ b/src/render/background/BackgroundShaderRenderer.js @@ -89,7 +89,7 @@ FORGE.BackgroundShaderRenderer.prototype._setDisplayObject = function(displayObj this._texture = new THREE.Texture(); this._texture.image = displayObject.element; } - else if (FORGE.Utils.isTypeOf(displayObject, ["VideoHTML5", "VideoDash"])) + else if (FORGE.Utils.isTypeOf(displayObject, ["VideoHTML5", "VideoDash", "VideoHls"])) { // Evil hack from Hell // Reduce texture size for big videos on safari From 2da8c74cfafffabd583bb02ba605f1f5a6ef8c53 Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Thu, 16 Nov 2017 13:40:09 +0100 Subject: [PATCH 05/19] Prepare HLS extern --- externs/lib/hls.ext.js | 343 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 343 insertions(+) create mode 100644 externs/lib/hls.ext.js diff --git a/externs/lib/hls.ext.js b/externs/lib/hls.ext.js new file mode 100644 index 00000000..ed06386d --- /dev/null +++ b/externs/lib/hls.ext.js @@ -0,0 +1,343 @@ +/** + * Simple extern file for hls.js, used in ForgeJS player. + * Only include used methods from hls.js. + */ + +/** + * @const + */ +var Hls = {}; + + +/* +.attachMedia(video) +.on(event, function) +.loadSource(url) + +Hls.Events.MEDIA_ATTACHED +Hls.Events.MANIFEST_PARSED + + + + + + + */ + + +/** + * @constructor + * @return {!MediaPlayer} + */ +// function MediaPlayer() {}; + +/** + * @param {HTMLMediaElement=} video + * @param {HTMLSourceElement=} source + * @param {Object=} context + * @return {MediaPlayer|null} + */ +// MediaPlayer.prototype.create = function(video, source, context) {}; + +/** + * @param {HTMLMediaElement=} view - Optional arg to set the video element. + * @param {string=} source - Optional arg to set the media source. + * @param {boolean=} AutoPlay - Optional arg to set auto play. + */ +// MediaPlayer.prototype.initialize = function(view, source, AutoPlay) {}; + +/** + * @param {boolean} value + */ +// MediaPlayer.prototype.setAutoPlay = function(value) {}; + +/** + * @param {Object} element + */ +// MediaPlayer.prototype.attachView = function(element) {}; + +/** + * @param {(string|Object)} urlOrManifest + */ +// MediaPlayer.prototype.attachSource = function(urlOrManifest) {}; + +/** + * @return {boolean} + */ +// MediaPlayer.prototype.isReady = function() {}; + +// MediaPlayer.prototype.play = function() {}; + +// MediaPlayer.prototype.pause = function() {}; + +// MediaPlayer.prototype.reset = function() {}; + +/** + * @param {boolean} value + */ +// MediaPlayer.prototype.setMute = function(value) {}; + +/** + * @param {number} value + */ +// MediaPlayer.prototype.setVolume = function(value) {}; + +/** + * @param {number} value + */ +// MediaPlayer.prototype.seek = function(value) {}; + +/** + * @param {string=} streamId + */ +// MediaPlayer.prototype.time = function(streamId) {}; + +/** + * @return {number} + */ +// MediaPlayer.prototype.duration = function() {}; + +/** + * @param {string} type - {@link MediaPlayerEvents} + * @param {Function} listener - callback method when the event fires. + * @param {Object=} scope - context of the listener so it can be removed properly. + */ +// MediaPlayer.prototype.on = function(type, listener, scope) {}; + +/** + * @param {string} type - {@link MediaPlayerEvents} + * @param {Function} listener - callback method when the event fires. + * @param {Object=} scope - context of the listener so it can be removed properly. + */ +// MediaPlayer.prototype.off = function(type, listener, scope) {}; + +/** + * @return {Debug} + */ +// MediaPlayer.prototype.getDebug = function() {}; + +/** + * @return {DashMetrics} + */ +// MediaPlayer.prototype.getDashMetrics = function() {}; + +/** + * @param {string} type + * @return {Object} + */ +// MediaPlayer.prototype.getMetricsFor = function(type) {}; + +/** + * @param {string} type + * @return {number} + */ +// MediaPlayer.prototype.getQualityFor = function(type) {}; + +/** + * @param {string} type + * @param {number} value + */ +// MediaPlayer.prototype.setQualityFor = function(type, value) {}; + +/** + * @param {string} type + * @return {Array} + */ +// MediaPlayer.prototype.getBitrateInfoListFor = function(type) {}; + +/** + * @param {string} type - 'audio' | 'video' + * @param {boolean} value + * @default {boolean} true + */ +// MediaPlayer.prototype.setAutoSwitchQualityFor = function(type, value) {}; + +/** + * @param {boolean} value + * @default false + */ +// MediaPlayer.prototype.setFastSwitchEnabled = function(value) {}; + +/** + * @param {boolean} value + * @default {boolean} true + */ +// MediaPlayer.prototype.setScheduleWhilePaused = function(value) {}; + +/** + * @param {boolean} value + * @default false + */ +// MediaPlayer.prototype.enableBufferOccupancyABR = function(value) {}; + +/** + * @constructor + * @return {!MediaPlayerEvents} + */ +// function MediaPlayerEvents() {}; + +// MediaPlayerEvents.prototype.CAN_PLAY; +// MediaPlayerEvents.prototype.ERROR; +// MediaPlayerEvents.prototype.PLAYBACK_ENDED; +// MediaPlayerEvents.prototype.PLAYBACK_ERROR; +// MediaPlayerEvents.prototype.PLAYBACK_METADATA_LOADED; +// MediaPlayerEvents.prototype.PLAYBACK_PAUSED; +// MediaPlayerEvents.prototype.PLAYBACK_PROGRESS; +// MediaPlayerEvents.prototype.PLAYBACK_SEEKED; +// MediaPlayerEvents.prototype.PLAYBACK_STARTED; +// MediaPlayerEvents.prototype.PLAYBACK_TIME_UPDATED; +// MediaPlayerEvents.prototype.QUALITY_CHANGE_RENDERED; +// MediaPlayerEvents.prototype.QUALITY_CHANGE_REQUESTED; +// MediaPlayerEvents.prototype.STREAM_INITIALIZED; +// MediaPlayerEvents.prototype.PERIOD_SWITCH_COMPLETED; +// MediaPlayerEvents.prototype.METRIC_CHANGED; + +/** + * @constructor + * @return {!DashMetrics} + */ +// function DashMetrics() {}; + +// DashMetrics.prototype.getBandwidthForRepresentation = function(representationId, periodId) {}; + +/** + * @param {string} representationId + * @param {number} periodIdx + * @return {number} + */ +// DashMetrics.prototype.getIndexForRepresentation = function(representationId, periodIdx) {}; + +/** + * @param {string} bufferType - String 'audio' or 'video', + * @param {number} periodIdx - Make sure this is the period index not id + * @return {number} + */ +// DashMetrics.prototype.getMaxIndexForBufferType = function(bufferType, periodIdx) {}; + +/** + * @param {Object} metrics + * @return {*} + */ +// DashMetrics.prototype.getCurrentRepresentationSwitch = function(metrics) {}; + +/** + * @param {Object} metrics + * @return {number} + */ +// DashMetrics.prototype.getCurrentBufferLevel = function(metrics) {}; + +/** + * @param {Object} metrics + * @return {null|*} + */ +// DashMetrics.prototype.getRequestsQueue = function(metrics) {}; + +/** + * @param {Object} metrics + * @return {*} + */ +// DashMetrics.prototype.getHttpRequests = function(metrics) {}; + +/** + * @param {Object} metrics + * @return + */ +// DashMetrics.prototype.getCurrentDroppedFrames = function(metrics) {}; + +/** + * @constructor + * @return {!Debug} + */ +// function Debug() {}; + +/** + * @param {boolean} value Set to false if you want to turn off logging to the browser's console. + * @default true + */ +// Debug.prototype.setLogToBrowserConsole = function(value) {}; + +/** + * @constructor + * @return {!MetricsList} + */ +// function MetricsList() {}; + +/** + * @constructor + * @return {!StreamInfo} + */ +// function StreamInfo() {}; + +// StreamInfo.prototype.id; +// StreamInfo.prototype.index; +// StreamInfo.prototype.start; +// StreamInfo.prototype.duration; +// StreamInfo.prototype.manifestinfo; +// StreamInfo.prototype.isLast; +// StreamInfo.prototype.isFirst; + +/** + * @constructor + * @return {!BitrateInfo} + */ +// function BitrateInfo() {}; + +// BitrateInfo.prototype.qualityIndex; +// BitrateInfo.prototype.bitrate; +// BitrateInfo.prototype.width; +// BitrateInfo.prototype.height; + +/** + * @constructor + * @return {!DroppedFrames} + */ +// function DroppedFrames() {}; + +// DroppedFrames.prototype.droppedFrames; + +/** + * @constructor + * @return {!MetricChangedEvents} + */ +// function MetricChangedEvents() {}; + +// MetricChangedEvents.prototype.mediaType; + +/** + * @constructor + * @return {!SwitchEvents} + */ +// function SwitchEvents() {}; + +// SwitchEvents.prototype.fromStreamInfo; +// SwitchEvents.prototype.toStreamInfo; + +/** + * @constructor + * @return {!QualityEvents} + */ +// function QualityEvents() {}; + +// QualityEvents.prototype.mediaType; +// QualityEvents.prototype.oldQuality; +// QualityEvents.prototype.newQuality; + +/** + * @constructor + * @return {!RepresentationSwitch} + */ +// function RepresentationSwitch() {}; + +// RepresentationSwitch.prototype.mt; +// RepresentationSwitch.prototype.t; +// RepresentationSwitch.prototype.to; + +/** + * @const + */ +// Hls.MediaPlayer = MediaPlayer; + +/** + * @const + */ +// Hls.MediaPlayer.events = MediaPlayerEvents; \ No newline at end of file From 1464c07b66d77a7629a60c70d20d5af10140e18c Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Thu, 16 Nov 2017 13:40:34 +0100 Subject: [PATCH 06/19] Add VideoHLS class based on VideoDash one --- Gruntfile.js | 1 + src/display/video/VideoHls.js | 3132 +++++++++++++++++++++++++++++++++ 2 files changed, 3133 insertions(+) create mode 100644 src/display/video/VideoHls.js diff --git a/Gruntfile.js b/Gruntfile.js index 4e4117ce..bfa3a174 100755 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -168,6 +168,7 @@ module.exports = function(grunt) "src/display/video/VideoBase.js", "src/display/video/VideoHTML5.js", "src/display/video/VideoDash.js", + "src/display/video/VideoHls.js", "src/display/video/VideoTimeRanges.js", "src/display/video/VideoQuality.js", "src/display/video/VideoQualityMode.js", diff --git a/src/display/video/VideoHls.js b/src/display/video/VideoHls.js new file mode 100644 index 00000000..c60561b1 --- /dev/null +++ b/src/display/video/VideoHls.js @@ -0,0 +1,3132 @@ +/** + * HLS video controller. + * + * @constructor FORGE.VideoHls + * @param {FORGE.Viewer} viewer - {@link FORGE.Viewer} reference. + * @param {string} key - The video file id reference. + * @param {?(string|FORGE.VideoQuality|Array<(string|FORGE.VideoQuality)>)=} config - Either a {@link FORGE.VideoQuality} or a string URL. + * @param {string=} qualityMode - The default quality mode. + * @extends {FORGE.VideoBase} + * + * @todo ability to call the QualityAbort event. + * @todo add protection controller and protection key controller to be able to manage external secured streams (DRM) + * @todo Add subtitles management with <track> and VTT/TTML(EBU-TT-D) files + */ +FORGE.VideoHls = function(viewer, key, config, qualityMode) +{ + /** + * The video identifier. + * @name FORGE.VideoHls#_key + * @type {string} + * @private + */ + this._key = key; + + /** + * {@link FORGE.VideoQuality} for this video, it can be temporarily a string into the constructor. + * @name FORGE.VideoHls#_config + * @type {?(string|FORGE.VideoQuality|Array<(string|FORGE.VideoQuality)>)} + * @private + */ + this._config = config || null; + + /** + * The manifest URL. + * @name FORGE.VideoHls#_manifestUrl + * @type {string} + * @private + */ + this._manifestUrl = ""; + + /** + * Array of {@link FORGE.VideoQuality}. + * @name FORGE.VideoHls#_qualities + * @type {Array<FORGE.VideoQuality>} + * @private + */ + this._qualities = null; + + /** + * The index of the current quality (if -1 no video is selected as the current one). + * @name FORGE.Video#_currentQuality + * @type {number} + * @private + */ + // this._currentQuality = -1; + + /** + * First quality is initialized? + * @name FORGE.VideoHls#_qualityInitialized + * @type {boolean} + * @private + */ + // this._qualityInitialized = false; + + /** + * Default quality mode, it can be either "auto" or "manual", modes are listed by FORGE.VideoQualityMode constants. + * @name FORGE.VideoHls#_defaultQualityMode + * @type {string} + * @private + */ + this._defaultQualityMode = qualityMode || FORGE.VideoQualityMode.AUTO; + + /** + * Current Quality mode. + * @name FORGE.VideoHls#_qualityMode + * @type {string} + * @private + */ + this._qualityMode = ""; + + /** + * Video object that handle the dom and some stats about the video. + * @name FORGE.VideoHls#_video + * @type {Object} + * @private + */ + this._video = null; + + /** + * Does the video loop? + * @name FORGE.VideoHls#_loop + * @type {boolean} + * @private + */ + this._loop = false; + + /** + * The volume of the video. + * @name FORGE.VideoHls#_volume + * @type {number} + * @private + */ + this._volume = 1; + + /** + * Is the video volume is muted? + * @name FORGE.VideoHls#_muted + * @type {boolean} + * @private + */ + this._muted = false; + + /** + * Private reference to the previous volume before mute. + * @name FORGE.VideoHls#_mutedVolume + * @type {number} + * @private + */ + this._mutedVolume = 0; + + /** + * Playback rate of the video + * @name FORGE.VideoHls#_playbackRate + * @type {number} + * @private + */ + this._playbackRate = 1; + + /** + * Does the video have received its metaData? + * @name FORGE.VideoHls#_metaDataLoaded + * @type {boolean} + * @private + */ + this._metaDataLoaded = false; + + /** + * The hls.js Media Player library.<br> + * The hls.js library must be loaded prior to the video instanciation! + * @name FORGE.VideoHls#_hlsMediaPlayer + * @type {Hls.MediaPlayer} + * @private + */ + this._hlsMediaPlayer = null; + + /** + * The hls stream info object. + * @name FORGE.VideoHls#_streamInfo + * @type {StreamInfo} + * @private + */ + this._streamInfo = null; + + /** + * The current index for video. + * @name FORGE.VideoHls#_currentIndex + * @type {number} + * @private + */ + this._currentVideoIndex = 0; + + /** + * The current pending index for video. + * @name FORGE.VideoHls#_currentPendingIndex + * @type {number} + * @private + */ + this._currentVideoPendingIndex = 0; + + /** + * The current index for audio. + * @name FORGE.VideoHls#_currentIndex + * @type {number} + * @private + */ + this._currentAudioIndex = 0; + + /** + * The current pending index for audio. + * @name FORGE.VideoHls#_currentPendingIndex + * @type {number} + * @private + */ + this._currentAudioPendingIndex = 0; + + /** + * The hls media player video metrics object. + * @name FORGE.VideoHls#_playerVideoMetrics + * @type {Object} + * @private + */ + this._playerVideoMetrics = null; + + /** + * The hls media player audio metrics object. + * @name FORGE.VideoHls#_playerAudioMetrics + * @type {Object} + * @private + */ + this._playerAudioMetrics = null; + + /** + * The hls stream metrics object. + * @name FORGE.VideoHls#_hlsMetrics + * @type {hlsMetrics} + * @private + */ + this._hlsMetrics = null; + + /** + * The monitoring object. + * @name FORGE.VideoHls#_monitoring + * @type {Object} + * @private + */ + this._monitoring = null; + + /** + * On load start event dispatcher. + * @name FORGE.VideoHls#_onLoadStart + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onLoadStart = null; + + /** + * On loaded metadata event dispatcher. + * @name FORGE.VideoHls#_onLoadedMetaData + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onLoadedMetaData = null; + + /** + * On loaded data event dispatcher. + * @name FORGE.VideoHls#_onLoadedData + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onLoadedData = null; + + /** + * On progress event dispatcher. + * @name FORGE.VideoHls#_onProgress + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onProgress = null; + + /** + * On duration change event dispatcher. + * @name FORGE.VideoHls#_onDurationChange + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onDurationChange = null; + + /** + * On can play event dispatcher. + * @name FORGE.VideoHls#_onCanPlay + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onCanPlay = null; + + /** + * On can play through event dispatcher. + * @name FORGE.VideoHls#_onCanPlayThrough + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onCanPlayThrough = null; + + /** + * On play event dispatcher. + * @name FORGE.VideoHls#_onPlay + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onPlay = null; + + /** + * On pause event dispatcher. + * @name FORGE.VideoHls#_onPause + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onPause = null; + + /** + * On time update event dispatcher. + * @name FORGE.VideoHls#_onTimeUpdate + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onTimeUpdate = null; + + /** + * On current time change event dispatcher. + * @name FORGE.VideoHls#_onCurrentTimeChange + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onCurrentTimeChange = null; + + /** + * On volume change event dispatcher. + * @name FORGE.VideoHls#_onVolumeChange + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onVolumeChange = null; + + /** + * On seeking event dispatcher. + * @name FORGE.VideoHls#_onSeeking + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onSeeking = null; + + /** + * On seeked event dispatcher. + * @name FORGE.VideoHls#_onSeeked + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onSeeked = null; + + /** + * On ended event dispatcher. + * @name FORGE.VideoHls#_onEnded + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onEnded = null; + + /** + * On error event dispatcher. + * @name FORGE.VideoHls#_onError + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onError = null; + + /** + * On stalled event dispatcher. + * @name FORGE.VideoHls#_onStalled + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onStalled = null; + + /** + * On rate change event dispatcher. + * @name FORGE.VideoHls#_onRateChange + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onRateChange = null; + + /** + * On playing event dispatcher. + * @name FORGE.VideoHls#_onPlaying + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onPlaying = null; + + /** + * On mute event dispatcher. + * @name FORGE.VideoHls#_onMute + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onMute = null; + + /** + * On unmute event dispatcher. + * @name FORGE.VideoHls#_onUnmute + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onUnmute = null; + + /** + * On qualityRequest event dispatcher. + * @name FORGE.VideoHls#_onQualityRequest + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onQualityRequest = null; + + /** + * On qualityChange event dispatcher. + * @name FORGE.VideoHls#_onQualityChange + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onQualityChange = null; + + /** + * On qualityAbort event dispatcher. + * @name FORGE.VideoHls#_onQualityAbort + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onQualityAbort = null; + + /** + * On qualties loaded event dispatcher. + * @name FORGE.VideoHls#_onQualitiesLoaded + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onQualitiesLoaded = null; + + /** + * On qualityModeChange event dispatcher. + * @name FORGE.VideoHls#_onQualityModeChange + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onQualityModeChange = null; + + /** + * On metrics changed event dispatcher. + * @name FORGE.VideoHls#_onMetricsChanged + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onMetricsChanged = null; + + /** + * Event handler for current video load start binded to this. + * @name FORGE.VideoHls#_onLoadStartBind + * @type {Function} + * @private + */ + this._onLoadStartBind = null; + + /** + * Event handler for current video loaded meta data binded to this. + * @name FORGE.VideoHls#_onLoadedMetaDataBind + * @type {Function} + * @private + */ + this._onLoadedMetaDataBind = null; + + /** + * Event handler for current video loaded data binded to this. + * @name FORGE.VideoHls#_onLoadedDataBind + * @type {Function} + * @private + */ + this._onLoadedDataBind = null; + + /** + * Event handler for current video progress binded to this. + * @name FORGE.VideoHls#_onProgressBind + * @type {Function} + * @private + */ + this._onProgressBind = null; + + /** + * Event handler for current video duration change binded to this. + * @name FORGE.VideoHls#_onDurationChangeBind + * @type {Function} + * @private + */ + this._onDurationChangeBind = null; + + /** + * Event handler for current video can play binded to this. + * @name FORGE.VideoHls#_onCanPlayBind + * @type {Function} + * @private + */ + this._onCanPlayBind = null; + + /** + * Event handler for current video can play throught binded to this. + * @name FORGE.VideoHls#_onCanPlayThroughBind + * @type {Function} + * @private + */ + this._onCanPlayThroughBind = null; + + /** + * Event handler for current video play binded to this. + * @name FORGE.VideoHls#_onPlayBind + * @type {Function} + * @private + */ + this._onPlayBind = null; + + /** + * Event handler for current video pause binded to this. + * @name FORGE.VideoHls#_onPauseBind + * @type {Function} + * @private + */ + this._onPauseBind = null; + + /** + * Event handler for current video time update binded to this. + * @name FORGE.VideoHls#_onTimeUpdateBind + * @type {Function} + * @private + */ + this._onTimeUpdateBind = null; + + /** + * Event handler for current video volume change binded to this. + * @name FORGE.VideoHls#_onVolumeChangeBind + * @type {Function} + * @private + */ + this._onVolumeChangeBind = null; + + /** + * Event handler for current video seeking binded to this. + * @name FORGE.VideoHls#_onSeekingBind + * @type {Function} + * @private + */ + this._onSeekingBind = null; + + /** + * Event handler for current video seeked binded to this. + * @name FORGE.VideoHls#_onSeekedBind + * @type {Function} + * @private + */ + this._onSeekedBind = null; + + /** + * Event handler for current video ended binded to this. + * @name FORGE.VideoHls#_onEndedBind + * @type {Function} + * @private + */ + this._onEndedBind = null; + + /** + * Event handler for current video error binded to this. + * @name FORGE.VideoHls#_onErrorBind + * @type {Function} + * @private + */ + this._onErrorBind = null; + + /** + * Event handler for current video stalled binded to this. + * @name FORGE.VideoHls#_onStalledBind + * @type {Function} + * @private + */ + this._onStalledBind = null; + + /** + * Event handler for current video rate change binded to this. + * @name FORGE.VideoHls#_onRateChangeBind + * @type {Function} + * @private + */ + this._onRateChangeBind = null; + + /** + * Event handler for current video playing binded to this. + * @name FORGE.VideoHls#_onPlayingBind + * @type {Function} + * @private + */ + this._onPlayingBind = null; + + /** + * Event handler for current video quality request binded to this. + * @name FORGE.VideoHls#_onQualityRequestBind + * @type {Function} + * @private + */ + this._onQualityRequestBind = null; + + /** + * Event handler for current video quality change binded to this. + * @name FORGE.VideoHls#_onQualityChangeBind + * @type {Function} + * @private + */ + this._onQualityChangeBind = null; + + /** + * Event handler for current video quality change aborted binded to this. + * @name FORGE.VideoHls#_onQualityAbortBind + * @type {Function} + * @private + */ + //this._onQualityAbortBind = null; + + /** + * Event handler for stream switch completed. + * @name FORGE.VideoHls#_onSwitchCompletedBind + * @type {Function} + * @private + */ + this._onSwitchCompletedBind = null; + + /** + * Event handler for metrics changed. + * @name FORGE.VideoHls#_onMetricsChangedBind + * @type {Function} + * @private + */ + this._onMetricsChangedBind = null; + + FORGE.VideoBase.call(this, viewer, "VideoHls"); +}; + +FORGE.VideoHls.prototype = Object.create(FORGE.VideoBase.prototype); +FORGE.VideoHls.prototype.constructor = FORGE.VideoHls; + +/** + * Media types list. + * @name FORGE.VideoHls.mediaType + * @type {Object} + * @const + */ +FORGE.VideoHls.mediaType = {}; + +/** + * @name FORGE.VideoHls.mediaType.VIDEO + * @type {string} + * @const + */ +FORGE.VideoHls.mediaType.VIDEO = "video"; + +/** + * @name FORGE.VideoHls.mediaType.AUDIO + * @type {string} + * @const + */ +FORGE.VideoHls.mediaType.AUDIO = "audio"; + +/** + * Boot sequence. + * @method FORGE.VideoHls#_boot + * @private + */ +FORGE.VideoHls.prototype._boot = function() +{ + FORGE.VideoBase.prototype._boot.call(this); + + if (typeof Hls === "undefined") + { + throw "FORGE.VideoHls._boot: Can't create HLS video stream without hls.js Media Player."; + } + + if (Hls.isSupported() === false) + { + throw "FORGE.VideoHls._boot: HLS video stream is not supported by your browser."; + } + + //register the uid + this._uid = this._key; + this._register(); + + this._loadHlsMediaPlayerSourceBind = this._loadHlsMediaPlayerSource.bind(this); + + this._onLoadStartBind = this._onLoadStartHandler.bind(this); + this._onDurationChangeBind = this._onDurationChangeHandler.bind(this); + this._onLoadedMetaDataBind = this._onLoadedMetaDataHandler.bind(this); + this._onLoadedDataBind = this._onLoadedDataHandler.bind(this); + this._onProgressBind = this._onProgressHandler.bind(this); + this._onCanPlayBind = this._onCanPlayHandler.bind(this); + this._onCanPlayThroughBind = this._onCanPlayThroughHandler.bind(this); + this._onPlayBind = this._onPlayHandler.bind(this); + this._onPauseBind = this._onPauseHandler.bind(this); + this._onTimeUpdateBind = this._onTimeUpdateHandler.bind(this); + this._onVolumeChangeBind = this._onVolumeChangeHandler.bind(this); + this._onSeekingBind = this._onSeekingHandler.bind(this); + this._onSeekedBind = this._onSeekedHandler.bind(this); + this._onEndedBind = this._onEndedHandler.bind(this); + this._onErrorBind = this._onErrorHandler.bind(this); + this._onStalledBind = this._onStalledHandler.bind(this); + this._onRateChangeBind = this._onRateChangeHandler.bind(this); + this._onPlayingBind = this._onPlayingHandler.bind(this); + this._onQualityRequestBind = this._onQualityRequestHandler.bind(this); + this._onQualityChangeBind = this._onQualityChangeHandler.bind(this); + //this._onQualityAbortBind = this._onQualityAbortHandler.bind(this); + + // HLS specific + this._onSwitchCompletedBind = this._onSwitchCompletedHandler.bind(this); + this._onMetricsChangedBind = this._onMetricsChangedHandler.bind(this); + + //Listen to the main volume change to adapt the video volume accordingly. + this._viewer.audio.onVolumeChange.add(this._mainVolumeChangeHandler, this); + + //Listen to the enabled state of the sound manager. + this._viewer.audio.onDisable.add(this._disableSoundHandler, this); + + //force the creation of "onQualitiesLoaded" event dispatcher and memorize it's data + this._onQualitiesLoaded = new FORGE.EventDispatcher(this, true); + + if (this._config !== null) + { + this.load(this._config); + } + + this._viewer.display.register(this); + this._notifyReady(); + this._applyPending(false); +}; + +/** + * Parse the video configuration object. + * @method FORGE.VideoHls#_parseConfig + * @private + * @param {?(string|FORGE.VideoQuality|Array<(string|FORGE.VideoQuality)>)} config - The config object to parse. + * @return {string} Returns the manifest url for HLS. + */ +FORGE.VideoHls.prototype._parseConfig = function(config) +{ + if (config !== null) + { + if (FORGE.Utils.isTypeOf(config, "string") === true) + { + config = [config]; + } + else if (FORGE.Utils.isTypeOf(config, "VideoQuality") === true) + { + config = [config]; + } + + if (FORGE.Utils.isArrayOf(config, "string") === true) + { + this._manifestUrl = config[0]; + } + else if (FORGE.Utils.isArrayOf(config, "VideoQuality") === true) + { + this._manifestUrl = config[0].url; + } + } + + return this._manifestUrl; +}; + +/** + * Notify that the dispay object has been resized.<br> + * This method ovverrides the {@link FORGE.DisplayObject} method. + * @method FORGE.VideoHls#_notifyResize + * @private + * @param {PropertyToUpdate} data - The data contains the property that have changed. + */ +FORGE.VideoHls.prototype._notifyResize = function(data) +{ + var video = this._video; + + if (video !== null && video.element !== null) + { + video.element.setAttribute("width", this.pixelWidth); + video.element.setAttribute("height", this.pixelHeight); + } + + FORGE.DisplayObject.prototype._notifyResize.call(this, data); +}; + +/** + * Create placeholders objects for videos and theirs attributes. + * @method FORGE.VideoHls#_createVideoObject + * @private + * @return {Object} Returns the populated videos array. + */ +FORGE.VideoHls.prototype._createVideoObject = function() +{ + var video = { + index: 0, + element: null, + buffer: null, + played: null + }; + + this._video = video; + + return video; +}; + +/** + * Populate a video object with an element <video> and a buffer/played {@link FORGE.VideoTimeRanges} managers. + * @method FORGE.VideoHls#_createVideoTag + * @private + * @return {Object} Returns the populated video object. + */ +FORGE.VideoHls.prototype._createVideoTag = function() +{ + //Create a video tag and get the quality + var element = document.createElement("video"); + element.setAttribute("webkit-playsinline", "webkit-playsinline"); + element.setAttribute("width", this.pixelWidth); + element.setAttribute("height", this.pixelHeight); + element.volume = 0; + element.playbackRate = this._playbackRate; + element.crossOrigin = "anonymous"; + element.id = "FORGE-VideoHls-" + this._uid; + + var buffer = new FORGE.VideoTimeRanges(element, "buffered"); + var played = new FORGE.VideoTimeRanges(element, "played"); + + //Update the video object with the element and fresh buffer and played + var video = this._video; + video.element = element; + video.buffer = buffer; + video.played = played; + video.lastTimeStamp = 0; + + return video; +}; + +/** + * Get a property of the video element of the current video object. + * @method FORGE.VideoHls#_getCurrentVideoElementProperty + * @param {string} property - The property you want to get from the current video element. + * @param {*} defaultReturnValue - The default return value if the video object or its element is null. + * @return {*} Return the requested property value or the default one if necessary. + * @private + */ +FORGE.VideoHls.prototype._getCurrentVideoElementProperty = function(property, defaultReturnValue) +{ + var video = this._video; + + if (video !== null && video.element !== null) + { + return video.element[property]; + } + + return defaultReturnValue; +}; + +/** + * Create instance of the hls.js Media Player. + * @method FORGE.VideoHls#_initHlsMediaPlayer + * @private + */ +FORGE.VideoHls.prototype._initHlsMediaPlayer = function() +{ + var hlsConfig = { + autoStartLoad: false, // start after Hls.Events.MANIFEST_PARSED + startPosition : -1, // startTime + debug: true, + startLevel: undefined, + enableWebVTT: true, + enableCEA708Captions: true, + stretchShortVideoTrack: false, + maxAudioFramesDrift : 1, + forceKeyFrameOnDiscontinuity: true + }; + + // create the Media Player + this._hlsMediaPlayer = new Hls(hlsConfig); + + // add video tag element and video source file + this._hlsMediaPlayer.attachMedia(this._video.element); + + // hls Media Player is ready? + this._hlsMediaPlayer.on(Hls.Events.MEDIA_ATTACHED, this._loadHlsMediaPlayerSourceBind); + + if (this._qualityMode === "") + { + this._setQualityMode(this._defaultQualityMode); + } +}; + +/** + * Load source into the hls.js Media Player. + * @method FORGE.VideoHls#_loadHlsMediaPlayerSource + * @private + */ +FORGE.VideoHls.prototype._loadHlsMediaPlayerSource = function() +{ + console.log("video and hls.js are now bound together !"); + this._hlsMediaPlayer.loadSource(this._manifestUrl); + // this._hlsMediaPlayer.on(Hls.Events.MANIFEST_PARSED, function (event, data) { + // console.log("manifest loaded, found " + data.levels.length + " quality level"); + // }); + + this._installEvents(); + + this._addVideoToDom(); +}; + +/** + * Add video element to the DOM. + * @method FORGE.VideoHls#_addVideoToDom + * @private + */ +FORGE.VideoHls.prototype._addVideoToDom = function() +{ + // Remove video tag from our container div + this._dom.innerHTML = ""; + + this._dom.appendChild(this._video.element); +}; + +/** + * Bind native events handler for the current video. + * @method FORGE.VideoHls#_installEvents + * @private + */ +FORGE.VideoHls.prototype._installEvents = function() +{ + this._hlsMediaPlayer.on(Hls.Events.MANIFEST_PARSED, function (event, data) { + console.log("manifest loaded, found " + data.levels.length + " quality level"); + }); + + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["CAN_PLAY"], this._onCanPlayBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["ERROR"], this._onErrorBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_ENDED"], this._onEndedBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_ERROR"], this._onErrorBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_METADATA_LOADED"], this._onLoadedMetaDataBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_PAUSED"], this._onPauseBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_PROGRESS"], this._onProgressBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_SEEKING"], this._onSeekingBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_SEEKED"], this._onSeekedBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_STARTED"], this._onPlayBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_TIME_UPDATED"], this._onTimeUpdateBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["QUALITY_CHANGE_RENDERED"], this._onQualityChangeBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["QUALITY_CHANGE_REQUESTED"], this._onQualityRequestBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["STREAM_INITIALIZED"], this._onLoadStartBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_PLAYING"], this._onPlayingBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["BUFFER_EMPTY"], this._onStalledBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_RATE_CHANGED"], this._onRateChangeBind); + + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PERIOD_SWITCH_COMPLETED"], this._onSwitchCompletedBind); + // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["METRIC_CHANGED"], this._onMetricsChangedBind); + + this._video.element.addEventListener("loadeddata", this._onLoadedDataBind, false); + this._video.element.addEventListener("durationchange", this._onDurationChangeBind, false); + this._video.element.addEventListener("canplaythrough", this._onCanPlayThroughBind, false); + this._video.element.addEventListener("volumechange", this._onVolumeChangeBind, false); +}; + +/** + * Unbind events handler for video. + * @method FORGE.VideoHls#_uninstallEvents + * @private + */ +FORGE.VideoHls.prototype._uninstallEvents = function() +{ + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["CAN_PLAY"], this._onCanPlayBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["ERROR"], this._onErrorBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_ENDED"], this._onEndedBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_ERROR"], this._onErrorBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_METADATA_LOADED"], this._onLoadedMetaDataBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_PAUSED"], this._onPauseBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_PROGRESS"], this._onProgressBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_SEEKING"], this._onSeekingBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_SEEKED"], this._onSeekedBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_STARTED"], this._onPlayBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_TIME_UPDATED"], this._onTimeUpdateBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["QUALITY_CHANGE_RENDERED"], this._onQualityChangeBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["QUALITY_CHANGE_REQUESTED"], this._onQualityRequestBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["STREAM_INITIALIZED"], this._onLoadStartBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_PLAYING"], this._onPlayingBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["BUFFER_EMPTY"], this._onStalledBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_RATE_CHANGED"], this._onRateChangeBind); + + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PERIOD_SWITCH_COMPLETED"], this._onSwitchCompletedBind); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["METRIC_CHANGED"], this._onMetricsChangedBind); + + this._video.element.removeEventListener("loadeddata", this._onLoadedDataBind, false); + this._video.element.removeEventListener("durationchange", this._onDurationChangeBind, false); + this._video.element.removeEventListener("canplaythrough", this._onCanPlayThroughBind, false); + this._video.element.removeEventListener("volumechange", this._onVolumeChangeBind, false); +}; + +/** + * Private event handler for loadStart. + * @method FORGE.VideoHls#_onLoadStartHandler + * @param {Event} event - The native video event. + * @private + */ +FORGE.VideoHls.prototype._onLoadStartHandler = function(event) +{ + var element = this._video.element; + this.log("onLoadStart [readyState: " + element.readyState + "]"); + + //populate qualities array with the HLS bitrates info list + this._createQualitiesFromBitrateInfoList(this._manifestUrl, this._hlsMediaPlayer.getBitrateInfoListFor(FORGE.VideoHls.mediaType.VIDEO)); + + if (this._onLoadStart !== null) + { + this._onLoadStart.dispatch(event); + } +}; + +/** + * Create a qualities array from the bitrates info list. + * @method FORGE.VideoHls#_createQualitiesFromBitrateInfoList + * @param {string} url - The manifest url. + * @param {Array<BitrateInfo>} bitrates - The bitrates array. + * @param {boolean=} checkURL - URL must be checked? + * @return {Array<FORGE.VideoQuality>} The qualities array. + * @private + */ +FORGE.VideoHls.prototype._createQualitiesFromBitrateInfoList = function(url, bitrates, checkURL) +{ + var qualities = []; + var quality; + + if (bitrates !== null) + { + for (var i = 0, ii = bitrates.length; i < ii; i++) + { + if (checkURL === true && FORGE.URL.isValid(url) === false) + { + throw "FORGE.Video: URL " + url + " is invalid"; + } + + quality = new FORGE.VideoQuality(url); + quality.id = bitrates[i].qualityIndex; + quality.bitrate = bitrates[i].bitrate; + quality.width = bitrates[i].width; + quality.height = bitrates[i].height; + + qualities.push(quality); + } + + this._qualities = /** @type {Array<FORGE.VideoQuality>} */ (qualities); + + if (this._onQualitiesLoaded !== null) + { + this._onQualitiesLoaded.dispatch(qualities); + } + } + else + { + this.destroy(); + } + + return qualities; +}; + +/** + * Get the index of a {@link FORGE.VideoQuality} that is in the _videoQualities array. + * @method FORGE.VideoHls#_indexOfQuality + * @private + * @param {FORGE.VideoQuality} quality - The quality you need to get its index. + * @return {number} Returns the index of the quality if found, -1 if not found. + */ +FORGE.VideoHls.prototype._indexOfQuality = function(quality) +{ + var q; + for (var i = 0, ii = this._qualities.length; i < ii; i++) + { + q = this._qualities[i]; + + if (q === quality) + { + return i; + } + } + + return -1; +}; + +/** + * Private event handler for period switch completed. + * @method FORGE.VideoHls#_onSwitchCompletedHandler + * @param {SwitchEvents} event - The hls.js media player event. + * @private + */ +FORGE.VideoHls.prototype._onSwitchCompletedHandler = function(event) +{ + var element = this._video.element; + this.log("_onSwitchCompleted [readyState: " + element.readyState + "]"); + + this._streamInfo = /** @type {StreamInfo} */ (event.toStreamInfo); +}; + +/** + * Private event handler for mertics changed. + * @method FORGE.VideoHls#_onMetricsChangedHandler + * @param {MetricChangedEvents} event - The hls.js media player event. + * @private + */ +FORGE.VideoHls.prototype._onMetricsChangedHandler = function(event) +{ + var element = this._video.element; + this.log("_onMetricsChangedHandler [readyState: " + element.readyState + "]"); + + if (this._playerVideoMetrics === null) + { + this._playerVideoMetrics = this._hlsMediaPlayer.getMetricsFor(FORGE.VideoHls.mediaType.VIDEO); + } + + if (this._playerAudioMetrics === null) + { + this._playerAudioMetrics = this._hlsMediaPlayer.getMetricsFor(FORGE.VideoHls.mediaType.AUDIO); + } + + if (this._hlsMetrics === null) + { + this._hlsMetrics = this._hlsMediaPlayer.gethlsMetrics(); + } + + //set the current quality index + // if (this._playerVideoMetrics !== null && this._hlsMetrics !== null) + // { + // var repSwitch = /** @type {RepresentationSwitch} */ (this._hlsMetrics.getCurrentRepresentationSwitch(this._playerVideoMetrics)); + // if (repSwitch !== null) + // { + // this._currentQuality = this._hlsMetrics.getIndexForRepresentation(repSwitch.to, this._streamInfo.index); + // if(this._qualityInitialized === false) + // { + // this._setRequestQuality(this._currentQuality); + // this._qualityInitialized = true; + // } + // } + // } + + if (this._onMetricsChanged !== null) + { + var metrics; + + if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) + { + metrics = this._getMetricsFor(FORGE.VideoHls.mediaType.VIDEO, this._playerVideoMetrics, this._hlsMetrics); + if (metrics) + { + this._monitoring = { + "videoBitrate": metrics.bitrate, + "videoIndex": metrics.index, + "videoPendingIndex": metrics.pendingIndex, + "videoMaxIndex": metrics.maxIndex, + "videoBufferLength": metrics.bufferLength, + "videoDroppedFrames": metrics.droppedFrames + //"videoRequestsQueue": metrics.requestsQueue + }; + } + } + + if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) + { + metrics = this._getMetricsFor(FORGE.VideoHls.mediaType.AUDIO, this._playerAudioMetrics, this._hlsMetrics); + if (metrics) + { + this._monitoring = { + "audioBitrate": metrics.bitrate, + "audioIndex": metrics.index, + "audioPendingIndex": metrics.pendingIndex, + "audioMaxIndex": metrics.maxIndex, + "audioBufferLength": metrics.bufferLength, + "audioDroppedFrames": metrics.droppedFrames + //"audioRequestsQueue": metrics.requestsQueue + }; + } + } + + this._onMetricsChanged.dispatch(event); + } +}; + + +/** + * Prepare a metrics object for video/audio data. + * @method FORGE.VideoHls#_getMetricsFor + * @param {string} type - The video or audio type. + * @param {Object} metrics - The player video or audio metrics. + * @param {hlsMetrics} hlsMetrics - The hls stream video or audio metrics. + * @return {?Object} The monitoring object + * @private + */ +FORGE.VideoHls.prototype._getMetricsFor = function(type, metrics, hlsMetrics) +{ + if (metrics !== null && hlsMetrics !== null) + { + var streamIndex = this._streamInfo.index; + var repSwitch, maxIndex, bufferLevel, droppedFramesMetrics, bitrate, index, pendingIndex, bufferLength, droppedFrames; //httpRequests requestsQueue pendingValue + + repSwitch = /** @type {RepresentationSwitch} */ (hlsMetrics.getCurrentRepresentationSwitch(metrics)); + if (repSwitch !== null) + { + // index = hlsMetrics.getIndexForRepresentation(repSwitch.to, streamIndex); + bitrate = Math.round(hlsMetrics.getBandwidthForRepresentation(repSwitch.to, streamIndex) / 1000); + } + if (isNaN(bitrate) || bitrate === undefined) + { + bitrate = 0; + } + + if (type === FORGE.VideoHls.mediaType.VIDEO) + { + index = this._currentVideoIndex + 1; + pendingIndex = this._currentVideoPendingIndex + 1; + } + else if (type === FORGE.VideoHls.mediaType.AUDIO) + { + index = this._currentAudioIndex + 1; + pendingIndex = this._currentAudioPendingIndex + 1; + } + + if (isNaN(index) || index === undefined) + { + index = 0; + } + if (isNaN(pendingIndex) || pendingIndex === undefined) + { + pendingIndex = 0; + } + + maxIndex = hlsMetrics.getMaxIndexForBufferType(type, streamIndex); + if (isNaN(maxIndex) || maxIndex === undefined) + { + maxIndex = 0; + } + + bufferLevel = hlsMetrics.getCurrentBufferLevel(metrics); + if (bufferLevel !== null) + { + bufferLength = bufferLevel.toPrecision(5); + } + if (isNaN(bufferLength) || bufferLength === undefined) + { + bufferLength = 0; + } + + //httpRequests = hlsMetrics.getHttpRequests(metrics); + + droppedFramesMetrics = /** @type {DroppedFrames} */ (hlsMetrics.getCurrentDroppedFrames(metrics)); + if (droppedFramesMetrics !== null) + { + droppedFrames = droppedFramesMetrics.droppedFrames; + } + + //pendingValue = this._hlsMediaPlayer.getQualityFor(type); + + //requestsQueue = hlsMetrics.getRequestsQueue(metrics); + + var result = { + bitrate: bitrate, + index: index, + pendingIndex: pendingIndex, + maxIndex: maxIndex, + bufferLength: bufferLength, + droppedFrames: droppedFrames + //requestsQueue: requestsQueue + }; + + return result; + } + + return null; +}; + +/** + * Private event handler for quality change. + * @method FORGE.VideoHls#_onQualityChangeHandler + * @private + * @param {QualityEvents} event - The hls.js media player event. + */ +FORGE.VideoHls.prototype._onQualityChangeHandler = function(event) +{ + var element = this._video.element; + this.log("onQualityChange [readyState: " + element.readyState + "]"); + + if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) + { + this._currentAudioIndex = event.newQuality; + this._currentAudioPendingIndex = event.newQuality; + } + else if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) + { + this._currentVideoIndex = event.newQuality; + this._currentVideoPendingIndex = event.newQuality; + + if (this._onQualityChange !== null) + { + this._onQualityChange.dispatch(this._currentVideoPendingIndex); + } + } +}; + +/** + * Private event handler for quality request. + * @method FORGE.VideoHls#_onQualityRequestHandler + * @private + * @param {QualityEvents} event - The hls.js media player event. + */ +FORGE.VideoHls.prototype._onQualityRequestHandler = function(event) +{ + var element = this._video.element; + this.log("onQualityRequest [readyState: " + element.readyState + "]"); + + if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) + { + this._currentAudioIndex = event.oldQuality; + this._currentAudioPendingIndex = event.newQuality; + } + else if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) + { + this._currentVideoIndex = event.oldQuality; + this._currentVideoPendingIndex = event.newQuality; + + if (this._onQualityRequest !== null) + { + this._onQualityRequest.dispatch(this._currentVideoPendingIndex); + } + } +}; + +/** + * Private event handler for quality request aborted. + * @method FORGE.VideoHls#_onQualityAbortHandler + * @private + * @param {Event} event - The hls.js media player event. + */ +// FORGE.VideoHls.prototype._onQualityAbortHandler = function(event) +// { +// var element = this._video.element; +// this.log("onQualityAbort [readyState: "+element.readyState+"]"); + +// if(this._onQualityAbort !== null) +// { +// this._onQualityAbort.dispatch(this._video.requestIndex); +// } +// }; + +/** + * Private event handler for durationChange. + * @method FORGE.VideoHls#_onDurationChangeHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onDurationChangeHandler = function(event) +{ + var element = this._video.element; + this.log("onDurationChange [readyState: " + element.readyState + "]"); + + //@firefox - FF disptach durationchange twice on readystate HAVE_METADATA (1) & HAVE_ENOUGH_DATA (4) + //I will not dispatch this event if readystate is HAVE_ENOUGH_DATA (4) ! + if (this._onDurationChange !== null && element.readyState === HTMLMediaElement.HAVE_METADATA) + { + this._onDurationChange.dispatch(event); + } +}; + +/** + * Private event handler for loadedMetaData. + * @method FORGE.VideoHls#_onLoadedMetaDataHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onLoadedMetaDataHandler = function(event) +{ + var element = this._video.element; + this.log("onLoadedMetaData [readyState: " + element.readyState + "]"); + + this._metaDataLoaded = true; + + if (this._onLoadedMetaData !== null) + { + this._onLoadedMetaData.dispatch(event); + } +}; + +/** + * Private event handler for loadedData. + * @method FORGE.VideoHls#_onLoadedDataHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onLoadedDataHandler = function(event) +{ + var element = this._video.element; + this.log("onLoadedData [readyState: " + element.readyState + "]"); + + if (this._onLoadedData !== null) + { + this._onLoadedData.dispatch(event); + } +}; + +/** + * Private event handler for progress. + * @method FORGE.VideoHls#_onProgressHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onProgressHandler = function(event) +{ + //var element = this._video.element; + //this.log("onProgress [readyState: "+element.readyState+"]"); + + if (this._onProgress !== null) + { + this._onProgress.dispatch(event); + } +}; + +/** + * Private event handler for canPlay. + * @method FORGE.VideoHls#_onCanPlayHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onCanPlayHandler = function(event) +{ + var element = this._video.element; + this.log("onCanPlay [readyState: " + element.readyState + "]"); + + this._canPlay = true; + + if (this._onCanPlay !== null) + { + this._onCanPlay.dispatch(event); + } +}; + +/** + * Private event handler for canPlayThrough. + * @method FORGE.VideoHls#_onCanPlayThroughHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onCanPlayThroughHandler = function(event) +{ + var element = this._video.element; + this.log("onCanPlayThrough [readyState: " + element.readyState + "]"); + + this._canPlay = true; + + if (this._onCanPlayThrough !== null) + { + this._onCanPlayThrough.dispatch(event); + } +}; + +/** + * Private event handler for play. + * @method FORGE.VideoHls#_onPlayHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onPlayHandler = function(event) +{ + var element = this._video.element; + this.log("onPlay [readyState: " + element.readyState + "]"); + + if (this._onPlay !== null) + { + this._onPlay.dispatch(event); + } +}; + +/** + * Private event handler for pause. + * @method FORGE.VideoHls#_onPauseHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onPauseHandler = function(event) +{ + var element = this._video.element; + this.log("onPause [readyState: " + element.readyState + "]"); + + this._playing = false; + + if (this._onPause !== null) + { + this._onPause.dispatch(event); + } +}; + +/** + * Private event handler for timeUpdate. + * @method FORGE.VideoHls#_onTimeUpdateHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onTimeUpdateHandler = function(event) +{ + //var element = this._video.element; + //this.log("onTimeUpdate [readyState: "+element.readyState+"]"); + + if (this._onTimeUpdate !== null) + { + this._onTimeUpdate.dispatch(event); + } +}; + +/** + * Private event handler for volumeChange. + * @method FORGE.VideoHls#_onVolumeChangeHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onVolumeChangeHandler = function(event) +{ + var element = this._video.element; + this.log("onVolumeChange [readyState: " + element.readyState + "]"); + + //I do not dispatch the volume change if readyState is HAVE_NOTHING (0). + //because I set the volume at 0 when I create the video element, it is not usefull to dispatch this internal volume change ? + if (this._onVolumeChange !== null && element.readyState !== HTMLMediaElement.HAVE_NOTHING) + { + this._onVolumeChange.dispatch(event); + } +}; + +/** + * Private event handler for seeking. + * @method FORGE.VideoHls#_onSeekingHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onSeekingHandler = function(event) +{ + var element = this._video.element; + this.log("onSeeking [readyState: " + element.readyState + "]"); + + this._canPlay = false; + + if (this._onSeeking !== null) + { + this._onSeeking.dispatch(event); + } +}; + +/** + * Private event handler for seeked. + * @method FORGE.VideoHls#_onSeekedHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onSeekedHandler = function(event) +{ + var element = this._video.element; + this.log("onSeeked [readyState: " + element.readyState + "]"); + + this._canPlay = false; + + if (this._onSeeked !== null) + { + this._onSeeked.dispatch(event); + } +}; + +/** + * Private event handler for ended. + * @method FORGE.VideoHls#_onEndedHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onEndedHandler = function(event) +{ + var element = this._video.element; + this.log("onEnded [readyState: " + element.readyState + "]"); + + this._playing = false; + //this._dom.currentTime = 0; + this._endCount++; + + if (this._loop === true) + { + this.play(); + } + + if (this._onEnded !== null) + { + this._onEnded.dispatch(event); + } +}; + +/** + * Private event handler for error. + * @method FORGE.VideoHls#_onErrorHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onErrorHandler = function(event) +{ + var element = this._video.element; + this.log("onError [readyState: " + element.readyState + "]"); + + if (this._onError !== null) + { + this._onError.dispatch(event); + } +}; + +/** + * Private event handler for stalled. + * @method FORGE.VideoHls#_onStalledHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onStalledHandler = function(event) +{ + var element = this._video.element; + this.log("onStalled [readyState: " + element.readyState + "]"); + + if (this._onStalled !== null) + { + this._onStalled.dispatch(event); + } +}; + +/** + * Private event handler for rate change. + * @method FORGE.VideoHls#_onRateChangeHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onRateChangeHandler = function(event) +{ + var element = this._video.element; + this.log("onRateChange [readyState: " + element.readyState + "]"); + + if (this._onRateChange !== null) + { + this._onRateChange.dispatch(event); + } +}; + +/** + * Private event handler for playing. + * @method FORGE.VideoHls#_onPlayingHandler + * @private + * @param {Event} event - The native video event. + */ +FORGE.VideoHls.prototype._onPlayingHandler = function(event) +{ + var element = this._video.element; + this.log("onPlaying [readyState: " + element.readyState + "]"); + + if (this._onPlaying !== null) + { + this._onPlaying.dispatch(event); + } +}; + +/** + * Destroy a video object at a specified index, wiil look at the video object into _videos array then detoy it. + * @method FORGE.VideoHls#_destroyVideo + * @private + */ +FORGE.VideoHls.prototype._destroyVideo = function() +{ + this.log("_destroyVideo"); + + if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + { + this._uninstallEvents(); + + this._hlsMediaPlayer.pause(); + this._hlsMediaPlayer.reset(); + } + + var video = this._video; + var element = video.element; + + if (typeof element !== "undefined" && element !== null) + { + if (element.parentNode === this._dom) + { + this._dom.removeChild(element); + } + } + + element = null; + video.element = null; + + if (video.buffer !== null) + { + video.buffer.destroy(); + video.buffer = null; + } + + if (video.played !== null) + { + video.played.destroy(); + video.played = null; + } + + video = null; +}; + +/** + * Handles the disable status of the sound manager. + * @method FORGE.VideoHls#_disableSoundHandler + * @private + */ +FORGE.VideoHls.prototype._disableSoundHandler = function() +{ + var v = this._video; + + if (v !== null && v.element !== null && this._viewer.audio.enabled === false) + { + this._hlsMediaPlayer.setVolume(0); + } +}; + +/** + * Handles the main volume change, update the volume factor to the video volume. + * @method FORGE.VideoHls#_mainVolumeChangeHandler + * @private + */ +FORGE.VideoHls.prototype._mainVolumeChangeHandler = function() +{ + this._updateVolume(); +}; + +/** + * Apply the main volume factor to the video volume. + * @method FORGE.VideoHls#_updateVolume + * @private + */ +FORGE.VideoHls.prototype._updateVolume = function() +{ + var v = this._video; + + if (v !== null && v.element !== null && this._viewer.audio.enabled === true) + { + this._hlsMediaPlayer.setVolume(this._volume * this._viewer.audio.volume); + if (this._muted === true) + { + this._hlsMediaPlayer.setMute(true); + } + else + { + this._hlsMediaPlayer.setMute(false); + } + } +}; + +/** + * Apply the requested quality index. + * @method FORGE.VideoHls#_setRequestQuality + * @param {number} index - The quality index. + * @private + */ +FORGE.VideoHls.prototype._setRequestQuality = function(index) +{ + this._currentVideoPendingIndex = index; + + if (this._streamInfo !== null && this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true && this._hlsMetrics !== null) + { + var streamIndex = this._streamInfo.index; + var maxVideoIndex = this._hlsMetrics.getMaxIndexForBufferType(FORGE.VideoHls.mediaType.VIDEO, streamIndex); + var maxAudioIndex = this._hlsMetrics.getMaxIndexForBufferType(FORGE.VideoHls.mediaType.AUDIO, streamIndex); + + var newVideoIndex = index, + newAudioIndex = index; + + // zero based indexes + if (newVideoIndex >= maxVideoIndex) + { + newVideoIndex = maxVideoIndex - 1; + } + if (newVideoIndex < 0) + { + newVideoIndex = 0; + } + if (newAudioIndex >= maxAudioIndex) + { + newAudioIndex = maxAudioIndex - 1; + } + if (newAudioIndex < 0) + { + newAudioIndex = 0; + } + + this._hlsMediaPlayer.setQualityFor(FORGE.VideoHls.mediaType.VIDEO, newVideoIndex); + this._hlsMediaPlayer.setQualityFor(FORGE.VideoHls.mediaType.AUDIO, newAudioIndex); + } + + // Update the volume for the requested video + this._updateVolume(); +}; + +/** + * Sets the quality mode.<br> + * This activate or deactivate the adaptative bitrate switching for video and audio (ABR). + * @method FORGE.VideoHls#_setQualityMode + * @private + * @param {string} mode - Quality mode to be set. + */ +FORGE.VideoHls.prototype._setQualityMode = function(mode) +{ + if (this._qualityMode === mode) + { + return; + } + + if (mode === FORGE.VideoQualityMode.AUTO || mode === FORGE.VideoQualityMode.MANUAL) + { + this._qualityMode = mode; + + // if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + // { + // if (mode === FORGE.VideoQualityMode.MANUAL) + // { + // this._hlsMediaPlayer.setAutoSwitchQualityFor(FORGE.VideoHls.mediaType.VIDEO, false); + // this._hlsMediaPlayer.setAutoSwitchQualityFor(FORGE.VideoHls.mediaType.AUDIO, false); + // } + // else + // { + // this._hlsMediaPlayer.setAutoSwitchQualityFor(FORGE.VideoHls.mediaType.VIDEO, true); + // this._hlsMediaPlayer.setAutoSwitchQualityFor(FORGE.VideoHls.mediaType.AUDIO, true); + // } + // } + + if (this._onQualityModeChange !== null) + { + this._onQualityModeChange.dispatch(this._qualityMode); + } + } +}; + +/** + * Load a config or a video url to the source. + * @method FORGE.VideoHls#load + * @param {?(string|FORGE.VideoQuality|Array<(string|FORGE.VideoQuality)>)} config - The {@link FORGE.VideoQuality} or the url string to load. + */ +FORGE.VideoHls.prototype.load = function(config) +{ + //parse the config in parameters + this._parseConfig(config); + + if (this._manifestUrl === "") + { + throw "FORGE.VideoHls : Can't create video with no manifest!"; + } + + //Create place holders for video and video element + this._createVideoObject(); + this._createVideoTag(); + + this._initHlsMediaPlayer(); +}; + +/** + * Plays the video. + * @method FORGE.VideoHls#play + * @param {number=} time - Current video time to start playback. + * @param {boolean=} loop - Media must be looped? + */ +FORGE.VideoHls.prototype.play = function(time, loop) +{ + FORGE.VideoBase.prototype.play.call(this, time, loop); + + if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + { + this._hlsMediaPlayer.play(); + this._playing = true; + this._paused = false; + this._playCount++; + } +}; + +/** + * Pauses the video. + * @method FORGE.VideoHls#pause + */ +FORGE.VideoHls.prototype.pause = function() +{ + if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + { + this._hlsMediaPlayer.pause(); + this._playing = false; + this._paused = true; + } +}; + +/** + * Stop the video the video (pause it and set time to 0). + * @method FORGE.VideoHls#stop + */ +FORGE.VideoHls.prototype.stop = function() +{ + if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + { + this._hlsMediaPlayer.pause(); + this._hlsMediaPlayer.seek(0); + this._video.element.currentTime = 0; + this._playing = false; + this._paused = true; + } +}; + +/** + * Toggles the playback status, if play toggle to pause and vice versa. + * @method FORGE.VideoHls#togglePlayback + */ +FORGE.VideoHls.prototype.togglePlayback = function() +{ + if (this._playing === true || this._viewer.audio.enabled === false) + { + this.pause(); + } + else + { + this.play(); + } +}; + +/** + * Mute the video sound. + * @method FORGE.VideoHls#mute + */ +FORGE.VideoHls.prototype.mute = function() +{ + if (this._muted === true || this._viewer.audio.enabled === false) + { + return; + } + + this._muted = true; + this._mutedVolume = this._volume; + + this._volume = 0; + this._updateVolume(); + + if (this._onMute !== null) + { + this._onMute.dispatch(); + } +}; + +/** + * Unmute the video sound. + * @method FORGE.VideoHls#unmute + * @param {number=} volume - The volume to be restored on unmute. + */ +FORGE.VideoHls.prototype.unmute = function(volume) +{ + if (this._muted === false) + { + return; + } + + var v = (typeof volume === "number") ? volume : this._mutedVolume; + + this._muted = false; + this._volume = FORGE.Math.clamp(v, 0, 1); + this._updateVolume(); + + if (this._onUnmute !== null) + { + this._onUnmute.dispatch(); + } +}; + +/** + * Enable/Disable the buffer-occupancy-based (BOLA) ABR rule set.<br> + * BOLA white paper: http://arxiv.org/abs/1601.06748. + * @method FORGE.VideoHls#enableBufferOccupancyABR + * @param {boolean} bool - Is the BOLA rule set is activated? + */ +FORGE.VideoHls.prototype.enableBufferOccupancyABR = function(bool) +{ + if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + { + this._hlsMediaPlayer.enableBufferOccupancyABR(bool); + } +}; + +/** + * Destroy method. + * @method FORGE.VideoHls#destroy + */ +FORGE.VideoHls.prototype.destroy = function() +{ + this._destroyVideo(); + + if (this._onLoadStart !== null) + { + this._onLoadStart.destroy(); + this._onLoadStart = null; + } + + if (this._onLoadedMetaData !== null) + { + this._onLoadedMetaData.destroy(); + this._onLoadedMetaData = null; + } + + if (this._onLoadedData !== null) + { + this._onLoadedData.destroy(); + this._onLoadedData = null; + } + + if (this._onProgress !== null) + { + this._onProgress.destroy(); + this._onProgress = null; + } + + if (this._onDurationChange !== null) + { + this._onDurationChange.destroy(); + this._onDurationChange = null; + } + + if (this._onCanPlay !== null) + { + this._onCanPlay.destroy(); + this._onCanPlay = null; + } + + if (this._onCanPlayThrough !== null) + { + this._onCanPlayThrough.destroy(); + this._onCanPlayThrough = null; + } + + if (this._onPlay !== null) + { + this._onPlay.destroy(); + this._onPlay = null; + } + + if (this._onPause !== null) + { + this._onPause.destroy(); + this._onPause = null; + } + + if (this._onTimeUpdate !== null) + { + this._onTimeUpdate.destroy(); + this._onTimeUpdate = null; + } + + if (this._onCurrentTimeChange !== null) + { + this._onCurrentTimeChange.destroy(); + this._onCurrentTimeChange = null; + } + + if (this._onVolumeChange !== null) + { + this._onVolumeChange.destroy(); + this._onVolumeChange = null; + } + + if (this._onSeeking !== null) + { + this._onSeeking.destroy(); + this._onSeeking = null; + } + + if (this._onSeeked !== null) + { + this._onSeeked.destroy(); + this._onSeeked = null; + } + + if (this._onEnded !== null) + { + this._onEnded.destroy(); + this._onEnded = null; + } + + if (this._onError !== null) + { + this._onError.destroy(); + this._onError = null; + } + + if (this._onStalled !== null) + { + this._onStalled.destroy(); + this._onStalled = null; + } + + if (this._onRateChange !== null) + { + this._onRateChange.destroy(); + this._onRateChange = null; + } + + if (this._onPlaying !== null) + { + this._onPlaying.destroy(); + this._onPlaying = null; + } + + if (this._onQualityRequest !== null) + { + this._onQualityRequest.destroy(); + this._onQualityRequest = null; + } + + if (this._onQualityChange !== null) + { + this._onQualityChange.destroy(); + this._onQualityChange = null; + } + + if (this._onQualityAbort !== null) + { + this._onQualityAbort.destroy(); + this._onQualityAbort = null; + } + + if (this._onQualitiesLoaded !== null) + { + this._onQualitiesLoaded.destroy(); + this._onQualitiesLoaded = null; + } + + if (this._onQualityModeChange !== null) + { + this._onQualityModeChange.destroy(); + this._onQualityModeChange = null; + } + + if (this._onMetricsChanged !== null) + { + this._onMetricsChanged.destroy(); + this._onMetricsChanged = null; + } + + this._onLoadStartBind = null; + this._onLoadedMetaDataBind = null; + this._onLoadedDataBind = null; + this._onProgressBind = null; + this._onDurationChangeBind = null; + this._onCanPlayBind = null; + this._onCanPlayThroughBind = null; + this._onPlayBind = null; + this._onPauseBind = null; + this._onTimeUpdateBind = null; + this._onVolumeChangeBind = null; + this._onSeekingBind = null; + this._onSeekedBind = null; + this._onEndedBind = null; + this._onErrorBind = null; + this._onPlayingBind = null; + this._onStalledBind = null; + this._onRateChangeBind = null; + this._onQualityRequestBind = null; + this._onQualityChangeBind = null; + //this._onQualityAbortBind = null; + this._onMetricsChangedBind = null; + + //Unbind main volume event + this._viewer.audio.onVolumeChange.remove(this._mainVolumeChangeHandler, this); + + this._viewer.audio.onDisable.remove(this._disableSoundHandler, this); + + this._hlsMediaPlayer = null; + this._playerVideoMetrics = null; + this._playerAudioMetrics = null; + this._hlsMetrics = null; + + this._monitoring = null; + this._streamInfo = null; + + this._config = null; + + this._qualities = null; + + this._video = null; + + FORGE.VideoBase.prototype.destroy.call(this); +}; + +/** + * Get the monitoring object related to the video. + * @name FORGE.VideoHls#monitoring + * @type {Object} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "monitoring", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._monitoring; + } +}); + +/** + * Get and set the quality index of the video. + * @name FORGE.VideoHls#quality + * @type {(number|FORGE.VideoQuality)} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "quality", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._qualities[this._currentVideoIndex]; + }, + + /** @this {FORGE.VideoHls} */ + set: function(value) + { + if (typeof value === "number" && value >= 0 && value < this._qualities.length) + { + this._setQualityMode(FORGE.VideoQualityMode.MANUAL); + this._setRequestQuality(value); + } + else if (FORGE.Utils.isTypeOf(value, "VideoQuality") === true) + { + var i = this._indexOfQuality(value); + + if (i !== -1) + { + this._setQualityMode(FORGE.VideoQualityMode.MANUAL); + this._setRequestQuality(i); + } + else + { + throw "Unknown quality"; + } + } + else + { + throw "Video quality " + value + " out of bounds"; + } + } +}); + +/** + * Get and set the quality mode.<br> + * Available quality mode are listed in FORGE.VideoQualityMode const. + * @name FORGE.VideoHls#qualityMode + * @type {string} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "qualityMode", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._qualityMode; + }, + + /** @this {FORGE.VideoHls} */ + set: function(value) + { + if (value === FORGE.VideoQualityMode.AUTO || value === FORGE.VideoQualityMode.MANUAL) + { + this._setQualityMode(value); + } + } +}); + +/** + * Get the quality array. + * @name FORGE.VideoHls#qualities + * @readonly + * @type {Array<FORGE.VideoQuality>} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "qualities", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._qualities; + } +}); + +/** + * Get the requested quality index, returns -1 if no request is being processed. + * @name FORGE.VideoHls#requestIndex + * @readonly + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "requestIndex", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._currentVideoPendingIndex; + } +}); + +/** + * Get the current quality index, returns -1 if no current is playing. + * @name FORGE.VideoHls#currentIndex + * @readonly + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "currentIndex", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._currentVideoIndex; + } +}); + +/** + * Get the video object array. + * @name FORGE.VideoHls#video + * @readonly + * @type {Object} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "video", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._video; + } +}); + +/** + * Get the html element of the current video. + * @name FORGE.VideoHls#element + * @readonly + * @type {?HTMLVideoElement} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "element", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + var video = this._video; + + if (video !== null && video.element !== null) + { + return video.element; + } + + return null; + } +}); + +/** + * Get the {@link FORGE.VideoTimeRanges} of the video for buffered ranges. + * @name FORGE.VideoHls#buffer + * @readonly + * @type {?FORGE.VideoTimeRanges} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "buffer", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + var video = this._video; + + if (video !== null && video.buffer !== null) + { + return video.buffer; + } + + return null; + } +}); + +/** + * Get the {@link FORGE.VideoTimeRanges} of the video for played ranges. + * @name FORGE.VideoHls#played + * @readonly + * @type {?FORGE.VideoTimeRanges} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "played", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + var video = this._video; + + if (video !== null && video.played !== null) + { + return video.played; + } + + return null; + } +}); + +/** + * Get the original width of the video source. + * @name FORGE.VideoHls#originalWidth + * @readonly + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "originalWidth", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._getCurrentVideoElementProperty("videoWidth", 0); + } +}); + +/** + * Get the original height of the video source. + * @name FORGE.VideoHls#originalHeight + * @readonly + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "originalHeight", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._getCurrentVideoElementProperty("videoHeight", 0); + } +}); + +/** + * Get and set the currentTime of the video. + * @name FORGE.VideoHls#currentTime + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "currentTime", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._hlsMediaPlayer.time(); + }, + + /** @this {FORGE.VideoHls} */ + set: function(value) + { + if (typeof value === "number") // && value < this.duration) //@todo see if we can put video currentTime in pending if no metadata received ? + { + this._hlsMediaPlayer.seek(value); + + if (this._onCurrentTimeChange !== null) + { + this._onCurrentTimeChange.dispatch(value); + } + } + } +}); + +/** + * Get and set the currentTime of the video in milliseconds. + * @name FORGE.VideoHls#currentTimeMS + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "currentTimeMS", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this.currentTime * 1000; + }, + + /** @this {FORGE.VideoHls} */ + set: function(value) + { + this.currentTime = value / 1000; + } +}); + +/** + * Get the remainingTime of the video. + * @name FORGE.VideoHls#remainingTime + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "remainingTime", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this.duration - this.currentTime; + } +}); + +/** + * Get the duration of the video in seconds. + * @name FORGE.VideoHls#duration + * @readonly + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "duration", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._hlsMediaPlayer.duration(); + } +}); + +/** + * Get the duration of the video in milli seconds. + * @name FORGE.VideoHls#durationMS + * @readonly + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "durationMS", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return Math.round(this.duration * 1000); + } +}); + +/** + * Get the metaDataLoaded status of the video. + * @name FORGE.VideoHls#metaDataLoaded + * @readonly + * @type {boolean} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "metaDataLoaded", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._metaDataLoaded; + } +}); + +/** + * Get and set the loop status of the video. + * @name FORGE.VideoHls#loop + * @type {boolean} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "loop", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._loop; + }, + + /** @this {FORGE.VideoHls} */ + set: function(value) + { + if (typeof value === "boolean") + { + this._loop = value; + } + } +}); + +/** + * Get and set the volume of the video. + * Set a volume unmute the video + * @name FORGE.VideoHls#volume + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "volume", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._volume; + }, + + /** @this {FORGE.VideoHls} */ + set: function(value) + { + if (typeof value === "number") + { + this._volume = FORGE.Math.clamp(value, 0, 1); + this._muted = false; + this._updateVolume(); + } + } +}); + +/** + * Get and set the mute status of the video. + * @name FORGE.VideoHls#muted + * @type {boolean} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "muted", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._muted; + }, + + /** @this {FORGE.VideoHls} */ + set: function(value) + { + if (Boolean(value) === true) + { + this.mute(); + } + else + { + this.unmute(); + } + } +}); + +/** + * Get and set the playback rate of the video. + * @name FORGE.VideoHls#playbackRate + * @type {number} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "playbackRate", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this._playbackRate; + }, + + /** @this {FORGE.VideoHls} */ + set: function(value) + { + if(typeof value === "number") + { + this._playbackRate = Math.abs(value); + + if (this._video !== null && this._video.element !== null) + { + this._video.element.playbackRate = this._playbackRate; + } + } + } +}); + +/** + * Get the "onLoadStart" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onLoadStart + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onLoadStart", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onLoadStart === null) + { + this._onLoadStart = new FORGE.EventDispatcher(this); + } + + return this._onLoadStart; + } +}); + +/** + * Get the "onLoadedMetaData" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onLoadedMetaData + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onLoadedMetaData", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onLoadedMetaData === null) + { + this._onLoadedMetaData = new FORGE.EventDispatcher(this); + } + + return this._onLoadedMetaData; + } +}); + +/** + * Get the "onLoadedData" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onLoadedData + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onLoadedData", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onLoadedData === null) + { + this._onLoadedData = new FORGE.EventDispatcher(this); + } + + return this._onLoadedData; + } +}); + +/** + * Get the "onProgress" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onProgress + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onProgress", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onProgress === null) + { + this._onProgress = new FORGE.EventDispatcher(this); + } + + return this._onProgress; + } +}); + +/** + * Get the "onDurationChange" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onDurationChange + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onDurationChange", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onDurationChange === null) + { + this._onDurationChange = new FORGE.EventDispatcher(this); + } + + return this._onDurationChange; + } +}); + +/** + * Get the "onCanPlay" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onCanPlay + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onCanPlay", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onCanPlay === null) + { + this._onCanPlay = new FORGE.EventDispatcher(this); + } + + return this._onCanPlay; + } +}); + +/** + * Get the "onCanPlayThrough" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onCanPlayThrough + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onCanPlayThrough", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onCanPlayThrough === null) + { + this._onCanPlayThrough = new FORGE.EventDispatcher(this); + } + + return this._onCanPlayThrough; + } +}); + +/** + * Get the "onPlay" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onPlay + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onPlay", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onPlay === null) + { + this._onPlay = new FORGE.EventDispatcher(this); + } + + return this._onPlay; + } +}); + +/** + * Get the "onPause" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onPause + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onPause", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onPause === null) + { + this._onPause = new FORGE.EventDispatcher(this); + } + + return this._onPause; + } +}); + +/** + * Get the "onTimeUpdate" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onTimeUpdate + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onTimeUpdate", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onTimeUpdate === null) + { + this._onTimeUpdate = new FORGE.EventDispatcher(this); + } + + return this._onTimeUpdate; + } +}); + +/** + * Get the "onCurrentTimeChange" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onCurrentTimeChange + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onCurrentTimeChange", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onCurrentTimeChange === null) + { + this._onCurrentTimeChange = new FORGE.EventDispatcher(this); + } + + return this._onCurrentTimeChange; + } +}); + +/** + * Get the "onVolumeChange" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onVolumeChange + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onVolumeChange", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onVolumeChange === null) + { + this._onVolumeChange = new FORGE.EventDispatcher(this); + } + + return this._onVolumeChange; + } +}); + +/** + * Get the "onSeeking" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onSeeking + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onSeeking", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onSeeking === null) + { + this._onSeeking = new FORGE.EventDispatcher(this); + } + + return this._onSeeking; + } +}); + +/** + * Get the "onSeeked" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onSeeked + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onSeeked", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onSeeked === null) + { + this._onSeeked = new FORGE.EventDispatcher(this); + } + + return this._onSeeked; + } +}); + +/** + * Get the "onEnded" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onEnded + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onEnded", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onEnded === null) + { + this._onEnded = new FORGE.EventDispatcher(this); + } + + return this._onEnded; + } +}); + +/** + * Get the "onError" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onError + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onError", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onError === null) + { + this._onError = new FORGE.EventDispatcher(this); + } + + return this._onError; + } +}); + +/** + * Get the "onStalled" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onStalled + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onStalled", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onStalled === null) + { + this._onStalled = new FORGE.EventDispatcher(this); + } + + return this._onStalled; + } +}); + +/** + * Get the "onRateChange" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onRateChange + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onRateChange", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onRateChange === null) + { + this._onRateChange = new FORGE.EventDispatcher(this); + } + + return this._onRateChange; + } +}); + +/** + * Get a copy of the "onStalled" event for the "onWaiting" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onWaiting + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onWaiting", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + return this.onStalled; + } +}); + +/** + * Get the "onPlaying" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onPlaying + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onPlaying", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onPlaying === null) + { + this._onPlaying = new FORGE.EventDispatcher(this); + } + + return this._onPlaying; + } +}); + +/** + * Get the "onQualityRequest" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onQualityRequest + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onQualityRequest", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onQualityRequest === null) + { + this._onQualityRequest = new FORGE.EventDispatcher(this); + } + + return this._onQualityRequest; + } +}); + +/** + * Get the "onQualityChange" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onQualityChange + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onQualityChange", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onQualityChange === null) + { + this._onQualityChange = new FORGE.EventDispatcher(this); + } + + return this._onQualityChange; + } +}); + +/** + * Get the "onQualityAbort" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onQualityAbort + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onQualityAbort", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onQualityAbort === null) + { + this._onQualityAbort = new FORGE.EventDispatcher(this); + } + + return this._onQualityAbort; + } +}); + +/** + * Get the "onMetricsChanged" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onMetricChanged + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onMetricsChanged", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onMetricsChanged === null) + { + this._onMetricsChanged = new FORGE.EventDispatcher(this); + } + + return this._onMetricsChanged; + } +}); + +/** + * Get the "onQualitiesLoaded" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onQualitiesLoaded + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onQualitiesLoaded", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onQualitiesLoaded === null) + { + this._onQualitiesLoaded = new FORGE.EventDispatcher(this, true); + } + + return this._onQualitiesLoaded; + } +}); + +/** + * Get the "onQualityModeChange" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onQualityModeChange + * @readonly + * @type {FORGE.EventDispatcher} + */ +Object.defineProperty(FORGE.VideoHls.prototype, "onQualityModeChange", +{ + /** @this {FORGE.VideoHls} */ + get: function() + { + if (this._onQualityModeChange === null) + { + this._onQualityModeChange = new FORGE.EventDispatcher(this); + } + + return this._onQualityModeChange; + } +}); From ea5b8860fe49f9a5b29c28d79e81efeb4e660019 Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Fri, 1 Dec 2017 16:03:49 +0100 Subject: [PATCH 07/19] Patch media comment --- src/media/Media.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/media/Media.js b/src/media/Media.js index 964d0cec..48b8a6fc 100644 --- a/src/media/Media.js +++ b/src/media/Media.js @@ -342,7 +342,7 @@ FORGE.Media.prototype._onLoadedMetaDataHandler = function() /** * Method to dispatch the load complete event and set the media ready. - * @method FORGE.Media#_onLoadedMetaDataHandler + * @method FORGE.Media#_notifyLoadComplete */ FORGE.Media.prototype._notifyLoadComplete = function() { From 6327cab495c35bc7b465bdfdb796794eb118be8f Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Fri, 1 Dec 2017 16:04:30 +0100 Subject: [PATCH 08/19] VideoHls class update for HLS stream support in AUTO quality mode. --- src/display/video/VideoHls.js | 1629 +++++++++++++++------------------ 1 file changed, 731 insertions(+), 898 deletions(-) diff --git a/src/display/video/VideoHls.js b/src/display/video/VideoHls.js index c60561b1..6581425d 100644 --- a/src/display/video/VideoHls.js +++ b/src/display/video/VideoHls.js @@ -143,13 +143,21 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) */ this._hlsMediaPlayer = null; + /** + * Is the hls.js Media Player ready? + * @name FORGE.VideoHls#_isReady + * @type {Hls.MediaPlayer} + * @private + */ + this._isReady = false; + /** * The hls stream info object. * @name FORGE.VideoHls#_streamInfo * @type {StreamInfo} * @private */ - this._streamInfo = null; + // this._streamInfo = null; /** * The current index for video. @@ -157,7 +165,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {number} * @private */ - this._currentVideoIndex = 0; + // this._currentVideoIndex = 0; /** * The current pending index for video. @@ -165,7 +173,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {number} * @private */ - this._currentVideoPendingIndex = 0; + // this._currentVideoPendingIndex = 0; /** * The current index for audio. @@ -173,7 +181,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {number} * @private */ - this._currentAudioIndex = 0; + // this._currentAudioIndex = 0; /** * The current pending index for audio. @@ -181,7 +189,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {number} * @private */ - this._currentAudioPendingIndex = 0; + // this._currentAudioPendingIndex = 0; /** * The hls media player video metrics object. @@ -189,7 +197,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {Object} * @private */ - this._playerVideoMetrics = null; + // this._playerVideoMetrics = null; /** * The hls media player audio metrics object. @@ -197,7 +205,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {Object} * @private */ - this._playerAudioMetrics = null; + // this._playerAudioMetrics = null; /** * The hls stream metrics object. @@ -205,7 +213,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {hlsMetrics} * @private */ - this._hlsMetrics = null; + // this._hlsMetrics = null; /** * The monitoring object. @@ -213,7 +221,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {Object} * @private */ - this._monitoring = null; + // this._monitoring = null; /** * On load start event dispatcher. @@ -343,6 +351,14 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) */ this._onError = null; + /** + * On waiting event dispatcher. + * @name FORGE.VideoHTML5#_onWaiting + * @type {?FORGE.EventDispatcher} + * @private + */ + this._onWaiting = null; + /** * On stalled event dispatcher. * @name FORGE.VideoHls#_onStalled @@ -429,151 +445,13 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {?FORGE.EventDispatcher} * @private */ - this._onMetricsChanged = null; - - /** - * Event handler for current video load start binded to this. - * @name FORGE.VideoHls#_onLoadStartBind - * @type {Function} - * @private - */ - this._onLoadStartBind = null; - - /** - * Event handler for current video loaded meta data binded to this. - * @name FORGE.VideoHls#_onLoadedMetaDataBind - * @type {Function} - * @private - */ - this._onLoadedMetaDataBind = null; - - /** - * Event handler for current video loaded data binded to this. - * @name FORGE.VideoHls#_onLoadedDataBind - * @type {Function} - * @private - */ - this._onLoadedDataBind = null; - - /** - * Event handler for current video progress binded to this. - * @name FORGE.VideoHls#_onProgressBind - * @type {Function} - * @private - */ - this._onProgressBind = null; - - /** - * Event handler for current video duration change binded to this. - * @name FORGE.VideoHls#_onDurationChangeBind - * @type {Function} - * @private - */ - this._onDurationChangeBind = null; - - /** - * Event handler for current video can play binded to this. - * @name FORGE.VideoHls#_onCanPlayBind - * @type {Function} - * @private - */ - this._onCanPlayBind = null; - - /** - * Event handler for current video can play throught binded to this. - * @name FORGE.VideoHls#_onCanPlayThroughBind - * @type {Function} - * @private - */ - this._onCanPlayThroughBind = null; - - /** - * Event handler for current video play binded to this. - * @name FORGE.VideoHls#_onPlayBind - * @type {Function} - * @private - */ - this._onPlayBind = null; - - /** - * Event handler for current video pause binded to this. - * @name FORGE.VideoHls#_onPauseBind - * @type {Function} - * @private - */ - this._onPauseBind = null; - - /** - * Event handler for current video time update binded to this. - * @name FORGE.VideoHls#_onTimeUpdateBind - * @type {Function} - * @private - */ - this._onTimeUpdateBind = null; + // this._onMetricsChanged = null; - /** - * Event handler for current video volume change binded to this. - * @name FORGE.VideoHls#_onVolumeChangeBind - * @type {Function} - * @private - */ - this._onVolumeChangeBind = null; - - /** - * Event handler for current video seeking binded to this. - * @name FORGE.VideoHls#_onSeekingBind - * @type {Function} - * @private - */ - this._onSeekingBind = null; - - /** - * Event handler for current video seeked binded to this. - * @name FORGE.VideoHls#_onSeekedBind - * @type {Function} - * @private - */ - this._onSeekedBind = null; - /** - * Event handler for current video ended binded to this. - * @name FORGE.VideoHls#_onEndedBind - * @type {Function} - * @private - */ - this._onEndedBind = null; - /** - * Event handler for current video error binded to this. - * @name FORGE.VideoHls#_onErrorBind - * @type {Function} - * @private - */ - this._onErrorBind = null; - /** - * Event handler for current video stalled binded to this. - * @name FORGE.VideoHls#_onStalledBind - * @type {Function} - * @private - */ - this._onStalledBind = null; - /** - * Event handler for current video rate change binded to this. - * @name FORGE.VideoHls#_onRateChangeBind - * @type {Function} - * @private - */ - this._onRateChangeBind = null; - /** - * Event handler for current video playing binded to this. - * @name FORGE.VideoHls#_onPlayingBind - * @type {Function} - * @private - */ - this._onPlayingBind = null; /** * Event handler for current video quality request binded to this. @@ -613,7 +491,15 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {Function} * @private */ - this._onMetricsChangedBind = null; + // this._onMetricsChangedBind = null; + + /** + * Event handler for all events fired by the HTMLVideoElement. See https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events for a list of available events. + * @name FORGE.VideoHls#_onEventBind + * @type {Function} + * @private + */ + this._onEventBind = null; FORGE.VideoBase.call(this, viewer, "VideoHls"); }; @@ -667,32 +553,34 @@ FORGE.VideoHls.prototype._boot = function() this._register(); this._loadHlsMediaPlayerSourceBind = this._loadHlsMediaPlayerSource.bind(this); - - this._onLoadStartBind = this._onLoadStartHandler.bind(this); - this._onDurationChangeBind = this._onDurationChangeHandler.bind(this); - this._onLoadedMetaDataBind = this._onLoadedMetaDataHandler.bind(this); - this._onLoadedDataBind = this._onLoadedDataHandler.bind(this); - this._onProgressBind = this._onProgressHandler.bind(this); - this._onCanPlayBind = this._onCanPlayHandler.bind(this); - this._onCanPlayThroughBind = this._onCanPlayThroughHandler.bind(this); - this._onPlayBind = this._onPlayHandler.bind(this); - this._onPauseBind = this._onPauseHandler.bind(this); - this._onTimeUpdateBind = this._onTimeUpdateHandler.bind(this); - this._onVolumeChangeBind = this._onVolumeChangeHandler.bind(this); - this._onSeekingBind = this._onSeekingHandler.bind(this); - this._onSeekedBind = this._onSeekedHandler.bind(this); - this._onEndedBind = this._onEndedHandler.bind(this); - this._onErrorBind = this._onErrorHandler.bind(this); - this._onStalledBind = this._onStalledHandler.bind(this); - this._onRateChangeBind = this._onRateChangeHandler.bind(this); - this._onPlayingBind = this._onPlayingHandler.bind(this); - this._onQualityRequestBind = this._onQualityRequestHandler.bind(this); - this._onQualityChangeBind = this._onQualityChangeHandler.bind(this); - //this._onQualityAbortBind = this._onQualityAbortHandler.bind(this); + this._launchHlsMediaPlayerBind = this._launchHlsMediaPlayer.bind(this); + + this._onEventBind = this._onEventHandler.bind(this); + + // this._onLoadStartBind = this._onLoadStartHandler.bind(this); + // this._onDurationChangeBind = this._onDurationChangeHandler.bind(this); + // this._onLoadedMetaDataBind = this._onLoadedMetaDataHandler.bind(this); + // this._onLoadedDataBind = this._onLoadedDataHandler.bind(this); + // this._onProgressBind = this._onProgressHandler.bind(this); + // this._onCanPlayBind = this._onCanPlayHandler.bind(this); + // this._onCanPlayThroughBind = this._onCanPlayThroughHandler.bind(this); + // this._onPlayBind = this._onPlayHandler.bind(this); + // this._onPauseBind = this._onPauseHandler.bind(this); + // this._onTimeUpdateBind = this._onTimeUpdateHandler.bind(this); + // this._onVolumeChangeBind = this._onVolumeChangeHandler.bind(this); + // this._onSeekingBind = this._onSeekingHandler.bind(this); + // this._onSeekedBind = this._onSeekedHandler.bind(this); + // this._onErrorBind = this._onErrorHandler.bind(this); + // this._onStalledBind = this._onStalledHandler.bind(this); + // this._onRateChangeBind = this._onRateChangeHandler.bind(this); + // this._onPlayingBind = this._onPlayingHandler.bind(this); + // this._onQualityRequestBind = this._onQualityRequestHandler.bind(this); + // this._onQualityChangeBind = this._onQualityChangeHandler.bind(this); + // //this._onQualityAbortBind = this._onQualityAbortHandler.bind(this); // HLS specific - this._onSwitchCompletedBind = this._onSwitchCompletedHandler.bind(this); - this._onMetricsChangedBind = this._onMetricsChangedHandler.bind(this); + // this._onSwitchCompletedBind = this._onSwitchCompletedHandler.bind(this); + // this._onMetricsChangedBind = this._onMetricsChangedHandler.bind(this); //Listen to the main volume change to adapt the video volume accordingly. this._viewer.audio.onVolumeChange.add(this._mainVolumeChangeHandler, this); @@ -755,12 +643,12 @@ FORGE.VideoHls.prototype._parseConfig = function(config) */ FORGE.VideoHls.prototype._notifyResize = function(data) { - var video = this._video; + var v = this._video; - if (video !== null && video.element !== null) + if (v !== null && v.element !== null) { - video.element.setAttribute("width", this.pixelWidth); - video.element.setAttribute("height", this.pixelHeight); + v.element.setAttribute("width", this.pixelWidth); + v.element.setAttribute("height", this.pixelHeight); } FORGE.DisplayObject.prototype._notifyResize.call(this, data); @@ -774,16 +662,16 @@ FORGE.VideoHls.prototype._notifyResize = function(data) */ FORGE.VideoHls.prototype._createVideoObject = function() { - var video = { + var v = { index: 0, element: null, buffer: null, played: null }; - this._video = video; + this._video = v; - return video; + return v; }; /** @@ -808,13 +696,13 @@ FORGE.VideoHls.prototype._createVideoTag = function() var played = new FORGE.VideoTimeRanges(element, "played"); //Update the video object with the element and fresh buffer and played - var video = this._video; - video.element = element; - video.buffer = buffer; - video.played = played; - video.lastTimeStamp = 0; + var v = this._video; + v.element = element; + v.buffer = buffer; + v.played = played; + v.lastTimeStamp = 0; - return video; + return v; }; /** @@ -827,11 +715,11 @@ FORGE.VideoHls.prototype._createVideoTag = function() */ FORGE.VideoHls.prototype._getCurrentVideoElementProperty = function(property, defaultReturnValue) { - var video = this._video; + var v = this._video; - if (video !== null && video.element !== null) + if (v !== null && v.element !== null) { - return video.element[property]; + return v.element[property]; } return defaultReturnValue; @@ -845,7 +733,7 @@ FORGE.VideoHls.prototype._getCurrentVideoElementProperty = function(property, de FORGE.VideoHls.prototype._initHlsMediaPlayer = function() { var hlsConfig = { - autoStartLoad: false, // start after Hls.Events.MANIFEST_PARSED + autoStartLoad: true, // start after Hls.Events.MANIFEST_PARSED startPosition : -1, // startTime debug: true, startLevel: undefined, @@ -878,17 +766,26 @@ FORGE.VideoHls.prototype._initHlsMediaPlayer = function() */ FORGE.VideoHls.prototype._loadHlsMediaPlayerSource = function() { - console.log("video and hls.js are now bound together !"); + this.log("video and hls.js are now bound together !"); this._hlsMediaPlayer.loadSource(this._manifestUrl); - // this._hlsMediaPlayer.on(Hls.Events.MANIFEST_PARSED, function (event, data) { - // console.log("manifest loaded, found " + data.levels.length + " quality level"); - // }); + this._hlsMediaPlayer.on(Hls.Events.MANIFEST_PARSED, this._launchHlsMediaPlayerBind); this._installEvents(); this._addVideoToDom(); }; +/** + * Play video file once the manifest is loaded. + * @method FORGE.VideoHls#_launchHlsMediaPlayer + * @private + */ +FORGE.VideoHls.prototype._launchHlsMediaPlayer = function(event, data) +{ + this.log("manifest loaded, found " + data.levels.length + " quality level"); + this._isReady = true; +}; + /** * Add video element to the DOM. * @method FORGE.VideoHls#_addVideoToDom @@ -909,10 +806,6 @@ FORGE.VideoHls.prototype._addVideoToDom = function() */ FORGE.VideoHls.prototype._installEvents = function() { - this._hlsMediaPlayer.on(Hls.Events.MANIFEST_PARSED, function (event, data) { - console.log("manifest loaded, found " + data.levels.length + " quality level"); - }); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["CAN_PLAY"], this._onCanPlayBind); // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["ERROR"], this._onErrorBind); // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_ENDED"], this._onEndedBind); @@ -930,14 +823,38 @@ FORGE.VideoHls.prototype._installEvents = function() // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_PLAYING"], this._onPlayingBind); // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["BUFFER_EMPTY"], this._onStalledBind); // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_RATE_CHANGED"], this._onRateChangeBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PERIOD_SWITCH_COMPLETED"], this._onSwitchCompletedBind); // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["METRIC_CHANGED"], this._onMetricsChangedBind); - this._video.element.addEventListener("loadeddata", this._onLoadedDataBind, false); - this._video.element.addEventListener("durationchange", this._onDurationChangeBind, false); - this._video.element.addEventListener("canplaythrough", this._onCanPlayThroughBind, false); - this._video.element.addEventListener("volumechange", this._onVolumeChangeBind, false); + var element = this._video.element; + + element.addEventListener("loadstart", this._onEventBind, false); + element.addEventListener("durationchange", this._onEventBind, false); + element.addEventListener("loadedmetadata", this._onEventBind, false); + element.addEventListener("loadeddata", this._onEventBind, false); + element.addEventListener("progress", this._onEventBind, false); + element.addEventListener("canplay", this._onEventBind, false); + element.addEventListener("canplaythrough", this._onEventBind, false); + element.addEventListener("play", this._onEventBind, false); + element.addEventListener("pause", this._onEventBind, false); + element.addEventListener("timeupdate", this._onEventBind, false); + element.addEventListener("volumechange", this._onEventBind, false); + element.addEventListener("seeking", this._onEventBind, false); + element.addEventListener("seeked", this._onEventBind, false); + element.addEventListener("ended", this._onEventBind, false); + element.addEventListener("error", this._onEventBind, false); + element.addEventListener("waiting", this._onEventBind, false); + element.addEventListener("stalled", this._onEventBind, false); + element.addEventListener("playing", this._onEventBind, false); + element.addEventListener("ratechange", this._onEventBind, false); + + + + + // this._video.element.addEventListener("loadeddata", this._onLoadedDataBind, false); + // this._video.element.addEventListener("durationchange", this._onDurationChangeBind, false); + // this._video.element.addEventListener("canplaythrough", this._onCanPlayThroughBind, false); + // this._video.element.addEventListener("volumechange", this._onVolumeChangeBind, false); }; /** @@ -947,6 +864,28 @@ FORGE.VideoHls.prototype._installEvents = function() */ FORGE.VideoHls.prototype._uninstallEvents = function() { + var element = this._video.element; + + element.removeEventListener("loadstart", this._onEventBind, false); + element.removeEventListener("durationchange", this._onEventBind, false); + element.removeEventListener("loadedmetadata", this._onEventBind, false); + element.removeEventListener("loadeddata", this._onEventBind, false); + element.removeEventListener("progress", this._onEventBind, false); + element.removeEventListener("canplay", this._onEventBind, false); + element.removeEventListener("canplaythrough", this._onEventBind, false); + element.removeEventListener("play", this._onEventBind, false); + element.removeEventListener("pause", this._onEventBind, false); + element.removeEventListener("timeupdate", this._onEventBind, false); + element.removeEventListener("volumechange", this._onEventBind, false); + element.removeEventListener("seeking", this._onEventBind, false); + element.removeEventListener("seeked", this._onEventBind, false); + element.removeEventListener("ended", this._onEventBind, false); + element.removeEventListener("error", this._onEventBind, false); + element.removeEventListener("waiting", this._onEventBind, false); + element.removeEventListener("stalled", this._onEventBind, false); + element.removeEventListener("playing", this._onEventBind, false); + element.removeEventListener("ratechange", this._onEventBind, false); + // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["CAN_PLAY"], this._onCanPlayBind); // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["ERROR"], this._onErrorBind); // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_ENDED"], this._onEndedBind); @@ -964,681 +903,564 @@ FORGE.VideoHls.prototype._uninstallEvents = function() // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_PLAYING"], this._onPlayingBind); // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["BUFFER_EMPTY"], this._onStalledBind); // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_RATE_CHANGED"], this._onRateChangeBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PERIOD_SWITCH_COMPLETED"], this._onSwitchCompletedBind); // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["METRIC_CHANGED"], this._onMetricsChangedBind); - this._video.element.removeEventListener("loadeddata", this._onLoadedDataBind, false); - this._video.element.removeEventListener("durationchange", this._onDurationChangeBind, false); - this._video.element.removeEventListener("canplaythrough", this._onCanPlayThroughBind, false); - this._video.element.removeEventListener("volumechange", this._onVolumeChangeBind, false); + // this._video.element.removeEventListener("loadeddata", this._onLoadedDataBind, false); + // this._video.element.removeEventListener("durationchange", this._onDurationChangeBind, false); + // this._video.element.removeEventListener("canplaythrough", this._onCanPlayThroughBind, false); + // this._video.element.removeEventListener("volumechange", this._onVolumeChangeBind, false); }; /** - * Private event handler for loadStart. - * @method FORGE.VideoHls#_onLoadStartHandler - * @param {Event} event - The native video event. + * Global handler for all events fired by an HTMLVideoElement. + * @method FORGE.VideoHls#_onEventHandler + * @param {Event} event - the fired event * @private */ -FORGE.VideoHls.prototype._onLoadStartHandler = function(event) +FORGE.VideoHls.prototype._onEventHandler = function(event) { var element = this._video.element; - this.log("onLoadStart [readyState: " + element.readyState + "]"); + this.log(event.type + " [readyState: " + element.readyState + "]"); - //populate qualities array with the HLS bitrates info list - this._createQualitiesFromBitrateInfoList(this._manifestUrl, this._hlsMediaPlayer.getBitrateInfoListFor(FORGE.VideoHls.mediaType.VIDEO)); - - if (this._onLoadStart !== null) - { - this._onLoadStart.dispatch(event); - } -}; - -/** - * Create a qualities array from the bitrates info list. - * @method FORGE.VideoHls#_createQualitiesFromBitrateInfoList - * @param {string} url - The manifest url. - * @param {Array<BitrateInfo>} bitrates - The bitrates array. - * @param {boolean=} checkURL - URL must be checked? - * @return {Array<FORGE.VideoQuality>} The qualities array. - * @private - */ -FORGE.VideoHls.prototype._createQualitiesFromBitrateInfoList = function(url, bitrates, checkURL) -{ - var qualities = []; - var quality; - - if (bitrates !== null) + switch (event.type) { - for (var i = 0, ii = bitrates.length; i < ii; i++) - { - if (checkURL === true && FORGE.URL.isValid(url) === false) + case "loadstart": + if (this._onLoadStart !== null) { - throw "FORGE.Video: URL " + url + " is invalid"; + this._onLoadStart.dispatch(event); } - quality = new FORGE.VideoQuality(url); - quality.id = bitrates[i].qualityIndex; - quality.bitrate = bitrates[i].bitrate; - quality.width = bitrates[i].width; - quality.height = bitrates[i].height; + break; - qualities.push(quality); - } - - this._qualities = /** @type {Array<FORGE.VideoQuality>} */ (qualities); - - if (this._onQualitiesLoaded !== null) - { - this._onQualitiesLoaded.dispatch(qualities); - } - } - else - { - this.destroy(); - } - - return qualities; -}; - -/** - * Get the index of a {@link FORGE.VideoQuality} that is in the _videoQualities array. - * @method FORGE.VideoHls#_indexOfQuality - * @private - * @param {FORGE.VideoQuality} quality - The quality you need to get its index. - * @return {number} Returns the index of the quality if found, -1 if not found. - */ -FORGE.VideoHls.prototype._indexOfQuality = function(quality) -{ - var q; - for (var i = 0, ii = this._qualities.length; i < ii; i++) - { - q = this._qualities[i]; - - if (q === quality) - { - return i; - } - } - - return -1; -}; - -/** - * Private event handler for period switch completed. - * @method FORGE.VideoHls#_onSwitchCompletedHandler - * @param {SwitchEvents} event - The hls.js media player event. - * @private - */ -FORGE.VideoHls.prototype._onSwitchCompletedHandler = function(event) -{ - var element = this._video.element; - this.log("_onSwitchCompleted [readyState: " + element.readyState + "]"); - - this._streamInfo = /** @type {StreamInfo} */ (event.toStreamInfo); -}; - -/** - * Private event handler for mertics changed. - * @method FORGE.VideoHls#_onMetricsChangedHandler - * @param {MetricChangedEvents} event - The hls.js media player event. - * @private - */ -FORGE.VideoHls.prototype._onMetricsChangedHandler = function(event) -{ - var element = this._video.element; - this.log("_onMetricsChangedHandler [readyState: " + element.readyState + "]"); - - if (this._playerVideoMetrics === null) - { - this._playerVideoMetrics = this._hlsMediaPlayer.getMetricsFor(FORGE.VideoHls.mediaType.VIDEO); - } - - if (this._playerAudioMetrics === null) - { - this._playerAudioMetrics = this._hlsMediaPlayer.getMetricsFor(FORGE.VideoHls.mediaType.AUDIO); - } - - if (this._hlsMetrics === null) - { - this._hlsMetrics = this._hlsMediaPlayer.gethlsMetrics(); - } + case "durationchange": + //@firefox - FF dispatch durationchange twice on readystate HAVE_METADATA (1) & HAVE_ENOUGH_DATA (4) + //I will not dispatch this event if readystate is 4 ! + if (this._onDurationChange !== null && element.readyState === HTMLMediaElement.HAVE_METADATA) + { + this._onDurationChange.dispatch(event); + } - //set the current quality index - // if (this._playerVideoMetrics !== null && this._hlsMetrics !== null) - // { - // var repSwitch = /** @type {RepresentationSwitch} */ (this._hlsMetrics.getCurrentRepresentationSwitch(this._playerVideoMetrics)); - // if (repSwitch !== null) - // { - // this._currentQuality = this._hlsMetrics.getIndexForRepresentation(repSwitch.to, this._streamInfo.index); - // if(this._qualityInitialized === false) - // { - // this._setRequestQuality(this._currentQuality); - // this._qualityInitialized = true; - // } - // } - // } + break; - if (this._onMetricsChanged !== null) - { - var metrics; + case "loadedmetadata": + this._metaDataLoaded = true; - if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) - { - metrics = this._getMetricsFor(FORGE.VideoHls.mediaType.VIDEO, this._playerVideoMetrics, this._hlsMetrics); - if (metrics) + if (this._onLoadedMetaData !== null) { - this._monitoring = { - "videoBitrate": metrics.bitrate, - "videoIndex": metrics.index, - "videoPendingIndex": metrics.pendingIndex, - "videoMaxIndex": metrics.maxIndex, - "videoBufferLength": metrics.bufferLength, - "videoDroppedFrames": metrics.droppedFrames - //"videoRequestsQueue": metrics.requestsQueue - }; + this._onLoadedMetaData.dispatch(event); } - } - if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) - { - metrics = this._getMetricsFor(FORGE.VideoHls.mediaType.AUDIO, this._playerAudioMetrics, this._hlsMetrics); - if (metrics) + break; + + case "loadeddata": + if (this._onLoadedData !== null) { - this._monitoring = { - "audioBitrate": metrics.bitrate, - "audioIndex": metrics.index, - "audioPendingIndex": metrics.pendingIndex, - "audioMaxIndex": metrics.maxIndex, - "audioBufferLength": metrics.bufferLength, - "audioDroppedFrames": metrics.droppedFrames - //"audioRequestsQueue": metrics.requestsQueue - }; + this._onLoadedData.dispatch(event); } - } - - this._onMetricsChanged.dispatch(event); - } -}; - - -/** - * Prepare a metrics object for video/audio data. - * @method FORGE.VideoHls#_getMetricsFor - * @param {string} type - The video or audio type. - * @param {Object} metrics - The player video or audio metrics. - * @param {hlsMetrics} hlsMetrics - The hls stream video or audio metrics. - * @return {?Object} The monitoring object - * @private - */ -FORGE.VideoHls.prototype._getMetricsFor = function(type, metrics, hlsMetrics) -{ - if (metrics !== null && hlsMetrics !== null) - { - var streamIndex = this._streamInfo.index; - var repSwitch, maxIndex, bufferLevel, droppedFramesMetrics, bitrate, index, pendingIndex, bufferLength, droppedFrames; //httpRequests requestsQueue pendingValue - repSwitch = /** @type {RepresentationSwitch} */ (hlsMetrics.getCurrentRepresentationSwitch(metrics)); - if (repSwitch !== null) - { - // index = hlsMetrics.getIndexForRepresentation(repSwitch.to, streamIndex); - bitrate = Math.round(hlsMetrics.getBandwidthForRepresentation(repSwitch.to, streamIndex) / 1000); - } - if (isNaN(bitrate) || bitrate === undefined) - { - bitrate = 0; - } + break; - if (type === FORGE.VideoHls.mediaType.VIDEO) - { - index = this._currentVideoIndex + 1; - pendingIndex = this._currentVideoPendingIndex + 1; - } - else if (type === FORGE.VideoHls.mediaType.AUDIO) - { - index = this._currentAudioIndex + 1; - pendingIndex = this._currentAudioPendingIndex + 1; - } + case "progress": + if (this._onProgress !== null) + { + this._onProgress.dispatch(event); + } - if (isNaN(index) || index === undefined) - { - index = 0; - } - if (isNaN(pendingIndex) || pendingIndex === undefined) - { - pendingIndex = 0; - } + break; - maxIndex = hlsMetrics.getMaxIndexForBufferType(type, streamIndex); - if (isNaN(maxIndex) || maxIndex === undefined) - { - maxIndex = 0; - } + case "canplay": + this._canPlay = true; - bufferLevel = hlsMetrics.getCurrentBufferLevel(metrics); - if (bufferLevel !== null) - { - bufferLength = bufferLevel.toPrecision(5); - } - if (isNaN(bufferLength) || bufferLength === undefined) - { - bufferLength = 0; - } - - //httpRequests = hlsMetrics.getHttpRequests(metrics); + if (this._onCanPlay !== null) + { + this._onCanPlay.dispatch(event); + } - droppedFramesMetrics = /** @type {DroppedFrames} */ (hlsMetrics.getCurrentDroppedFrames(metrics)); - if (droppedFramesMetrics !== null) - { - droppedFrames = droppedFramesMetrics.droppedFrames; - } + break; - //pendingValue = this._hlsMediaPlayer.getQualityFor(type); + case "canplaythrough": + this._canPlay = true; - //requestsQueue = hlsMetrics.getRequestsQueue(metrics); + if (this._onCanPlayThrough !== null) + { + this._onCanPlayThrough.dispatch(event); + } - var result = { - bitrate: bitrate, - index: index, - pendingIndex: pendingIndex, - maxIndex: maxIndex, - bufferLength: bufferLength, - droppedFrames: droppedFrames - //requestsQueue: requestsQueue - }; + break; - return result; - } + case "play": + if (this._onPlay !== null) + { + this._onPlay.dispatch(event); + } - return null; -}; + break; -/** - * Private event handler for quality change. - * @method FORGE.VideoHls#_onQualityChangeHandler - * @private - * @param {QualityEvents} event - The hls.js media player event. - */ -FORGE.VideoHls.prototype._onQualityChangeHandler = function(event) -{ - var element = this._video.element; - this.log("onQualityChange [readyState: " + element.readyState + "]"); + case "pause": + this._playing = false; - if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) - { - this._currentAudioIndex = event.newQuality; - this._currentAudioPendingIndex = event.newQuality; - } - else if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) - { - this._currentVideoIndex = event.newQuality; - this._currentVideoPendingIndex = event.newQuality; + if (this._onPause !== null) + { + this._onPause.dispatch(event); + } - if (this._onQualityChange !== null) - { - this._onQualityChange.dispatch(this._currentVideoPendingIndex); - } - } -}; + break; -/** - * Private event handler for quality request. - * @method FORGE.VideoHls#_onQualityRequestHandler - * @private - * @param {QualityEvents} event - The hls.js media player event. - */ -FORGE.VideoHls.prototype._onQualityRequestHandler = function(event) -{ - var element = this._video.element; - this.log("onQualityRequest [readyState: " + element.readyState + "]"); + case "timeupdate": + if (this._onTimeUpdate !== null) + { + this._onTimeUpdate.dispatch(event); + } - if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) - { - this._currentAudioIndex = event.oldQuality; - this._currentAudioPendingIndex = event.newQuality; - } - else if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) - { - this._currentVideoIndex = event.oldQuality; - this._currentVideoPendingIndex = event.newQuality; + break; - if (this._onQualityRequest !== null) - { - this._onQualityRequest.dispatch(this._currentVideoPendingIndex); - } - } -}; + case "volumechange": + //I do not dispatch the volume change if readyState is HAVE_NOTHING (0). Because + //I set the volume at 0 when I create the video element, it is + //not usefull to dispatch this internal volume change ? + if (this._onVolumeChange !== null && element.readyState !== HTMLMediaElement.HAVE_NOTHING) + { + this._onVolumeChange.dispatch(event); + } -/** - * Private event handler for quality request aborted. - * @method FORGE.VideoHls#_onQualityAbortHandler - * @private - * @param {Event} event - The hls.js media player event. - */ -// FORGE.VideoHls.prototype._onQualityAbortHandler = function(event) -// { -// var element = this._video.element; -// this.log("onQualityAbort [readyState: "+element.readyState+"]"); + break; -// if(this._onQualityAbort !== null) -// { -// this._onQualityAbort.dispatch(this._video.requestIndex); -// } -// }; + case "seeking": + this._canPlay = false; -/** - * Private event handler for durationChange. - * @method FORGE.VideoHls#_onDurationChangeHandler - * @private - * @param {Event} event - The native video event. - */ -FORGE.VideoHls.prototype._onDurationChangeHandler = function(event) -{ - var element = this._video.element; - this.log("onDurationChange [readyState: " + element.readyState + "]"); + if (this._onSeeking !== null) + { + this._onSeeking.dispatch(event); + } - //@firefox - FF disptach durationchange twice on readystate HAVE_METADATA (1) & HAVE_ENOUGH_DATA (4) - //I will not dispatch this event if readystate is HAVE_ENOUGH_DATA (4) ! - if (this._onDurationChange !== null && element.readyState === HTMLMediaElement.HAVE_METADATA) - { - this._onDurationChange.dispatch(event); - } -}; + break; -/** - * Private event handler for loadedMetaData. - * @method FORGE.VideoHls#_onLoadedMetaDataHandler - * @private - * @param {Event} event - The native video event. - */ -FORGE.VideoHls.prototype._onLoadedMetaDataHandler = function(event) -{ - var element = this._video.element; - this.log("onLoadedMetaData [readyState: " + element.readyState + "]"); + case "seeked": + this._canPlay = false; - this._metaDataLoaded = true; + if (this._onSeeked !== null) + { + this._onSeeked.dispatch(event); + } - if (this._onLoadedMetaData !== null) - { - this._onLoadedMetaData.dispatch(event); - } -}; + break; -/** - * Private event handler for loadedData. - * @method FORGE.VideoHls#_onLoadedDataHandler - * @private - * @param {Event} event - The native video event. - */ -FORGE.VideoHls.prototype._onLoadedDataHandler = function(event) -{ - var element = this._video.element; - this.log("onLoadedData [readyState: " + element.readyState + "]"); + case "ended": + this._playing = false; + this.currentTime = 0; + this._endCount++; - if (this._onLoadedData !== null) - { - this._onLoadedData.dispatch(event); - } -}; + if (this._loop === true) + { + this.play(0); + } -/** - * Private event handler for progress. - * @method FORGE.VideoHls#_onProgressHandler - * @private - * @param {Event} event - The native video event. - */ -FORGE.VideoHls.prototype._onProgressHandler = function(event) -{ - //var element = this._video.element; - //this.log("onProgress [readyState: "+element.readyState+"]"); + if (this._onEnded !== null) + { + this._onEnded.dispatch(event); + } - if (this._onProgress !== null) - { - this._onProgress.dispatch(event); - } -}; + break; -/** - * Private event handler for canPlay. - * @method FORGE.VideoHls#_onCanPlayHandler - * @private - * @param {Event} event - The native video event. - */ -FORGE.VideoHls.prototype._onCanPlayHandler = function(event) -{ - var element = this._video.element; - this.log("onCanPlay [readyState: " + element.readyState + "]"); + case "error": + if (this._onError !== null) + { + this._onError.dispatch(event); + } - this._canPlay = true; + break; - if (this._onCanPlay !== null) - { - this._onCanPlay.dispatch(event); - } -}; + case "waiting": + if (this._onWaiting !== null) + { + this._onWaiting.dispatch(event); + } -/** - * Private event handler for canPlayThrough. - * @method FORGE.VideoHls#_onCanPlayThroughHandler - * @private - * @param {Event} event - The native video event. - */ -FORGE.VideoHls.prototype._onCanPlayThroughHandler = function(event) -{ - var element = this._video.element; - this.log("onCanPlayThrough [readyState: " + element.readyState + "]"); + break; - this._canPlay = true; + case "stalled": + if (this._onStalled !== null) + { + this._onStalled.dispatch(event); + } - if (this._onCanPlayThrough !== null) - { - this._onCanPlayThrough.dispatch(event); - } -}; + break; -/** - * Private event handler for play. - * @method FORGE.VideoHls#_onPlayHandler - * @private - * @param {Event} event - The native video event. - */ -FORGE.VideoHls.prototype._onPlayHandler = function(event) -{ - var element = this._video.element; - this.log("onPlay [readyState: " + element.readyState + "]"); + case "playing": + if (this._onPlaying !== null) + { + this._onPlaying.dispatch(event); + } - if (this._onPlay !== null) - { - this._onPlay.dispatch(event); - } -}; + break; -/** - * Private event handler for pause. - * @method FORGE.VideoHls#_onPauseHandler - * @private - * @param {Event} event - The native video event. - */ -FORGE.VideoHls.prototype._onPauseHandler = function(event) -{ - var element = this._video.element; - this.log("onPause [readyState: " + element.readyState + "]"); + case "ratechange": + if (this._onRateChange !== null) + { + this._onRateChange.dispatch(event); + } - this._playing = false; + break; - if (this._onPause !== null) - { - this._onPause.dispatch(event); + default: + this.warn("The event \"" + event.type + "\" is not handled."); + + break; } }; /** - * Private event handler for timeUpdate. - * @method FORGE.VideoHls#_onTimeUpdateHandler - * @private + * Private event handler for loadStart. + * @method FORGE.VideoHls#_onLoadStartHandler * @param {Event} event - The native video event. + * @private */ -FORGE.VideoHls.prototype._onTimeUpdateHandler = function(event) -{ - //var element = this._video.element; - //this.log("onTimeUpdate [readyState: "+element.readyState+"]"); +// FORGE.VideoHls.prototype._onLoadStartHandler = function(event) +// { +// var element = this._video.element; +// this.log("onLoadStart [readyState: " + element.readyState + "]"); - if (this._onTimeUpdate !== null) - { - this._onTimeUpdate.dispatch(event); - } -}; +// //populate qualities array with the HLS bitrates info list +// this._createQualitiesFromBitrateInfoList(this._manifestUrl, this._hlsMediaPlayer.getBitrateInfoListFor(FORGE.VideoHls.mediaType.VIDEO)); + +// if (this._onLoadStart !== null) +// { +// this._onLoadStart.dispatch(event); +// } +// }; /** - * Private event handler for volumeChange. - * @method FORGE.VideoHls#_onVolumeChangeHandler + * Create a qualities array from the bitrates info list. + * @method FORGE.VideoHls#_createQualitiesFromBitrateInfoList + * @param {string} url - The manifest url. + * @param {Array<BitrateInfo>} bitrates - The bitrates array. + * @param {boolean=} checkURL - URL must be checked? + * @return {Array<FORGE.VideoQuality>} The qualities array. * @private - * @param {Event} event - The native video event. */ -FORGE.VideoHls.prototype._onVolumeChangeHandler = function(event) -{ - var element = this._video.element; - this.log("onVolumeChange [readyState: " + element.readyState + "]"); +// FORGE.VideoHls.prototype._createQualitiesFromBitrateInfoList = function(url, bitrates, checkURL) +// { +// var qualities = []; +// var quality; - //I do not dispatch the volume change if readyState is HAVE_NOTHING (0). - //because I set the volume at 0 when I create the video element, it is not usefull to dispatch this internal volume change ? - if (this._onVolumeChange !== null && element.readyState !== HTMLMediaElement.HAVE_NOTHING) - { - this._onVolumeChange.dispatch(event); - } -}; +// if (bitrates !== null) +// { +// for (var i = 0, ii = bitrates.length; i < ii; i++) +// { +// if (checkURL === true && FORGE.URL.isValid(url) === false) +// { +// throw "FORGE.Video: URL " + url + " is invalid"; +// } + +// quality = new FORGE.VideoQuality(url); +// quality.id = bitrates[i].qualityIndex; +// quality.bitrate = bitrates[i].bitrate; +// quality.width = bitrates[i].width; +// quality.height = bitrates[i].height; + +// qualities.push(quality); +// } + +// this._qualities = /** @type {Array<FORGE.VideoQuality>} */ (qualities); + +// if (this._onQualitiesLoaded !== null) +// { +// this._onQualitiesLoaded.dispatch(qualities); +// } +// } +// else +// { +// this.destroy(); +// } + +// return qualities; +// }; /** - * Private event handler for seeking. - * @method FORGE.VideoHls#_onSeekingHandler + * Get the index of a {@link FORGE.VideoQuality} that is in the _videoQualities array. + * @method FORGE.VideoHls#_indexOfQuality * @private - * @param {Event} event - The native video event. + * @param {FORGE.VideoQuality} quality - The quality you need to get its index. + * @return {number} Returns the index of the quality if found, -1 if not found. */ -FORGE.VideoHls.prototype._onSeekingHandler = function(event) -{ - var element = this._video.element; - this.log("onSeeking [readyState: " + element.readyState + "]"); +// FORGE.VideoHls.prototype._indexOfQuality = function(quality) +// { +// var q; +// for (var i = 0, ii = this._qualities.length; i < ii; i++) +// { +// q = this._qualities[i]; - this._canPlay = false; +// if (q === quality) +// { +// return i; +// } +// } - if (this._onSeeking !== null) - { - this._onSeeking.dispatch(event); - } -}; +// return -1; +// }; /** - * Private event handler for seeked. - * @method FORGE.VideoHls#_onSeekedHandler + * Private event handler for period switch completed. + * @method FORGE.VideoHls#_onSwitchCompletedHandler + * @param {SwitchEvents} event - The hls.js media player event. * @private - * @param {Event} event - The native video event. */ -FORGE.VideoHls.prototype._onSeekedHandler = function(event) -{ - var element = this._video.element; - this.log("onSeeked [readyState: " + element.readyState + "]"); - - this._canPlay = false; +// FORGE.VideoHls.prototype._onSwitchCompletedHandler = function(event) +// { +// var element = this._video.element; +// this.log("_onSwitchCompleted [readyState: " + element.readyState + "]"); - if (this._onSeeked !== null) - { - this._onSeeked.dispatch(event); - } -}; +// this._streamInfo = /** @type {StreamInfo} */ (event.toStreamInfo); +// }; /** - * Private event handler for ended. - * @method FORGE.VideoHls#_onEndedHandler + * Private event handler for mertics changed. + * @method FORGE.VideoHls#_onMetricsChangedHandler + * @param {MetricChangedEvents} event - The hls.js media player event. * @private - * @param {Event} event - The native video event. */ -FORGE.VideoHls.prototype._onEndedHandler = function(event) -{ - var element = this._video.element; - this.log("onEnded [readyState: " + element.readyState + "]"); +// FORGE.VideoHls.prototype._onMetricsChangedHandler = function(event) +// { +// var element = this._video.element; +// this.log("_onMetricsChangedHandler [readyState: " + element.readyState + "]"); - this._playing = false; - //this._dom.currentTime = 0; - this._endCount++; +// if (this._playerVideoMetrics === null) +// { +// this._playerVideoMetrics = this._hlsMediaPlayer.getMetricsFor(FORGE.VideoHls.mediaType.VIDEO); +// } - if (this._loop === true) - { - this.play(); - } +// if (this._playerAudioMetrics === null) +// { +// this._playerAudioMetrics = this._hlsMediaPlayer.getMetricsFor(FORGE.VideoHls.mediaType.AUDIO); +// } + +// if (this._hlsMetrics === null) +// { +// this._hlsMetrics = this._hlsMediaPlayer.gethlsMetrics(); +// } + +// //set the current quality index +// // if (this._playerVideoMetrics !== null && this._hlsMetrics !== null) +// // { +// // var repSwitch = /** @type {RepresentationSwitch} */ (this._hlsMetrics.getCurrentRepresentationSwitch(this._playerVideoMetrics)); +// // if (repSwitch !== null) +// // { +// // this._currentQuality = this._hlsMetrics.getIndexForRepresentation(repSwitch.to, this._streamInfo.index); +// // if(this._qualityInitialized === false) +// // { +// // this._setRequestQuality(this._currentQuality); +// // this._qualityInitialized = true; +// // } +// // } +// // } + +// if (this._onMetricsChanged !== null) +// { +// var metrics; + +// if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) +// { +// metrics = this._getMetricsFor(FORGE.VideoHls.mediaType.VIDEO, this._playerVideoMetrics, this._hlsMetrics); +// if (metrics) +// { +// this._monitoring = { +// "videoBitrate": metrics.bitrate, +// "videoIndex": metrics.index, +// "videoPendingIndex": metrics.pendingIndex, +// "videoMaxIndex": metrics.maxIndex, +// "videoBufferLength": metrics.bufferLength, +// "videoDroppedFrames": metrics.droppedFrames +// //"videoRequestsQueue": metrics.requestsQueue +// }; +// } +// } + +// if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) +// { +// metrics = this._getMetricsFor(FORGE.VideoHls.mediaType.AUDIO, this._playerAudioMetrics, this._hlsMetrics); +// if (metrics) +// { +// this._monitoring = { +// "audioBitrate": metrics.bitrate, +// "audioIndex": metrics.index, +// "audioPendingIndex": metrics.pendingIndex, +// "audioMaxIndex": metrics.maxIndex, +// "audioBufferLength": metrics.bufferLength, +// "audioDroppedFrames": metrics.droppedFrames +// //"audioRequestsQueue": metrics.requestsQueue +// }; +// } +// } + +// this._onMetricsChanged.dispatch(event); +// } +// }; - if (this._onEnded !== null) - { - this._onEnded.dispatch(event); - } -}; /** - * Private event handler for error. - * @method FORGE.VideoHls#_onErrorHandler + * Prepare a metrics object for video/audio data. + * @method FORGE.VideoHls#_getMetricsFor + * @param {string} type - The video or audio type. + * @param {Object} metrics - The player video or audio metrics. + * @param {hlsMetrics} hlsMetrics - The hls stream video or audio metrics. + * @return {?Object} The monitoring object * @private - * @param {Event} event - The native video event. */ -FORGE.VideoHls.prototype._onErrorHandler = function(event) -{ - var element = this._video.element; - this.log("onError [readyState: " + element.readyState + "]"); +// FORGE.VideoHls.prototype._getMetricsFor = function(type, metrics, hlsMetrics) +// { +// if (metrics !== null && hlsMetrics !== null) +// { +// var streamIndex = this._streamInfo.index; +// var repSwitch, maxIndex, bufferLevel, droppedFramesMetrics, bitrate, index, pendingIndex, bufferLength, droppedFrames; //httpRequests requestsQueue pendingValue + +// repSwitch = /** @type {RepresentationSwitch} */ (hlsMetrics.getCurrentRepresentationSwitch(metrics)); +// if (repSwitch !== null) +// { +// // index = hlsMetrics.getIndexForRepresentation(repSwitch.to, streamIndex); +// bitrate = Math.round(hlsMetrics.getBandwidthForRepresentation(repSwitch.to, streamIndex) / 1000); +// } +// if (isNaN(bitrate) || bitrate === undefined) +// { +// bitrate = 0; +// } + +// if (type === FORGE.VideoHls.mediaType.VIDEO) +// { +// index = this._currentVideoIndex + 1; +// pendingIndex = this._currentVideoPendingIndex + 1; +// } +// else if (type === FORGE.VideoHls.mediaType.AUDIO) +// { +// index = this._currentAudioIndex + 1; +// pendingIndex = this._currentAudioPendingIndex + 1; +// } + +// if (isNaN(index) || index === undefined) +// { +// index = 0; +// } +// if (isNaN(pendingIndex) || pendingIndex === undefined) +// { +// pendingIndex = 0; +// } + +// maxIndex = hlsMetrics.getMaxIndexForBufferType(type, streamIndex); +// if (isNaN(maxIndex) || maxIndex === undefined) +// { +// maxIndex = 0; +// } + +// bufferLevel = hlsMetrics.getCurrentBufferLevel(metrics); +// if (bufferLevel !== null) +// { +// bufferLength = bufferLevel.toPrecision(5); +// } +// if (isNaN(bufferLength) || bufferLength === undefined) +// { +// bufferLength = 0; +// } + +// //httpRequests = hlsMetrics.getHttpRequests(metrics); + +// droppedFramesMetrics = /** @type {DroppedFrames} */ (hlsMetrics.getCurrentDroppedFrames(metrics)); +// if (droppedFramesMetrics !== null) +// { +// droppedFrames = droppedFramesMetrics.droppedFrames; +// } + +// //pendingValue = this._hlsMediaPlayer.getQualityFor(type); + +// //requestsQueue = hlsMetrics.getRequestsQueue(metrics); + +// var result = { +// bitrate: bitrate, +// index: index, +// pendingIndex: pendingIndex, +// maxIndex: maxIndex, +// bufferLength: bufferLength, +// droppedFrames: droppedFrames +// //requestsQueue: requestsQueue +// }; + +// return result; +// } - if (this._onError !== null) - { - this._onError.dispatch(event); - } -}; +// return null; +// }; /** - * Private event handler for stalled. - * @method FORGE.VideoHls#_onStalledHandler + * Private event handler for quality change. + * @method FORGE.VideoHls#_onQualityChangeHandler * @private - * @param {Event} event - The native video event. + * @param {QualityEvents} event - The hls.js media player event. */ -FORGE.VideoHls.prototype._onStalledHandler = function(event) -{ - var element = this._video.element; - this.log("onStalled [readyState: " + element.readyState + "]"); +// FORGE.VideoHls.prototype._onQualityChangeHandler = function(event) +// { +// var element = this._video.element; +// this.log("onQualityChange [readyState: " + element.readyState + "]"); - if (this._onStalled !== null) - { - this._onStalled.dispatch(event); - } -}; +// if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) +// { +// this._currentAudioIndex = event.newQuality; +// this._currentAudioPendingIndex = event.newQuality; +// } +// else if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) +// { +// this._currentVideoIndex = event.newQuality; +// this._currentVideoPendingIndex = event.newQuality; + +// if (this._onQualityChange !== null) +// { +// this._onQualityChange.dispatch(this._currentVideoPendingIndex); +// } +// } +// }; /** - * Private event handler for rate change. - * @method FORGE.VideoHls#_onRateChangeHandler + * Private event handler for quality request. + * @method FORGE.VideoHls#_onQualityRequestHandler * @private - * @param {Event} event - The native video event. + * @param {QualityEvents} event - The hls.js media player event. */ -FORGE.VideoHls.prototype._onRateChangeHandler = function(event) -{ - var element = this._video.element; - this.log("onRateChange [readyState: " + element.readyState + "]"); +// FORGE.VideoHls.prototype._onQualityRequestHandler = function(event) +// { +// var element = this._video.element; +// this.log("onQualityRequest [readyState: " + element.readyState + "]"); - if (this._onRateChange !== null) - { - this._onRateChange.dispatch(event); - } -}; +// if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) +// { +// this._currentAudioIndex = event.oldQuality; +// this._currentAudioPendingIndex = event.newQuality; +// } +// else if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) +// { +// this._currentVideoIndex = event.oldQuality; +// this._currentVideoPendingIndex = event.newQuality; + +// if (this._onQualityRequest !== null) +// { +// this._onQualityRequest.dispatch(this._currentVideoPendingIndex); +// } +// } +// }; /** - * Private event handler for playing. - * @method FORGE.VideoHls#_onPlayingHandler + * Private event handler for quality request aborted. + * @method FORGE.VideoHls#_onQualityAbortHandler * @private - * @param {Event} event - The native video event. + * @param {Event} event - The hls.js media player event. */ -FORGE.VideoHls.prototype._onPlayingHandler = function(event) -{ - var element = this._video.element; - this.log("onPlaying [readyState: " + element.readyState + "]"); +// FORGE.VideoHls.prototype._onQualityAbortHandler = function(event) +// { +// var element = this._video.element; +// this.log("onQualityAbort [readyState: "+element.readyState+"]"); - if (this._onPlaying !== null) - { - this._onPlaying.dispatch(event); - } -}; +// if(this._onQualityAbort !== null) +// { +// this._onQualityAbort.dispatch(this._video.requestIndex); +// } +// }; /** * Destroy a video object at a specified index, wiil look at the video object into _videos array then detoy it. @@ -1649,16 +1471,21 @@ FORGE.VideoHls.prototype._destroyVideo = function() { this.log("_destroyVideo"); - if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + var v = this._video; + var element = v.element; + + if (this._hlsMediaPlayer !== null && this._isReady === true && typeof element !== "undefined") { this._uninstallEvents(); - this._hlsMediaPlayer.pause(); - this._hlsMediaPlayer.reset(); + element.pause(); + + this._hlsMediaPlayer.stopLoad(); + this._hlsMediaPlayer.detachMedia(); + this._hlsMediaPlayer.destroy(); } - var video = this._video; - var element = video.element; + this._onEventBind = null; if (typeof element !== "undefined" && element !== null) { @@ -1669,21 +1496,21 @@ FORGE.VideoHls.prototype._destroyVideo = function() } element = null; - video.element = null; + v.element = null; - if (video.buffer !== null) + if (v.buffer !== null) { - video.buffer.destroy(); - video.buffer = null; + v.buffer.destroy(); + v.buffer = null; } - if (video.played !== null) + if (v.played !== null) { - video.played.destroy(); - video.played = null; + v.played.destroy(); + v.played = null; } - video = null; + v = null; }; /** @@ -1697,7 +1524,7 @@ FORGE.VideoHls.prototype._disableSoundHandler = function() if (v !== null && v.element !== null && this._viewer.audio.enabled === false) { - this._hlsMediaPlayer.setVolume(0); + v.element.volume = 0; } }; @@ -1722,15 +1549,7 @@ FORGE.VideoHls.prototype._updateVolume = function() if (v !== null && v.element !== null && this._viewer.audio.enabled === true) { - this._hlsMediaPlayer.setVolume(this._volume * this._viewer.audio.volume); - if (this._muted === true) - { - this._hlsMediaPlayer.setMute(true); - } - else - { - this._hlsMediaPlayer.setMute(false); - } + v.element.volume = this._volume * this._viewer.audio.volume; } }; @@ -1740,44 +1559,44 @@ FORGE.VideoHls.prototype._updateVolume = function() * @param {number} index - The quality index. * @private */ -FORGE.VideoHls.prototype._setRequestQuality = function(index) -{ - this._currentVideoPendingIndex = index; - - if (this._streamInfo !== null && this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true && this._hlsMetrics !== null) - { - var streamIndex = this._streamInfo.index; - var maxVideoIndex = this._hlsMetrics.getMaxIndexForBufferType(FORGE.VideoHls.mediaType.VIDEO, streamIndex); - var maxAudioIndex = this._hlsMetrics.getMaxIndexForBufferType(FORGE.VideoHls.mediaType.AUDIO, streamIndex); - - var newVideoIndex = index, - newAudioIndex = index; - - // zero based indexes - if (newVideoIndex >= maxVideoIndex) - { - newVideoIndex = maxVideoIndex - 1; - } - if (newVideoIndex < 0) - { - newVideoIndex = 0; - } - if (newAudioIndex >= maxAudioIndex) - { - newAudioIndex = maxAudioIndex - 1; - } - if (newAudioIndex < 0) - { - newAudioIndex = 0; - } +// FORGE.VideoHls.prototype._setRequestQuality = function(index) +// { +// this._currentVideoPendingIndex = index; - this._hlsMediaPlayer.setQualityFor(FORGE.VideoHls.mediaType.VIDEO, newVideoIndex); - this._hlsMediaPlayer.setQualityFor(FORGE.VideoHls.mediaType.AUDIO, newAudioIndex); - } +// if (this._streamInfo !== null && this._hlsMediaPlayer !== null && this._isReady === true && this._hlsMetrics !== null) +// { +// var streamIndex = this._streamInfo.index; +// var maxVideoIndex = this._hlsMetrics.getMaxIndexForBufferType(FORGE.VideoHls.mediaType.VIDEO, streamIndex); +// var maxAudioIndex = this._hlsMetrics.getMaxIndexForBufferType(FORGE.VideoHls.mediaType.AUDIO, streamIndex); + +// var newVideoIndex = index, +// newAudioIndex = index; + +// // zero based indexes +// if (newVideoIndex >= maxVideoIndex) +// { +// newVideoIndex = maxVideoIndex - 1; +// } +// if (newVideoIndex < 0) +// { +// newVideoIndex = 0; +// } +// if (newAudioIndex >= maxAudioIndex) +// { +// newAudioIndex = maxAudioIndex - 1; +// } +// if (newAudioIndex < 0) +// { +// newAudioIndex = 0; +// } + +// this._hlsMediaPlayer.setQualityFor(FORGE.VideoHls.mediaType.VIDEO, newVideoIndex); +// this._hlsMediaPlayer.setQualityFor(FORGE.VideoHls.mediaType.AUDIO, newAudioIndex); +// } - // Update the volume for the requested video - this._updateVolume(); -}; +// // Update the volume for the requested video +// this._updateVolume(); +// }; /** * Sets the quality mode.<br> @@ -1797,7 +1616,7 @@ FORGE.VideoHls.prototype._setQualityMode = function(mode) { this._qualityMode = mode; - // if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + // if (this._hlsMediaPlayer !== null && this._isReady === true) // { // if (mode === FORGE.VideoQualityMode.MANUAL) // { @@ -1850,12 +1669,30 @@ FORGE.VideoHls.prototype.play = function(time, loop) { FORGE.VideoBase.prototype.play.call(this, time, loop); - if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + var currentVideo = this._video; + + if (this._hlsMediaPlayer !== null && this._isReady === true && currentVideo !== null && currentVideo.element !== null) { - this._hlsMediaPlayer.play(); - this._playing = true; - this._paused = false; - this._playCount++; + var p = currentVideo.element.play(); + if (typeof p !== "undefined" && typeof Promise !== "undefined" && p instanceof Promise) + { + p.then(function() + { + this._playing = true; + this._paused = false; + this._playCount++; + }.bind(this)) + .catch(function(error) + { + this.log("Error while playing the video : " + error); + }.bind(this)); + } + else + { + this._playing = true; + this._paused = true; + this._playCount++; + } } }; @@ -1865,9 +1702,11 @@ FORGE.VideoHls.prototype.play = function(time, loop) */ FORGE.VideoHls.prototype.pause = function() { - if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + var currentVideo = this._video; + + if (this._hlsMediaPlayer !== null && this._isReady === true && currentVideo !== null && currentVideo.element !== null) { - this._hlsMediaPlayer.pause(); + currentVideo.element.pause(); this._playing = false; this._paused = true; } @@ -1879,11 +1718,12 @@ FORGE.VideoHls.prototype.pause = function() */ FORGE.VideoHls.prototype.stop = function() { - if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) + var currentVideo = this._video; + + if (this._hlsMediaPlayer !== null && this._isReady === true && currentVideo !== null && currentVideo.element !== null) { - this._hlsMediaPlayer.pause(); - this._hlsMediaPlayer.seek(0); - this._video.element.currentTime = 0; + currentVideo.element.pause(); + currentVideo.element.currentTime = 0; this._playing = false; this._paused = true; } @@ -1952,20 +1792,6 @@ FORGE.VideoHls.prototype.unmute = function(volume) } }; -/** - * Enable/Disable the buffer-occupancy-based (BOLA) ABR rule set.<br> - * BOLA white paper: http://arxiv.org/abs/1601.06748. - * @method FORGE.VideoHls#enableBufferOccupancyABR - * @param {boolean} bool - Is the BOLA rule set is activated? - */ -FORGE.VideoHls.prototype.enableBufferOccupancyABR = function(bool) -{ - if (this._hlsMediaPlayer !== null && this._hlsMediaPlayer.isReady() === true) - { - this._hlsMediaPlayer.enableBufferOccupancyABR(bool); - } -}; - /** * Destroy method. * @method FORGE.VideoHls#destroy @@ -2076,6 +1902,12 @@ FORGE.VideoHls.prototype.destroy = function() this._onStalled = null; } + if (this._onWaiting !== null) + { + this._onWaiting.destroy(); + this._onWaiting = null; + } + if (this._onRateChange !== null) { this._onRateChange.destroy(); @@ -2118,47 +1950,28 @@ FORGE.VideoHls.prototype.destroy = function() this._onQualityModeChange = null; } - if (this._onMetricsChanged !== null) - { - this._onMetricsChanged.destroy(); - this._onMetricsChanged = null; - } - - this._onLoadStartBind = null; - this._onLoadedMetaDataBind = null; - this._onLoadedDataBind = null; - this._onProgressBind = null; - this._onDurationChangeBind = null; - this._onCanPlayBind = null; - this._onCanPlayThroughBind = null; - this._onPlayBind = null; - this._onPauseBind = null; - this._onTimeUpdateBind = null; - this._onVolumeChangeBind = null; - this._onSeekingBind = null; - this._onSeekedBind = null; - this._onEndedBind = null; - this._onErrorBind = null; - this._onPlayingBind = null; - this._onStalledBind = null; - this._onRateChangeBind = null; - this._onQualityRequestBind = null; - this._onQualityChangeBind = null; + // if (this._onMetricsChanged !== null) + // { + // this._onMetricsChanged.destroy(); + // this._onMetricsChanged = null; + // } + + // this._onQualityRequestBind = null; + // this._onQualityChangeBind = null; //this._onQualityAbortBind = null; - this._onMetricsChangedBind = null; + // this._onMetricsChangedBind = null; //Unbind main volume event this._viewer.audio.onVolumeChange.remove(this._mainVolumeChangeHandler, this); this._viewer.audio.onDisable.remove(this._disableSoundHandler, this); - this._hlsMediaPlayer = null; - this._playerVideoMetrics = null; - this._playerAudioMetrics = null; - this._hlsMetrics = null; + // this._playerVideoMetrics = null; + // this._playerAudioMetrics = null; + // this._hlsMetrics = null; - this._monitoring = null; - this._streamInfo = null; + // this._monitoring = null; + // this._streamInfo = null; this._config = null; @@ -2415,19 +2228,34 @@ Object.defineProperty(FORGE.VideoHls.prototype, "currentTime", /** @this {FORGE.VideoHls} */ get: function() { - return this._hlsMediaPlayer.time(); + // return this._hlsMediaPlayer.time(); + return this._getCurrentVideoElementProperty("currentTime", 0); }, /** @this {FORGE.VideoHls} */ set: function(value) { - if (typeof value === "number") // && value < this.duration) //@todo see if we can put video currentTime in pending if no metadata received ? + // if (typeof value === "number") // && value < this.duration) //@todo see if we can put video currentTime in pending if no metadata received ? + // { + // this._hlsMediaPlayer.seek(value); + + // if (this._onCurrentTimeChange !== null) + // { + // this._onCurrentTimeChange.dispatch(value); + // } + // } + if (typeof value === "number") //@todo see if we can put video currentTime in pending if no metadata received ? (typeof value === "number" && value < this.duration) { - this._hlsMediaPlayer.seek(value); + var currentVideo = this._video; - if (this._onCurrentTimeChange !== null) + if (currentVideo !== null && currentVideo.element !== null) { - this._onCurrentTimeChange.dispatch(value); + currentVideo.element.currentTime = value; + + if (this._onCurrentTimeChange !== null) + { + this._onCurrentTimeChange.dispatch(value); + } } } } @@ -2957,37 +2785,42 @@ Object.defineProperty(FORGE.VideoHls.prototype, "onStalled", }); /** - * Get the "onRateChange" event {@link FORGE.EventDispatcher} of the video. - * @name FORGE.VideoHls#onRateChange + * Get the "onWaiting" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onWaiting * @readonly * @type {FORGE.EventDispatcher} */ -Object.defineProperty(FORGE.VideoHls.prototype, "onRateChange", +Object.defineProperty(FORGE.VideoHls.prototype, "onWaiting", { /** @this {FORGE.VideoHls} */ get: function() { - if (this._onRateChange === null) + if (this._onWaiting === null) { - this._onRateChange = new FORGE.EventDispatcher(this); + this._onWaiting = new FORGE.EventDispatcher(this); } - return this._onRateChange; + return this._onWaiting; } }); /** - * Get a copy of the "onStalled" event for the "onWaiting" event {@link FORGE.EventDispatcher} of the video. - * @name FORGE.VideoHls#onWaiting + * Get the "onRateChange" event {@link FORGE.EventDispatcher} of the video. + * @name FORGE.VideoHls#onRateChange * @readonly * @type {FORGE.EventDispatcher} */ -Object.defineProperty(FORGE.VideoHls.prototype, "onWaiting", +Object.defineProperty(FORGE.VideoHls.prototype, "onRateChange", { /** @this {FORGE.VideoHls} */ get: function() { - return this.onStalled; + if (this._onRateChange === null) + { + this._onRateChange = new FORGE.EventDispatcher(this); + } + + return this._onRateChange; } }); From 76daa7c1a5ac91879225e41ed375632c14f1d4be Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Fri, 1 Dec 2017 17:52:25 +0100 Subject: [PATCH 09/19] Add quality change handlers --- src/display/video/VideoHls.js | 773 ++++++++-------------------------- 1 file changed, 179 insertions(+), 594 deletions(-) diff --git a/src/display/video/VideoHls.js b/src/display/video/VideoHls.js index 6581425d..4469d08b 100644 --- a/src/display/video/VideoHls.js +++ b/src/display/video/VideoHls.js @@ -46,22 +46,6 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) */ this._qualities = null; - /** - * The index of the current quality (if -1 no video is selected as the current one). - * @name FORGE.Video#_currentQuality - * @type {number} - * @private - */ - // this._currentQuality = -1; - - /** - * First quality is initialized? - * @name FORGE.VideoHls#_qualityInitialized - * @type {boolean} - * @private - */ - // this._qualityInitialized = false; - /** * Default quality mode, it can be either "auto" or "manual", modes are listed by FORGE.VideoQualityMode constants. * @name FORGE.VideoHls#_defaultQualityMode @@ -151,21 +135,13 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) */ this._isReady = false; - /** - * The hls stream info object. - * @name FORGE.VideoHls#_streamInfo - * @type {StreamInfo} - * @private - */ - // this._streamInfo = null; - /** * The current index for video. * @name FORGE.VideoHls#_currentIndex * @type {number} * @private */ - // this._currentVideoIndex = 0; + this._currentIndex = 0; /** * The current pending index for video. @@ -173,55 +149,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {number} * @private */ - // this._currentVideoPendingIndex = 0; - - /** - * The current index for audio. - * @name FORGE.VideoHls#_currentIndex - * @type {number} - * @private - */ - // this._currentAudioIndex = 0; - - /** - * The current pending index for audio. - * @name FORGE.VideoHls#_currentPendingIndex - * @type {number} - * @private - */ - // this._currentAudioPendingIndex = 0; - - /** - * The hls media player video metrics object. - * @name FORGE.VideoHls#_playerVideoMetrics - * @type {Object} - * @private - */ - // this._playerVideoMetrics = null; - - /** - * The hls media player audio metrics object. - * @name FORGE.VideoHls#_playerAudioMetrics - * @type {Object} - * @private - */ - // this._playerAudioMetrics = null; - - /** - * The hls stream metrics object. - * @name FORGE.VideoHls#_hlsMetrics - * @type {hlsMetrics} - * @private - */ - // this._hlsMetrics = null; - - /** - * The monitoring object. - * @name FORGE.VideoHls#_monitoring - * @type {Object} - * @private - */ - // this._monitoring = null; + this._currentPendingIndex = 0; /** * On load start event dispatcher. @@ -439,20 +367,6 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) */ this._onQualityModeChange = null; - /** - * On metrics changed event dispatcher. - * @name FORGE.VideoHls#_onMetricsChanged - * @type {?FORGE.EventDispatcher} - * @private - */ - // this._onMetricsChanged = null; - - - - - - - /** * Event handler for current video quality request binded to this. * @name FORGE.VideoHls#_onQualityRequestBind @@ -475,7 +389,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * @type {Function} * @private */ - //this._onQualityAbortBind = null; + this._onQualityAbortBind = null; /** * Event handler for stream switch completed. @@ -485,14 +399,6 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) */ this._onSwitchCompletedBind = null; - /** - * Event handler for metrics changed. - * @name FORGE.VideoHls#_onMetricsChangedBind - * @type {Function} - * @private - */ - // this._onMetricsChangedBind = null; - /** * Event handler for all events fired by the HTMLVideoElement. See https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events for a list of available events. * @name FORGE.VideoHls#_onEventBind @@ -556,31 +462,12 @@ FORGE.VideoHls.prototype._boot = function() this._launchHlsMediaPlayerBind = this._launchHlsMediaPlayer.bind(this); this._onEventBind = this._onEventHandler.bind(this); - - // this._onLoadStartBind = this._onLoadStartHandler.bind(this); - // this._onDurationChangeBind = this._onDurationChangeHandler.bind(this); - // this._onLoadedMetaDataBind = this._onLoadedMetaDataHandler.bind(this); - // this._onLoadedDataBind = this._onLoadedDataHandler.bind(this); - // this._onProgressBind = this._onProgressHandler.bind(this); - // this._onCanPlayBind = this._onCanPlayHandler.bind(this); - // this._onCanPlayThroughBind = this._onCanPlayThroughHandler.bind(this); - // this._onPlayBind = this._onPlayHandler.bind(this); - // this._onPauseBind = this._onPauseHandler.bind(this); - // this._onTimeUpdateBind = this._onTimeUpdateHandler.bind(this); - // this._onVolumeChangeBind = this._onVolumeChangeHandler.bind(this); - // this._onSeekingBind = this._onSeekingHandler.bind(this); - // this._onSeekedBind = this._onSeekedHandler.bind(this); - // this._onErrorBind = this._onErrorHandler.bind(this); - // this._onStalledBind = this._onStalledHandler.bind(this); - // this._onRateChangeBind = this._onRateChangeHandler.bind(this); - // this._onPlayingBind = this._onPlayingHandler.bind(this); - // this._onQualityRequestBind = this._onQualityRequestHandler.bind(this); - // this._onQualityChangeBind = this._onQualityChangeHandler.bind(this); - // //this._onQualityAbortBind = this._onQualityAbortHandler.bind(this); + this._onQualityAbortBind = this._onQualityAbortHandler.bind(this); // HLS specific - // this._onSwitchCompletedBind = this._onSwitchCompletedHandler.bind(this); - // this._onMetricsChangedBind = this._onMetricsChangedHandler.bind(this); + this._onQualityRequestBind = this._onQualityRequestHandler.bind(this); + this._onQualityChangeBind = this._onQualityChangeHandler.bind(this); + this._onSwitchCompletedBind = this._onSwitchCompletedHandler.bind(this); //Listen to the main volume change to adapt the video volume accordingly. this._viewer.audio.onVolumeChange.add(this._mainVolumeChangeHandler, this); @@ -732,7 +619,8 @@ FORGE.VideoHls.prototype._getCurrentVideoElementProperty = function(property, de */ FORGE.VideoHls.prototype._initHlsMediaPlayer = function() { - var hlsConfig = { + // HLS config + var config = { autoStartLoad: true, // start after Hls.Events.MANIFEST_PARSED startPosition : -1, // startTime debug: true, @@ -745,7 +633,7 @@ FORGE.VideoHls.prototype._initHlsMediaPlayer = function() }; // create the Media Player - this._hlsMediaPlayer = new Hls(hlsConfig); + this._hlsMediaPlayer = new Hls(config); // add video tag element and video source file this._hlsMediaPlayer.attachMedia(this._video.element); @@ -783,6 +671,10 @@ FORGE.VideoHls.prototype._loadHlsMediaPlayerSource = function() FORGE.VideoHls.prototype._launchHlsMediaPlayer = function(event, data) { this.log("manifest loaded, found " + data.levels.length + " quality level"); + + //populate qualities array with the HLS bitrates info list + this._createQualitiesFromBitrateInfoList(this._manifestUrl, data.levels); + this._isReady = true; }; @@ -806,25 +698,12 @@ FORGE.VideoHls.prototype._addVideoToDom = function() */ FORGE.VideoHls.prototype._installEvents = function() { - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["CAN_PLAY"], this._onCanPlayBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["ERROR"], this._onErrorBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_ENDED"], this._onEndedBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_ERROR"], this._onErrorBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_METADATA_LOADED"], this._onLoadedMetaDataBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_PAUSED"], this._onPauseBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_PROGRESS"], this._onProgressBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_SEEKING"], this._onSeekingBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_SEEKED"], this._onSeekedBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_STARTED"], this._onPlayBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_TIME_UPDATED"], this._onTimeUpdateBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["QUALITY_CHANGE_RENDERED"], this._onQualityChangeBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["QUALITY_CHANGE_REQUESTED"], this._onQualityRequestBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["STREAM_INITIALIZED"], this._onLoadStartBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_PLAYING"], this._onPlayingBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["BUFFER_EMPTY"], this._onStalledBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PLAYBACK_RATE_CHANGED"], this._onRateChangeBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["PERIOD_SWITCH_COMPLETED"], this._onSwitchCompletedBind); - // this._hlsMediaPlayer.on(Hls.MediaPlayer.events["METRIC_CHANGED"], this._onMetricsChangedBind); + this._hlsMediaPlayer.on(Hls.Events.LEVEL_LOADED, this._onQualityChangeBind); + this._hlsMediaPlayer.on(Hls.Events.LEVEL_LOADING, this._onQualityRequestBind); + this._hlsMediaPlayer.on(Hls.Events.LEVEL_SWITCHED, this._onSwitchCompletedBind); + this._hlsMediaPlayer.on(Hls.ErrorDetails.LEVEL_LOAD_ERROR, this._onQualityAbortBind); + this._hlsMediaPlayer.on(Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT, this._onQualityAbortBind); + this._hlsMediaPlayer.on(Hls.ErrorDetails.LEVEL_SWITCH_ERROR, this._onQualityAbortBind); var element = this._video.element; @@ -847,14 +726,6 @@ FORGE.VideoHls.prototype._installEvents = function() element.addEventListener("stalled", this._onEventBind, false); element.addEventListener("playing", this._onEventBind, false); element.addEventListener("ratechange", this._onEventBind, false); - - - - - // this._video.element.addEventListener("loadeddata", this._onLoadedDataBind, false); - // this._video.element.addEventListener("durationchange", this._onDurationChangeBind, false); - // this._video.element.addEventListener("canplaythrough", this._onCanPlayThroughBind, false); - // this._video.element.addEventListener("volumechange", this._onVolumeChangeBind, false); }; /** @@ -886,30 +757,12 @@ FORGE.VideoHls.prototype._uninstallEvents = function() element.removeEventListener("playing", this._onEventBind, false); element.removeEventListener("ratechange", this._onEventBind, false); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["CAN_PLAY"], this._onCanPlayBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["ERROR"], this._onErrorBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_ENDED"], this._onEndedBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_ERROR"], this._onErrorBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_METADATA_LOADED"], this._onLoadedMetaDataBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_PAUSED"], this._onPauseBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_PROGRESS"], this._onProgressBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_SEEKING"], this._onSeekingBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_SEEKED"], this._onSeekedBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_STARTED"], this._onPlayBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_TIME_UPDATED"], this._onTimeUpdateBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["QUALITY_CHANGE_RENDERED"], this._onQualityChangeBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["QUALITY_CHANGE_REQUESTED"], this._onQualityRequestBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["STREAM_INITIALIZED"], this._onLoadStartBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_PLAYING"], this._onPlayingBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["BUFFER_EMPTY"], this._onStalledBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PLAYBACK_RATE_CHANGED"], this._onRateChangeBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["PERIOD_SWITCH_COMPLETED"], this._onSwitchCompletedBind); - // this._hlsMediaPlayer.off(Hls.MediaPlayer.events["METRIC_CHANGED"], this._onMetricsChangedBind); - - // this._video.element.removeEventListener("loadeddata", this._onLoadedDataBind, false); - // this._video.element.removeEventListener("durationchange", this._onDurationChangeBind, false); - // this._video.element.removeEventListener("canplaythrough", this._onCanPlayThroughBind, false); - // this._video.element.removeEventListener("volumechange", this._onVolumeChangeBind, false); + this._hlsMediaPlayer.off(Hls.ErrorDetails.LEVEL_LOAD_ERROR, this._onQualityAbortBind); + this._hlsMediaPlayer.off(Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT, this._onQualityAbortBind); + this._hlsMediaPlayer.off(Hls.ErrorDetails.LEVEL_SWITCH_ERROR, this._onQualityAbortBind); + this._hlsMediaPlayer.off(Hls.Events.LEVEL_LOADED, this._onQualityChangeBind); + this._hlsMediaPlayer.off(Hls.Events.LEVEL_LOADING, this._onQualityRequestBind); + this._hlsMediaPlayer.off(Hls.Events.LEVEL_SWITCHED, this._onSwitchCompletedBind); }; /** @@ -1111,71 +964,51 @@ FORGE.VideoHls.prototype._onEventHandler = function(event) }; /** - * Private event handler for loadStart. - * @method FORGE.VideoHls#_onLoadStartHandler - * @param {Event} event - The native video event. - * @private - */ -// FORGE.VideoHls.prototype._onLoadStartHandler = function(event) -// { -// var element = this._video.element; -// this.log("onLoadStart [readyState: " + element.readyState + "]"); - -// //populate qualities array with the HLS bitrates info list -// this._createQualitiesFromBitrateInfoList(this._manifestUrl, this._hlsMediaPlayer.getBitrateInfoListFor(FORGE.VideoHls.mediaType.VIDEO)); - -// if (this._onLoadStart !== null) -// { -// this._onLoadStart.dispatch(event); -// } -// }; - -/** - * Create a qualities array from the bitrates info list. + * Create a qualities array from the levels info list. * @method FORGE.VideoHls#_createQualitiesFromBitrateInfoList * @param {string} url - The manifest url. - * @param {Array<BitrateInfo>} bitrates - The bitrates array. + * @param {Array<Level>} levels - The levels array. * @param {boolean=} checkURL - URL must be checked? * @return {Array<FORGE.VideoQuality>} The qualities array. * @private */ -// FORGE.VideoHls.prototype._createQualitiesFromBitrateInfoList = function(url, bitrates, checkURL) -// { -// var qualities = []; -// var quality; - -// if (bitrates !== null) -// { -// for (var i = 0, ii = bitrates.length; i < ii; i++) -// { -// if (checkURL === true && FORGE.URL.isValid(url) === false) -// { -// throw "FORGE.Video: URL " + url + " is invalid"; -// } - -// quality = new FORGE.VideoQuality(url); -// quality.id = bitrates[i].qualityIndex; -// quality.bitrate = bitrates[i].bitrate; -// quality.width = bitrates[i].width; -// quality.height = bitrates[i].height; - -// qualities.push(quality); -// } - -// this._qualities = /** @type {Array<FORGE.VideoQuality>} */ (qualities); - -// if (this._onQualitiesLoaded !== null) -// { -// this._onQualitiesLoaded.dispatch(qualities); -// } -// } -// else -// { -// this.destroy(); -// } - -// return qualities; -// }; +FORGE.VideoHls.prototype._createQualitiesFromBitrateInfoList = function(url, bitrates, checkURL) +{ + var qualities = []; + var quality; + + if (bitrates !== null) + { + for (var i = 0, ii = bitrates.length; i < ii; i++) + { + if (checkURL === true && typeof bitrates[i].url !== undefined && FORGE.URL.isValid(bitrates[i].url[0]) === false) + { + throw "FORGE.Video: URL " + url + " is invalid"; + } + + quality = new FORGE.VideoQuality(bitrates[i].url[0]); + quality.id = i; + quality.bitrate = bitrates[i].bitrate; + quality.width = bitrates[i].width; + quality.height = bitrates[i].height; + + qualities.push(quality); + } + + this._qualities = /** @type {Array<FORGE.VideoQuality>} */ (qualities); + + if (this._onQualitiesLoaded !== null) + { + this._onQualitiesLoaded.dispatch(qualities); + } + } + else + { + this.destroy(); + } + + return qualities; +}; /** * Get the index of a {@link FORGE.VideoQuality} that is in the _videoQualities array. @@ -1184,283 +1017,91 @@ FORGE.VideoHls.prototype._onEventHandler = function(event) * @param {FORGE.VideoQuality} quality - The quality you need to get its index. * @return {number} Returns the index of the quality if found, -1 if not found. */ -// FORGE.VideoHls.prototype._indexOfQuality = function(quality) -// { -// var q; -// for (var i = 0, ii = this._qualities.length; i < ii; i++) -// { -// q = this._qualities[i]; +FORGE.VideoHls.prototype._indexOfQuality = function(quality) +{ + var q; + for (var i = 0, ii = this._qualities.length; i < ii; i++) + { + q = this._qualities[i]; -// if (q === quality) -// { -// return i; -// } -// } + if (q === quality) + { + return i; + } + } -// return -1; -// }; + return -1; +}; /** * Private event handler for period switch completed. * @method FORGE.VideoHls#_onSwitchCompletedHandler - * @param {SwitchEvents} event - The hls.js media player event. + * @param {Object} event - The hls.js media player event. * @private */ -// FORGE.VideoHls.prototype._onSwitchCompletedHandler = function(event) -// { -// var element = this._video.element; -// this.log("_onSwitchCompleted [readyState: " + element.readyState + "]"); - -// this._streamInfo = /** @type {StreamInfo} */ (event.toStreamInfo); -// }; +FORGE.VideoHls.prototype._onSwitchCompletedHandler = function(event) +{ + var element = this._video.element; + this.log("_onSwitchCompleted [readyState: " + element.readyState + "]"); -/** - * Private event handler for mertics changed. - * @method FORGE.VideoHls#_onMetricsChangedHandler - * @param {MetricChangedEvents} event - The hls.js media player event. - * @private - */ -// FORGE.VideoHls.prototype._onMetricsChangedHandler = function(event) -// { -// var element = this._video.element; -// this.log("_onMetricsChangedHandler [readyState: " + element.readyState + "]"); - -// if (this._playerVideoMetrics === null) -// { -// this._playerVideoMetrics = this._hlsMediaPlayer.getMetricsFor(FORGE.VideoHls.mediaType.VIDEO); -// } - -// if (this._playerAudioMetrics === null) -// { -// this._playerAudioMetrics = this._hlsMediaPlayer.getMetricsFor(FORGE.VideoHls.mediaType.AUDIO); -// } - -// if (this._hlsMetrics === null) -// { -// this._hlsMetrics = this._hlsMediaPlayer.gethlsMetrics(); -// } - -// //set the current quality index -// // if (this._playerVideoMetrics !== null && this._hlsMetrics !== null) -// // { -// // var repSwitch = /** @type {RepresentationSwitch} */ (this._hlsMetrics.getCurrentRepresentationSwitch(this._playerVideoMetrics)); -// // if (repSwitch !== null) -// // { -// // this._currentQuality = this._hlsMetrics.getIndexForRepresentation(repSwitch.to, this._streamInfo.index); -// // if(this._qualityInitialized === false) -// // { -// // this._setRequestQuality(this._currentQuality); -// // this._qualityInitialized = true; -// // } -// // } -// // } - -// if (this._onMetricsChanged !== null) -// { -// var metrics; - -// if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) -// { -// metrics = this._getMetricsFor(FORGE.VideoHls.mediaType.VIDEO, this._playerVideoMetrics, this._hlsMetrics); -// if (metrics) -// { -// this._monitoring = { -// "videoBitrate": metrics.bitrate, -// "videoIndex": metrics.index, -// "videoPendingIndex": metrics.pendingIndex, -// "videoMaxIndex": metrics.maxIndex, -// "videoBufferLength": metrics.bufferLength, -// "videoDroppedFrames": metrics.droppedFrames -// //"videoRequestsQueue": metrics.requestsQueue -// }; -// } -// } - -// if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) -// { -// metrics = this._getMetricsFor(FORGE.VideoHls.mediaType.AUDIO, this._playerAudioMetrics, this._hlsMetrics); -// if (metrics) -// { -// this._monitoring = { -// "audioBitrate": metrics.bitrate, -// "audioIndex": metrics.index, -// "audioPendingIndex": metrics.pendingIndex, -// "audioMaxIndex": metrics.maxIndex, -// "audioBufferLength": metrics.bufferLength, -// "audioDroppedFrames": metrics.droppedFrames -// //"audioRequestsQueue": metrics.requestsQueue -// }; -// } -// } - -// this._onMetricsChanged.dispatch(event); -// } -// }; - - -/** - * Prepare a metrics object for video/audio data. - * @method FORGE.VideoHls#_getMetricsFor - * @param {string} type - The video or audio type. - * @param {Object} metrics - The player video or audio metrics. - * @param {hlsMetrics} hlsMetrics - The hls stream video or audio metrics. - * @return {?Object} The monitoring object - * @private - */ -// FORGE.VideoHls.prototype._getMetricsFor = function(type, metrics, hlsMetrics) -// { -// if (metrics !== null && hlsMetrics !== null) -// { -// var streamIndex = this._streamInfo.index; -// var repSwitch, maxIndex, bufferLevel, droppedFramesMetrics, bitrate, index, pendingIndex, bufferLength, droppedFrames; //httpRequests requestsQueue pendingValue - -// repSwitch = /** @type {RepresentationSwitch} */ (hlsMetrics.getCurrentRepresentationSwitch(metrics)); -// if (repSwitch !== null) -// { -// // index = hlsMetrics.getIndexForRepresentation(repSwitch.to, streamIndex); -// bitrate = Math.round(hlsMetrics.getBandwidthForRepresentation(repSwitch.to, streamIndex) / 1000); -// } -// if (isNaN(bitrate) || bitrate === undefined) -// { -// bitrate = 0; -// } - -// if (type === FORGE.VideoHls.mediaType.VIDEO) -// { -// index = this._currentVideoIndex + 1; -// pendingIndex = this._currentVideoPendingIndex + 1; -// } -// else if (type === FORGE.VideoHls.mediaType.AUDIO) -// { -// index = this._currentAudioIndex + 1; -// pendingIndex = this._currentAudioPendingIndex + 1; -// } - -// if (isNaN(index) || index === undefined) -// { -// index = 0; -// } -// if (isNaN(pendingIndex) || pendingIndex === undefined) -// { -// pendingIndex = 0; -// } - -// maxIndex = hlsMetrics.getMaxIndexForBufferType(type, streamIndex); -// if (isNaN(maxIndex) || maxIndex === undefined) -// { -// maxIndex = 0; -// } - -// bufferLevel = hlsMetrics.getCurrentBufferLevel(metrics); -// if (bufferLevel !== null) -// { -// bufferLength = bufferLevel.toPrecision(5); -// } -// if (isNaN(bufferLength) || bufferLength === undefined) -// { -// bufferLength = 0; -// } - -// //httpRequests = hlsMetrics.getHttpRequests(metrics); - -// droppedFramesMetrics = /** @type {DroppedFrames} */ (hlsMetrics.getCurrentDroppedFrames(metrics)); -// if (droppedFramesMetrics !== null) -// { -// droppedFrames = droppedFramesMetrics.droppedFrames; -// } - -// //pendingValue = this._hlsMediaPlayer.getQualityFor(type); - -// //requestsQueue = hlsMetrics.getRequestsQueue(metrics); - -// var result = { -// bitrate: bitrate, -// index: index, -// pendingIndex: pendingIndex, -// maxIndex: maxIndex, -// bufferLength: bufferLength, -// droppedFrames: droppedFrames -// //requestsQueue: requestsQueue -// }; - -// return result; -// } - -// return null; -// }; + // new level is event.data.level; +}; /** * Private event handler for quality change. * @method FORGE.VideoHls#_onQualityChangeHandler * @private - * @param {QualityEvents} event - The hls.js media player event. - */ -// FORGE.VideoHls.prototype._onQualityChangeHandler = function(event) -// { -// var element = this._video.element; -// this.log("onQualityChange [readyState: " + element.readyState + "]"); - -// if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) -// { -// this._currentAudioIndex = event.newQuality; -// this._currentAudioPendingIndex = event.newQuality; -// } -// else if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) -// { -// this._currentVideoIndex = event.newQuality; -// this._currentVideoPendingIndex = event.newQuality; - -// if (this._onQualityChange !== null) -// { -// this._onQualityChange.dispatch(this._currentVideoPendingIndex); -// } -// } -// }; + * @param {Object} event - The hls.js media player event. + */ +FORGE.VideoHls.prototype._onQualityChangeHandler = function(event) +{ + var element = this._video.element; + this.log("onQualityChange [readyState: " + element.readyState + "]"); + + // this._currentIndex = event.data.level; + // this._currentPendingIndex = event.data.level; + + // if (this._onQualityChange !== null) + // { + // this._onQualityChange.dispatch(this._currentIndex); + // } +}; /** * Private event handler for quality request. * @method FORGE.VideoHls#_onQualityRequestHandler * @private - * @param {QualityEvents} event - The hls.js media player event. - */ -// FORGE.VideoHls.prototype._onQualityRequestHandler = function(event) -// { -// var element = this._video.element; -// this.log("onQualityRequest [readyState: " + element.readyState + "]"); - -// if (event.mediaType === FORGE.VideoHls.mediaType.AUDIO) -// { -// this._currentAudioIndex = event.oldQuality; -// this._currentAudioPendingIndex = event.newQuality; -// } -// else if (event.mediaType === FORGE.VideoHls.mediaType.VIDEO) -// { -// this._currentVideoIndex = event.oldQuality; -// this._currentVideoPendingIndex = event.newQuality; - -// if (this._onQualityRequest !== null) -// { -// this._onQualityRequest.dispatch(this._currentVideoPendingIndex); -// } -// } -// }; + * @param {Object} event - The hls.js media player event. + */ +FORGE.VideoHls.prototype._onQualityRequestHandler = function(event) +{ + var element = this._video.element; + this.log("onQualityRequest [readyState: " + element.readyState + "]"); + + // this._currentPendingIndex = event.data.level; + + // if (this._onQualityRequest !== null) + // { + // this._onQualityRequest.dispatch(this._currentPendingIndex); + // } +}; /** * Private event handler for quality request aborted. * @method FORGE.VideoHls#_onQualityAbortHandler * @private - * @param {Event} event - The hls.js media player event. + * @param {Object} event - The hls.js media player event. */ -// FORGE.VideoHls.prototype._onQualityAbortHandler = function(event) -// { -// var element = this._video.element; -// this.log("onQualityAbort [readyState: "+element.readyState+"]"); +FORGE.VideoHls.prototype._onQualityAbortHandler = function(event) +{ + var element = this._video.element; + this.log("onQualityAbort [readyState: "+element.readyState+"]"); -// if(this._onQualityAbort !== null) -// { -// this._onQualityAbort.dispatch(this._video.requestIndex); -// } -// }; + if(this._onQualityAbort !== null) + { + this._onQualityAbort.dispatch(this._currentPendingIndex); + } +}; /** * Destroy a video object at a specified index, wiil look at the video object into _videos array then detoy it. @@ -1559,44 +1200,32 @@ FORGE.VideoHls.prototype._updateVolume = function() * @param {number} index - The quality index. * @private */ -// FORGE.VideoHls.prototype._setRequestQuality = function(index) -// { -// this._currentVideoPendingIndex = index; - -// if (this._streamInfo !== null && this._hlsMediaPlayer !== null && this._isReady === true && this._hlsMetrics !== null) -// { -// var streamIndex = this._streamInfo.index; -// var maxVideoIndex = this._hlsMetrics.getMaxIndexForBufferType(FORGE.VideoHls.mediaType.VIDEO, streamIndex); -// var maxAudioIndex = this._hlsMetrics.getMaxIndexForBufferType(FORGE.VideoHls.mediaType.AUDIO, streamIndex); - -// var newVideoIndex = index, -// newAudioIndex = index; - -// // zero based indexes -// if (newVideoIndex >= maxVideoIndex) -// { -// newVideoIndex = maxVideoIndex - 1; -// } -// if (newVideoIndex < 0) -// { -// newVideoIndex = 0; -// } -// if (newAudioIndex >= maxAudioIndex) -// { -// newAudioIndex = maxAudioIndex - 1; -// } -// if (newAudioIndex < 0) -// { -// newAudioIndex = 0; -// } - -// this._hlsMediaPlayer.setQualityFor(FORGE.VideoHls.mediaType.VIDEO, newVideoIndex); -// this._hlsMediaPlayer.setQualityFor(FORGE.VideoHls.mediaType.AUDIO, newAudioIndex); -// } - -// // Update the volume for the requested video -// this._updateVolume(); -// }; +FORGE.VideoHls.prototype._setRequestQuality = function(index) +{ + this._currentPendingIndex = index; + + if (this._hlsMediaPlayer !== null && this._isReady === true) + { + // var streamIndex = this._streamId; + var maxIndex = this._hlsMediaPlayer.levels.length; + var newIndex = index; + + // zero based indexes + if (newIndex >= maxIndex) + { + newIndex = maxIndex - 1; + } + if (newIndex < 0) + { + newIndex = 0; + } + + this._hlsMediaPlayer.loadLevel(newIndex); + } + + // Update the volume for the requested video + this._updateVolume(); +}; /** * Sets the quality mode.<br> @@ -1616,19 +1245,17 @@ FORGE.VideoHls.prototype._setQualityMode = function(mode) { this._qualityMode = mode; - // if (this._hlsMediaPlayer !== null && this._isReady === true) - // { - // if (mode === FORGE.VideoQualityMode.MANUAL) - // { - // this._hlsMediaPlayer.setAutoSwitchQualityFor(FORGE.VideoHls.mediaType.VIDEO, false); - // this._hlsMediaPlayer.setAutoSwitchQualityFor(FORGE.VideoHls.mediaType.AUDIO, false); - // } - // else - // { - // this._hlsMediaPlayer.setAutoSwitchQualityFor(FORGE.VideoHls.mediaType.VIDEO, true); - // this._hlsMediaPlayer.setAutoSwitchQualityFor(FORGE.VideoHls.mediaType.AUDIO, true); - // } - // } + if (this._hlsMediaPlayer !== null && this._isReady === true) + { + if (mode === FORGE.VideoQualityMode.MANUAL) + { + this._hlsMediaPlayer.loadLevel(this._currentIndex); + } + else + { + this._hlsMediaPlayer.loadLevel(-1); + } + } if (this._onQualityModeChange !== null) { @@ -1669,11 +1296,11 @@ FORGE.VideoHls.prototype.play = function(time, loop) { FORGE.VideoBase.prototype.play.call(this, time, loop); - var currentVideo = this._video; + var v = this._video; - if (this._hlsMediaPlayer !== null && this._isReady === true && currentVideo !== null && currentVideo.element !== null) + if (this._hlsMediaPlayer !== null && this._isReady === true && v !== null && v.element !== null) { - var p = currentVideo.element.play(); + var p = v.element.play(); if (typeof p !== "undefined" && typeof Promise !== "undefined" && p instanceof Promise) { p.then(function() @@ -1702,11 +1329,11 @@ FORGE.VideoHls.prototype.play = function(time, loop) */ FORGE.VideoHls.prototype.pause = function() { - var currentVideo = this._video; + var v = this._video; - if (this._hlsMediaPlayer !== null && this._isReady === true && currentVideo !== null && currentVideo.element !== null) + if (this._hlsMediaPlayer !== null && this._isReady === true && v !== null && v.element !== null) { - currentVideo.element.pause(); + v.element.pause(); this._playing = false; this._paused = true; } @@ -1718,12 +1345,12 @@ FORGE.VideoHls.prototype.pause = function() */ FORGE.VideoHls.prototype.stop = function() { - var currentVideo = this._video; + var v = this._video; - if (this._hlsMediaPlayer !== null && this._isReady === true && currentVideo !== null && currentVideo.element !== null) + if (this._hlsMediaPlayer !== null && this._isReady === true && v !== null && v.element !== null) { - currentVideo.element.pause(); - currentVideo.element.currentTime = 0; + v.element.pause(); + v.element.currentTime = 0; this._playing = false; this._paused = true; } @@ -1950,29 +1577,16 @@ FORGE.VideoHls.prototype.destroy = function() this._onQualityModeChange = null; } - // if (this._onMetricsChanged !== null) - // { - // this._onMetricsChanged.destroy(); - // this._onMetricsChanged = null; - // } - - // this._onQualityRequestBind = null; - // this._onQualityChangeBind = null; - //this._onQualityAbortBind = null; - // this._onMetricsChangedBind = null; + this._onQualityRequestBind = null; + this._onQualityChangeBind = null; + this._onQualityAbortBind = null; + this._onSwitchCompletedBind = null; //Unbind main volume event this._viewer.audio.onVolumeChange.remove(this._mainVolumeChangeHandler, this); this._viewer.audio.onDisable.remove(this._disableSoundHandler, this); - // this._playerVideoMetrics = null; - // this._playerAudioMetrics = null; - // this._hlsMetrics = null; - - // this._monitoring = null; - // this._streamInfo = null; - this._config = null; this._qualities = null; @@ -2006,7 +1620,7 @@ Object.defineProperty(FORGE.VideoHls.prototype, "quality", /** @this {FORGE.VideoHls} */ get: function() { - return this._qualities[this._currentVideoIndex]; + return this._qualities[this._currentIndex]; }, /** @this {FORGE.VideoHls} */ @@ -2088,7 +1702,7 @@ Object.defineProperty(FORGE.VideoHls.prototype, "requestIndex", /** @this {FORGE.VideoHls} */ get: function() { - return this._currentVideoPendingIndex; + return this._currentPendingIndex; } }); @@ -2103,7 +1717,7 @@ Object.defineProperty(FORGE.VideoHls.prototype, "currentIndex", /** @this {FORGE.VideoHls} */ get: function() { - return this._currentVideoIndex; + return this._currentIndex; } }); @@ -2235,15 +1849,6 @@ Object.defineProperty(FORGE.VideoHls.prototype, "currentTime", /** @this {FORGE.VideoHls} */ set: function(value) { - // if (typeof value === "number") // && value < this.duration) //@todo see if we can put video currentTime in pending if no metadata received ? - // { - // this._hlsMediaPlayer.seek(value); - - // if (this._onCurrentTimeChange !== null) - // { - // this._onCurrentTimeChange.dispatch(value); - // } - // } if (typeof value === "number") //@todo see if we can put video currentTime in pending if no metadata received ? (typeof value === "number" && value < this.duration) { var currentVideo = this._video; @@ -2306,7 +1911,7 @@ Object.defineProperty(FORGE.VideoHls.prototype, "duration", /** @this {FORGE.VideoHls} */ get: function() { - return this._hlsMediaPlayer.duration(); + return this._getCurrentVideoElementProperty("duration", 0); } }); @@ -2904,26 +2509,6 @@ Object.defineProperty(FORGE.VideoHls.prototype, "onQualityAbort", } }); -/** - * Get the "onMetricsChanged" event {@link FORGE.EventDispatcher} of the video. - * @name FORGE.VideoHls#onMetricChanged - * @readonly - * @type {FORGE.EventDispatcher} - */ -Object.defineProperty(FORGE.VideoHls.prototype, "onMetricsChanged", -{ - /** @this {FORGE.VideoHls} */ - get: function() - { - if (this._onMetricsChanged === null) - { - this._onMetricsChanged = new FORGE.EventDispatcher(this); - } - - return this._onMetricsChanged; - } -}); - /** * Get the "onQualitiesLoaded" event {@link FORGE.EventDispatcher} of the video. * @name FORGE.VideoHls#onQualitiesLoaded From fc0d6fb67dbdf6bad6f0718192ca55bd9a6093fe Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Mon, 4 Dec 2017 14:54:58 +0100 Subject: [PATCH 10/19] Add a check on BackgroundRenderer quality change handler for video media --- src/render/RenderManager.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/render/RenderManager.js b/src/render/RenderManager.js index 2caba804..abe61043 100644 --- a/src/render/RenderManager.js +++ b/src/render/RenderManager.js @@ -432,7 +432,10 @@ FORGE.RenderManager.prototype._mediaQualityChangeHandler = function(event) { this.log("Media quality has changed"); - this._backgroundRenderer.displayObject = event.emitter; + if (this._backgroundRenderer !== null) + { + this._backgroundRenderer.displayObject = event.emitter; + } }; /** From ff63266f4be70fb01c6978b309806129bafb1e12 Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Mon, 4 Dec 2017 14:55:55 +0100 Subject: [PATCH 11/19] Add quality management through event data object with -1 level add for auto levels --- src/display/video/VideoHls.js | 68 ++++++++++++++++++++--------------- 1 file changed, 40 insertions(+), 28 deletions(-) diff --git a/src/display/video/VideoHls.js b/src/display/video/VideoHls.js index 4469d08b..2717f675 100644 --- a/src/display/video/VideoHls.js +++ b/src/display/video/VideoHls.js @@ -623,7 +623,7 @@ FORGE.VideoHls.prototype._initHlsMediaPlayer = function() var config = { autoStartLoad: true, // start after Hls.Events.MANIFEST_PARSED startPosition : -1, // startTime - debug: true, + debug: false, startLevel: undefined, enableWebVTT: true, enableCEA708Captions: true, @@ -1036,63 +1036,74 @@ FORGE.VideoHls.prototype._indexOfQuality = function(quality) /** * Private event handler for period switch completed. * @method FORGE.VideoHls#_onSwitchCompletedHandler - * @param {Object} event - The hls.js media player event. + * @param {string} event - The hls.js media player event. + * @param {Object} data - The hls.js media player event data. * @private */ -FORGE.VideoHls.prototype._onSwitchCompletedHandler = function(event) +FORGE.VideoHls.prototype._onSwitchCompletedHandler = function(event, data) { var element = this._video.element; this.log("_onSwitchCompleted [readyState: " + element.readyState + "]"); - // new level is event.data.level; + // new level is event.data.level reported to onQualityChange; + this._onQualityChangeHandler(event, data); }; /** * Private event handler for quality change. * @method FORGE.VideoHls#_onQualityChangeHandler * @private - * @param {Object} event - The hls.js media player event. + * @param {string} event - The hls.js media player event. + * @param {Object} data - The hls.js media player event data. */ -FORGE.VideoHls.prototype._onQualityChangeHandler = function(event) +FORGE.VideoHls.prototype._onQualityChangeHandler = function(event, data) { var element = this._video.element; this.log("onQualityChange [readyState: " + element.readyState + "]"); - // this._currentIndex = event.data.level; - // this._currentPendingIndex = event.data.level; + if (this._currentIndex !== data.level) + { + this._currentIndex = data.level; + this._currentPendingIndex = data.level; - // if (this._onQualityChange !== null) - // { - // this._onQualityChange.dispatch(this._currentIndex); - // } + if (this._onQualityChange !== null) + { + this._onQualityChange.dispatch(this._currentIndex); + } + } }; /** * Private event handler for quality request. * @method FORGE.VideoHls#_onQualityRequestHandler * @private - * @param {Object} event - The hls.js media player event. + * @param {string} event - The hls.js media player event. + * @param {Object} data - The hls.js media player event data. */ -FORGE.VideoHls.prototype._onQualityRequestHandler = function(event) +FORGE.VideoHls.prototype._onQualityRequestHandler = function(event, data) { var element = this._video.element; this.log("onQualityRequest [readyState: " + element.readyState + "]"); - // this._currentPendingIndex = event.data.level; + if (this._currentPendingIndex !== data.level) + { + this._currentPendingIndex = data.level; - // if (this._onQualityRequest !== null) - // { - // this._onQualityRequest.dispatch(this._currentPendingIndex); - // } + if (this._onQualityRequest !== null) + { + this._onQualityRequest.dispatch(this._currentPendingIndex); + } + } }; /** * Private event handler for quality request aborted. * @method FORGE.VideoHls#_onQualityAbortHandler * @private - * @param {Object} event - The hls.js media player event. + * @param {string} event - The hls.js media player event. + * @param {Object} data - The hls.js media player event data. */ -FORGE.VideoHls.prototype._onQualityAbortHandler = function(event) +FORGE.VideoHls.prototype._onQualityAbortHandler = function(event, data) { var element = this._video.element; this.log("onQualityAbort [readyState: "+element.readyState+"]"); @@ -1206,7 +1217,6 @@ FORGE.VideoHls.prototype._setRequestQuality = function(index) if (this._hlsMediaPlayer !== null && this._isReady === true) { - // var streamIndex = this._streamId; var maxIndex = this._hlsMediaPlayer.levels.length; var newIndex = index; @@ -1215,12 +1225,14 @@ FORGE.VideoHls.prototype._setRequestQuality = function(index) { newIndex = maxIndex - 1; } - if (newIndex < 0) + + // return to auto level + if (newIndex <= -1) { - newIndex = 0; + newIndex = -1; } - this._hlsMediaPlayer.loadLevel(newIndex); + this._hlsMediaPlayer.nextLevel = newIndex; } // Update the volume for the requested video @@ -1249,11 +1261,11 @@ FORGE.VideoHls.prototype._setQualityMode = function(mode) { if (mode === FORGE.VideoQualityMode.MANUAL) { - this._hlsMediaPlayer.loadLevel(this._currentIndex); + this._hlsMediaPlayer.nextLevel = this._currentIndex; } else { - this._hlsMediaPlayer.loadLevel(-1); + this._hlsMediaPlayer.nextLevel = -1; } } @@ -1626,7 +1638,7 @@ Object.defineProperty(FORGE.VideoHls.prototype, "quality", /** @this {FORGE.VideoHls} */ set: function(value) { - if (typeof value === "number" && value >= 0 && value < this._qualities.length) + if (typeof value === "number" && value >= -1 && value < this._qualities.length) { this._setQualityMode(FORGE.VideoQualityMode.MANUAL); this._setRequestQuality(value); From f8f82b96d11705e1e724c7de454aeb46a9fc033e Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Mon, 4 Dec 2017 17:30:33 +0100 Subject: [PATCH 12/19] Manage error states (network and media errors) --- src/display/video/VideoHls.js | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/display/video/VideoHls.js b/src/display/video/VideoHls.js index 2717f675..b36074ec 100644 --- a/src/display/video/VideoHls.js +++ b/src/display/video/VideoHls.js @@ -399,6 +399,14 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) */ this._onSwitchCompletedBind = null; + /** + * Event handler for error. + * @name FORGE.VideoHls#_onErrorBind + * @type {Function} + * @private + */ + this._onErrorBind = null; + /** * Event handler for all events fired by the HTMLVideoElement. See https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events for a list of available events. * @name FORGE.VideoHls#_onEventBind @@ -468,6 +476,7 @@ FORGE.VideoHls.prototype._boot = function() this._onQualityRequestBind = this._onQualityRequestHandler.bind(this); this._onQualityChangeBind = this._onQualityChangeHandler.bind(this); this._onSwitchCompletedBind = this._onSwitchCompletedHandler.bind(this); + this._onErrorBind = this._onErrorHandler.bind(this); //Listen to the main volume change to adapt the video volume accordingly. this._viewer.audio.onVolumeChange.add(this._mainVolumeChangeHandler, this); @@ -704,6 +713,7 @@ FORGE.VideoHls.prototype._installEvents = function() this._hlsMediaPlayer.on(Hls.ErrorDetails.LEVEL_LOAD_ERROR, this._onQualityAbortBind); this._hlsMediaPlayer.on(Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT, this._onQualityAbortBind); this._hlsMediaPlayer.on(Hls.ErrorDetails.LEVEL_SWITCH_ERROR, this._onQualityAbortBind); + this._hlsMediaPlayer.on(Hls.Events.ERROR, this._onErrorBind); var element = this._video.element; @@ -757,6 +767,7 @@ FORGE.VideoHls.prototype._uninstallEvents = function() element.removeEventListener("playing", this._onEventBind, false); element.removeEventListener("ratechange", this._onEventBind, false); + this._hlsMediaPlayer.off(Hls.Events.ERROR, this._onErrorBind); this._hlsMediaPlayer.off(Hls.ErrorDetails.LEVEL_LOAD_ERROR, this._onQualityAbortBind); this._hlsMediaPlayer.off(Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT, this._onQualityAbortBind); this._hlsMediaPlayer.off(Hls.ErrorDetails.LEVEL_SWITCH_ERROR, this._onQualityAbortBind); @@ -963,6 +974,40 @@ FORGE.VideoHls.prototype._onEventHandler = function(event) } }; +/** + * Private event handler for HLS errors. + * @method FORGE.VideoHls#_onErrorHandler + * @param {string} event - The hls.js media player event. + * @param {Object} data - The hls.js media player event data. + * @private + */ +FORGE.VideoHls.prototype._onErrorHandler = function(event, data) +{ + var element = this._video.element; + this.log(event+" [readyState: " + element.readyState + "]"); + + if (data.fatal) + { + switch(data.type) + { + case Hls.ErrorTypes.NETWORK_ERROR: + // try to recover network error + this.log("Fatal network error encountered, try to recover"); + this._hlsMediaPlayer.startLoad(); + break; + case Hls.ErrorTypes.MEDIA_ERROR: + // try to recover a media error + this.log("Fatal media error encountered, try to recover"); + this._hlsMediaPlayer.recoverMediaError(); + break; + default: + // cannot recover + this.destroy(); + break; + } + } +}; + /** * Create a qualities array from the levels info list. * @method FORGE.VideoHls#_createQualitiesFromBitrateInfoList @@ -1589,6 +1634,7 @@ FORGE.VideoHls.prototype.destroy = function() this._onQualityModeChange = null; } + this._onErrorBind = null; this._onQualityRequestBind = null; this._onQualityChangeBind = null; this._onQualityAbortBind = null; From a5b8bf55dd557869fd4cb9dcffaa3f267d3fc09c Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Tue, 5 Dec 2017 16:16:12 +0100 Subject: [PATCH 13/19] Clean of VideoHls class --- src/display/video/VideoHls.js | 64 +++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 29 deletions(-) diff --git a/src/display/video/VideoHls.js b/src/display/video/VideoHls.js index b36074ec..a87e0d4e 100644 --- a/src/display/video/VideoHls.js +++ b/src/display/video/VideoHls.js @@ -122,7 +122,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) * The hls.js Media Player library.<br> * The hls.js library must be loaded prior to the video instanciation! * @name FORGE.VideoHls#_hlsMediaPlayer - * @type {Hls.MediaPlayer} + * @type {Hls} * @private */ this._hlsMediaPlayer = null; @@ -130,7 +130,7 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) /** * Is the hls.js Media Player ready? * @name FORGE.VideoHls#_isReady - * @type {Hls.MediaPlayer} + * @type {boolean} * @private */ this._isReady = false; @@ -367,6 +367,22 @@ FORGE.VideoHls = function(viewer, key, config, qualityMode) */ this._onQualityModeChange = null; + /** + * Event handler for HLS source binded to this. + * @name FORGE.VideoHls#_loadHlsMediaPlayerSourceBind + * @type {Function} + * @private + */ + this._loadHlsMediaPlayerSourceBind = null; + + /** + * Event handler for hls manifest parsed binded to this. + * @name FORGE.VideoHls#_launchHlsMediaPlayerBind + * @type {Function} + * @private + */ + this._launchHlsMediaPlayerBind; + /** * Event handler for current video quality request binded to this. * @name FORGE.VideoHls#_onQualityRequestBind @@ -1012,30 +1028,30 @@ FORGE.VideoHls.prototype._onErrorHandler = function(event, data) * Create a qualities array from the levels info list. * @method FORGE.VideoHls#_createQualitiesFromBitrateInfoList * @param {string} url - The manifest url. - * @param {Array<Level>} levels - The levels array. + * @param {Array<Hls.Level>} levels - The levels array. * @param {boolean=} checkURL - URL must be checked? * @return {Array<FORGE.VideoQuality>} The qualities array. * @private */ -FORGE.VideoHls.prototype._createQualitiesFromBitrateInfoList = function(url, bitrates, checkURL) +FORGE.VideoHls.prototype._createQualitiesFromBitrateInfoList = function(url, levels, checkURL) { var qualities = []; var quality; - if (bitrates !== null) + if (levels !== null) { - for (var i = 0, ii = bitrates.length; i < ii; i++) + for (var i = 0, ii = levels.length; i < ii; i++) { - if (checkURL === true && typeof bitrates[i].url !== undefined && FORGE.URL.isValid(bitrates[i].url[0]) === false) + if (checkURL === true && typeof levels[i].url !== undefined && FORGE.URL.isValid(levels[i].url[0]) === false) { throw "FORGE.Video: URL " + url + " is invalid"; } - quality = new FORGE.VideoQuality(bitrates[i].url[0]); + quality = new FORGE.VideoQuality(levels[i].url[0]); quality.id = i; - quality.bitrate = bitrates[i].bitrate; - quality.width = bitrates[i].width; - quality.height = bitrates[i].height; + quality.bitrate = levels[i].bitrate; + quality.width = levels[i].width; + quality.height = levels[i].height; qualities.push(quality); } @@ -1145,10 +1161,8 @@ FORGE.VideoHls.prototype._onQualityRequestHandler = function(event, data) * Private event handler for quality request aborted. * @method FORGE.VideoHls#_onQualityAbortHandler * @private - * @param {string} event - The hls.js media player event. - * @param {Object} data - The hls.js media player event data. */ -FORGE.VideoHls.prototype._onQualityAbortHandler = function(event, data) +FORGE.VideoHls.prototype._onQualityAbortHandler = function() { var element = this._video.element; this.log("onQualityAbort [readyState: "+element.readyState+"]"); @@ -1178,6 +1192,10 @@ FORGE.VideoHls.prototype._destroyVideo = function() element.pause(); this._hlsMediaPlayer.stopLoad(); + + this._hlsMediaPlayer.off(Hls.Events.MEDIA_ATTACHED, this._loadHlsMediaPlayerSourceBind); + this._hlsMediaPlayer.off(Hls.Events.MANIFEST_PARSED, this._launchHlsMediaPlayerBind); + this._hlsMediaPlayer.detachMedia(); this._hlsMediaPlayer.destroy(); } @@ -1634,11 +1652,14 @@ FORGE.VideoHls.prototype.destroy = function() this._onQualityModeChange = null; } + this._onEventBind = null; this._onErrorBind = null; this._onQualityRequestBind = null; this._onQualityChangeBind = null; this._onQualityAbortBind = null; this._onSwitchCompletedBind = null; + this._loadHlsMediaPlayerSourceBind = null; + this._launchHlsMediaPlayerBind = null; //Unbind main volume event this._viewer.audio.onVolumeChange.remove(this._mainVolumeChangeHandler, this); @@ -1654,20 +1675,6 @@ FORGE.VideoHls.prototype.destroy = function() FORGE.VideoBase.prototype.destroy.call(this); }; -/** - * Get the monitoring object related to the video. - * @name FORGE.VideoHls#monitoring - * @type {Object} - */ -Object.defineProperty(FORGE.VideoHls.prototype, "monitoring", -{ - /** @this {FORGE.VideoHls} */ - get: function() - { - return this._monitoring; - } -}); - /** * Get and set the quality index of the video. * @name FORGE.VideoHls#quality @@ -1900,7 +1907,6 @@ Object.defineProperty(FORGE.VideoHls.prototype, "currentTime", /** @this {FORGE.VideoHls} */ get: function() { - // return this._hlsMediaPlayer.time(); return this._getCurrentVideoElementProperty("currentTime", 0); }, From e8e4d06d29808d0407a50d3eb82c472f8117bfbf Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Tue, 5 Dec 2017 16:16:34 +0100 Subject: [PATCH 14/19] Add hls.js externs for minification --- externs/lib/hls.ext.js | 696 ++++++++++++++++++++++++++++------------- 1 file changed, 487 insertions(+), 209 deletions(-) diff --git a/externs/lib/hls.ext.js b/externs/lib/hls.ext.js index ed06386d..85b3f444 100644 --- a/externs/lib/hls.ext.js +++ b/externs/lib/hls.ext.js @@ -3,341 +3,619 @@ * Only include used methods from hls.js. */ -/** - * @const - */ -var Hls = {}; - - -/* -.attachMedia(video) -.on(event, function) -.loadSource(url) - -Hls.Events.MEDIA_ATTACHED -Hls.Events.MANIFEST_PARSED - - - - - - - */ - - /** * @constructor - * @return {!MediaPlayer} + * @param {Hls.Config} config + * @return {!Hls} */ -// function MediaPlayer() {}; +function Hls(config) {}; /** - * @param {HTMLMediaElement=} video - * @param {HTMLSourceElement=} source - * @param {Object=} context - * @return {MediaPlayer|null} + * @return {boolean} */ -// MediaPlayer.prototype.create = function(video, source, context) {}; +Hls.isSupported = function() {}; /** - * @param {HTMLMediaElement=} view - Optional arg to set the video element. - * @param {string=} source - Optional arg to set the media source. - * @param {boolean=} AutoPlay - Optional arg to set auto play. + * @type {string} */ -// MediaPlayer.prototype.initialize = function(view, source, AutoPlay) {}; +Hls.version; /** - * @param {boolean} value + * @type {Array} */ -// MediaPlayer.prototype.setAutoPlay = function(value) {}; +Hls.DefaultConfig; /** - * @param {Object} element + * @return {undefined} */ -// MediaPlayer.prototype.attachView = function(element) {}; +Hls.prototype.destroy = function() {}; /** - * @param {(string|Object)} urlOrManifest + * @param {HTMLVideoElement} media + * @return {undefined} */ -// MediaPlayer.prototype.attachSource = function(urlOrManifest) {}; +Hls.prototype.attachMedia = function(media) {}; /** - * @return {boolean} + * @return {undefined} */ -// MediaPlayer.prototype.isReady = function() {}; - -// MediaPlayer.prototype.play = function() {}; - -// MediaPlayer.prototype.pause = function() {}; - -// MediaPlayer.prototype.reset = function() {}; +Hls.prototype.detachMedia = function() {}; /** - * @param {boolean} value + * @param {string} url + * @return {undefined} */ -// MediaPlayer.prototype.setMute = function(value) {}; +Hls.prototype.loadSource = function(url) {}; /** - * @param {number} value + * @param {number=} startPosition + * @return {undefined} */ -// MediaPlayer.prototype.setVolume = function(value) {}; +Hls.prototype.startLoad = function(startPosition) {}; /** - * @param {number} value + * @return {undefined} */ -// MediaPlayer.prototype.seek = function(value) {}; +Hls.prototype.stopLoad = function() {}; /** - * @param {string=} streamId + * @return {undefined} */ -// MediaPlayer.prototype.time = function(streamId) {}; +Hls.prototype.swapAudioCodec = function() {}; /** - * @return {number} + * @return {undefined} */ -// MediaPlayer.prototype.duration = function() {}; +Hls.prototype.recoverMediaError = function() {}; /** - * @param {string} type - {@link MediaPlayerEvents} - * @param {Function} listener - callback method when the event fires. - * @param {Object=} scope - context of the listener so it can be removed properly. + * @type {Array<Hls.Level>} */ -// MediaPlayer.prototype.on = function(type, listener, scope) {}; +Hls.prototype.levels; /** - * @param {string} type - {@link MediaPlayerEvents} - * @param {Function} listener - callback method when the event fires. - * @param {Object=} scope - context of the listener so it can be removed properly. + * @type {number} */ -// MediaPlayer.prototype.off = function(type, listener, scope) {}; +Hls.prototype.currentLevel; /** - * @return {Debug} + * @type {number} */ -// MediaPlayer.prototype.getDebug = function() {}; +Hls.prototype.nextLevel; /** - * @return {DashMetrics} + * @type {number} */ -// MediaPlayer.prototype.getDashMetrics = function() {}; +Hls.prototype.loadLevel; /** - * @param {string} type - * @return {Object} + * @type {number} */ -// MediaPlayer.prototype.getMetricsFor = function(type) {}; +Hls.prototype.nextLoadLevel; /** - * @param {string} type - * @return {number} + * @type {number} */ -// MediaPlayer.prototype.getQualityFor = function(type) {}; +Hls.prototype.firstLevel; /** - * @param {string} type - * @param {number} value + * @type {number} */ -// MediaPlayer.prototype.setQualityFor = function(type, value) {}; +Hls.prototype.startLevel; /** - * @param {string} type - * @return {Array} + * @type {number} */ -// MediaPlayer.prototype.getBitrateInfoListFor = function(type) {}; +Hls.prototype.autoLevelCapping; /** - * @param {string} type - 'audio' | 'video' - * @param {boolean} value - * @default {boolean} true + * @type {boolean} */ -// MediaPlayer.prototype.setAutoSwitchQualityFor = function(type, value) {}; +Hls.prototype.autoLevelEnabled; /** - * @param {boolean} value - * @default false + * @type {number} */ -// MediaPlayer.prototype.setFastSwitchEnabled = function(value) {}; +Hls.prototype.manualLevel; /** - * @param {boolean} value - * @default {boolean} true + * @type {number} */ -// MediaPlayer.prototype.setScheduleWhilePaused = function(value) {}; +Hls.prototype.minAutoLevel; /** - * @param {boolean} value - * @default false + * @type {number} */ -// MediaPlayer.prototype.enableBufferOccupancyABR = function(value) {}; +Hls.prototype.maxAutoLevel; /** - * @constructor - * @return {!MediaPlayerEvents} - */ -// function MediaPlayerEvents() {}; - -// MediaPlayerEvents.prototype.CAN_PLAY; -// MediaPlayerEvents.prototype.ERROR; -// MediaPlayerEvents.prototype.PLAYBACK_ENDED; -// MediaPlayerEvents.prototype.PLAYBACK_ERROR; -// MediaPlayerEvents.prototype.PLAYBACK_METADATA_LOADED; -// MediaPlayerEvents.prototype.PLAYBACK_PAUSED; -// MediaPlayerEvents.prototype.PLAYBACK_PROGRESS; -// MediaPlayerEvents.prototype.PLAYBACK_SEEKED; -// MediaPlayerEvents.prototype.PLAYBACK_STARTED; -// MediaPlayerEvents.prototype.PLAYBACK_TIME_UPDATED; -// MediaPlayerEvents.prototype.QUALITY_CHANGE_RENDERED; -// MediaPlayerEvents.prototype.QUALITY_CHANGE_REQUESTED; -// MediaPlayerEvents.prototype.STREAM_INITIALIZED; -// MediaPlayerEvents.prototype.PERIOD_SWITCH_COMPLETED; -// MediaPlayerEvents.prototype.METRIC_CHANGED; - -/** - * @constructor - * @return {!DashMetrics} + * @type {number} */ -// function DashMetrics() {}; - -// DashMetrics.prototype.getBandwidthForRepresentation = function(representationId, periodId) {}; +Hls.prototype.nextAutoLevel; /** - * @param {string} representationId - * @param {number} periodIdx - * @return {number} + * @type {Array} */ -// DashMetrics.prototype.getIndexForRepresentation = function(representationId, periodIdx) {}; +Hls.prototype.audioTracks; /** - * @param {string} bufferType - String 'audio' or 'video', - * @param {number} periodIdx - Make sure this is the period index not id - * @return {number} + * @type {number} */ -// DashMetrics.prototype.getMaxIndexForBufferType = function(bufferType, periodIdx) {}; +Hls.prototype.audioTrack; /** - * @param {Object} metrics - * @return {*} + * @type {number} */ -// DashMetrics.prototype.getCurrentRepresentationSwitch = function(metrics) {}; +Hls.prototype.liveSyncPosition; /** - * @param {Object} metrics - * @return {number} + * @type {Array} */ -// DashMetrics.prototype.getCurrentBufferLevel = function(metrics) {}; +Hls.prototype.subtitleTracks; /** - * @param {Object} metrics - * @return {null|*} + * @type {number} */ -// DashMetrics.prototype.getRequestsQueue = function(metrics) {}; +Hls.prototype.subtitleTrack; /** - * @param {Object} metrics - * @return {*} + * @typedef {{ + * url: string, + * responseType: string, + * type: string, + * rangeStart: (number|undefined), + * rangeEnd: (number|undefined), + * progressData: (boolean|undefined) + * }} */ -// DashMetrics.prototype.getHttpRequests = function(metrics) {}; +Hls.Context; /** - * @param {Object} metrics - * @return + * @typedef {{ + * autoStartLoad: (boolean|undefined), + * startPosition: (number|undefined), + * debug: (boolean|undefined), + * startLevel: (number|undefined), + * enableWebVTT: (boolean|undefined), + * enableCEA708Captions: (boolean|undefined), + * stretchShortVideoTrack: (boolean|undefined), + * maxAudioFramesDrift : (number|undefined), + * forceKeyFrameOnDiscontinuity: (boolean|undefined) + * }} */ -// DashMetrics.prototype.getCurrentDroppedFrames = function(metrics) {}; +Hls.Config; /** - * @constructor - * @return {!Debug} + * @typedef {{ + * context: Hls.Context, + * config: Hls.Config, + * callbacks: {onSuccess: function(), onProgress: function(), onError: function(), onTimeout: function()}, + * load: function(Object, Object, Object), + * abort: function(), + * destroy: function() + * }} */ -// function Debug() {}; +Hls.Loader; /** - * @param {boolean} value Set to false if you want to turn off logging to the browser's console. - * @default true - */ -// Debug.prototype.setLogToBrowserConsole = function(value) {}; + * @typedef {{ + * type: string, + * level: number, + * loader: Hls.Loader, + * autoLevel: boolean, + * duration: number, + * sn: (number|string), + * bitrateTest: boolean, + * loadCounter: number, + * cc: number, + * loadIdx: number, + * decryptdata: ({uri: string, key: Object}|undefined), + * start: number, + * dropped: number, + * startPTS: number, + * endPTS: number, + * startDTS: number, + * endDTS: number, + * deltaPTS: number, + * backtracked: boolean, + * trackId: number, + * byteLength: number, + * loaded: number, + * byteRangeStartOffset: number, + * byteRangeEndOffset: number, + * lastByteRangeEndOffset: number, + * rawByteRange: Array, + * rawProgramDateTime: Array, + * title: string, + * tagList: Array, + * levelkey: LevelKey, + * baseurl: string, + * relurl: string, + * url: string + * }} + */ +Hls.Fragment; + +/** + * @typedef {{ + * url: Array<string>, + * bitrate: (number|undefined), + * name: (string|undefined), + * codecs: (string|undefined), + * width: (number|undefined), + * height: (number|undefined) + * }} + */ +Hls.Level; + +/** + * @typedef {{ + * version: number, + * type: (string|undefined), + * startSN: number, + * endSN: number, + * totalduration: number, + * targetduration: number, + * fragments: Array<Hls.Fragment>, + * live: boolean + * }} + */ +Hls.LevelDetails; + +/** + * @typedef {{ + * trequest: number, + * tfirst: number, + * tload: number, + * loaded: number, + * bw: (number|undefined), + * total: (number|undefined) + * }} + */ +Hls.Stats; + +/** + * @typedef {{ + * code: number, + * text: string + * }} + */ +Hls.Response; + +/** + * @typedef {{ + * type: (string|undefined), + * details: (string|undefined), + * fatal: (boolean|undefined), + * url: (string|undefined), + * reason: (string|undefined), + * err: (Error|undefined), + * mimeType: (string|undefined), + * parent: (string|undefined), + * content: (string|undefined), + * hole: (number|undefined), + * id: (string|number|undefined), + * startOffset: (number|undefined), + * endOffset: (number|undefined), + * audioTracks: (Array|undefined), + * subtitleTracks: (Array|undefined), + * subtitles: (Array|undefined), + * media: (Element|undefined), + * pending: (number|undefined), + * currentDropped: (number|undefined), + * currentDecoded: (number|undefined), + * totalDroppedFrames: (number|undefined), + * level: (number|undefined), + * droppedLevel: (number|undefined), + * levels: (Array<Hls.Level>|undefined), + * firstLevel: (number|undefined), + * audio: (boolean|undefined), + * video: (boolean|undefined), + * altAudio: (boolean|undefined), + * data: (?|undefined), + * drift: (?|undefined), + * start: (number|undefined), + * end: (number|undefined), + * buffer: (number|undefined), + * previousState: (?|undefined), + * nextState: (?|undefined), + * success: (boolean|undefined), + * payload: (?|undefined), + * initPTS: (number|undefined), + * bytes: (number|undefined), + * response: (Hls.Response|undefined), + * loader: (Hls.Loader|undefined), + * frag: (Hls.Fragment|undefined), + * context: (Hls.Context|undefined), + * stats: (Hls.Stats|undefined) + * }} + */ +Hls.EventCallback; + +/** + * @param {string} event + * @param {?function(Object=, Hls.EventCallback=): void} callback + * @return {undefined} + */ +Hls.prototype.on = function(event, callback) {}; + +/** + * @param {string} event + * @param {?function(Object=, Hls.EventCallback=): void} callback + * @return {undefined} + */ +Hls.prototype.off = function(event, callback) {}; -/** - * @constructor - * @return {!MetricsList} - */ -// function MetricsList() {}; /** * @constructor - * @return {!StreamInfo} */ -// function StreamInfo() {}; +Hls.Events = function () {}; -// StreamInfo.prototype.id; -// StreamInfo.prototype.index; -// StreamInfo.prototype.start; -// StreamInfo.prototype.duration; -// StreamInfo.prototype.manifestinfo; -// StreamInfo.prototype.isLast; -// StreamInfo.prototype.isFirst; +/** @const {string} */ +Hls.Events.MEDIA_ATTACHING; -/** - * @constructor - * @return {!BitrateInfo} - */ -// function BitrateInfo() {}; +/** @const {string} */ +Hls.Events.MEDIA_ATTACHED; -// BitrateInfo.prototype.qualityIndex; -// BitrateInfo.prototype.bitrate; -// BitrateInfo.prototype.width; -// BitrateInfo.prototype.height; +/** @const {string} */ +Hls.Events.MEDIA_DETACHING; -/** - * @constructor - * @return {!DroppedFrames} - */ -// function DroppedFrames() {}; +/** @const {string} */ +Hls.Events.MEDIA_DETACHED; -// DroppedFrames.prototype.droppedFrames; +/** @const {string} */ +Hls.Events.BUFFER_RESET; -/** - * @constructor - * @return {!MetricChangedEvents} - */ -// function MetricChangedEvents() {}; +/** @const {string} */ +Hls.Events.BUFFER_CODECS; -// MetricChangedEvents.prototype.mediaType; +/** @const {string} */ +Hls.Events.BUFFER_CREATED; -/** - * @constructor - * @return {!SwitchEvents} - */ -// function SwitchEvents() {}; +/** @const {string} */ +Hls.Events.BUFFER_APPENDING; + +/** @const {string} */ +Hls.Events.BUFFER_APPENDED; + +/** @const {string} */ +Hls.Events.BUFFER_EOS; + +/** @const {string} */ +Hls.Events.BUFFER_FLUSHING; + +/** @const {string} */ +Hls.Events.BUFFER_FLUSHED; + +/** @const {string} */ +Hls.Events.MANIFEST_LOADING; + +/** @const {string} */ +Hls.Events.MANIFEST_LOADED; + +/** @const {string} */ +Hls.Events.MANIFEST_PARSED; + +/** @const {string} */ +Hls.Events.LEVEL_SWITCH; + +/** @const {string} */ +Hls.Events.LEVEL_SWITCHING; + +/** @const {string} */ +Hls.Events.LEVEL_SWITCHED; + +/** @const {string} */ +Hls.Events.LEVEL_LOADING; + +/** @const {string} */ +Hls.Events.LEVEL_LOADED; + +/** @const {string} */ +Hls.Events.LEVEL_UPDATED; + +/** @const {string} */ +Hls.Events.LEVEL_PTS_UPDATED; + +/** @const {string} */ +Hls.Events.AUDIO_TRACKS_UPDATED; + +/** @const {string} */ +Hls.Events.AUDIO_TRACK_SWITCH; + +/** @const {string} */ +Hls.Events.AUDIO_TRACK_SWITCHING; + +/** @const {string} */ +Hls.Events.AUDIO_TRACK_SWITCHED; + +/** @const {string} */ +Hls.Events.AUDIO_TRACK_LOADING; + +/** @const {string} */ +Hls.Events.AUDIO_TRACK_LOADED; + +/** @const {string} */ +Hls.Events.SUBTITLE_TRACKS_UPDATED; + +/** @const {string} */ +Hls.Events.SUBTITLE_TRACK_SWITCH; + +/** @const {string} */ +Hls.Events.SUBTITLE_TRACK_LOADING; + +/** @const {string} */ +Hls.Events.SUBTITLE_TRACK_LOADED; + +/** @const {string} */ +Hls.Events.SUBTITLE_FRAG_PROCESSED; + +/** @const {string} */ +Hls.Events.INIT_PTS_FOUND; + +/** @const {string} */ +Hls.Events.FRAG_LOADING; + +/** @const {string} */ +Hls.Events.FRAG_LOAD_PROGRESS; + +/** @const {string} */ +Hls.Events.FRAG_LOAD_EMERGENCY_ABORTED; + +/** @const {string} */ +Hls.Events.FRAG_LOADED; + +/** @const {string} */ +Hls.Events.FRAG_DECRYPTED; + +/** @const {string} */ +Hls.Events.FRAG_PARSING_INIT_SEGMENT; + +/** @const {string} */ +Hls.Events.FRAG_PARSING_USERDATA; + +/** @const {string} */ +Hls.Events.FRAG_PARSING_METADATA; + +/** @const {string} */ +Hls.Events.FRAG_PARSING_DATA; + +/** @const {string} */ +Hls.Events.FRAG_PARSED; + +/** @const {string} */ +Hls.Events.FRAG_BUFFERED; + +/** @const {string} */ +Hls.Events.FRAG_CHANGED; + +/** @const {string} */ +Hls.Events.FPS_DROP; + +/** @const {string} */ +Hls.Events.FPS_DROP_LEVEL_CAPPING; + +/** @const {string} */ +Hls.Events.ERROR; + +/** @const {string} */ +Hls.Events.DESTROYING; + +/** @const {string} */ +Hls.Events.KEY_LOADING; + +/** @const {string} */ +Hls.Events.KEY_LOADED; + +/** @const {string} */ +Hls.Events.STREAM_STATE_TRANSITION; -// SwitchEvents.prototype.fromStreamInfo; -// SwitchEvents.prototype.toStreamInfo; /** * @constructor - * @return {!QualityEvents} */ -// function QualityEvents() {}; +Hls.ErrorTypes = function () {}; + +/** @const {string} */ +Hls.ErrorTypes.NETWORK_ERROR; + +/** @const {string} */ +Hls.ErrorTypes.MEDIA_ERROR; + +/** @const {string} */ +Hls.ErrorTypes.MUX_ERROR; + +/** @const {string} */ +Hls.ErrorTypes.OTHER_ERROR; -// QualityEvents.prototype.mediaType; -// QualityEvents.prototype.oldQuality; -// QualityEvents.prototype.newQuality; /** * @constructor - * @return {!RepresentationSwitch} */ -// function RepresentationSwitch() {}; +Hls.ErrorDetails = function () {}; -// RepresentationSwitch.prototype.mt; -// RepresentationSwitch.prototype.t; -// RepresentationSwitch.prototype.to; +/** @const {string} */ +Hls.ErrorDetails.MANIFEST_LOAD_ERROR; -/** - * @const - */ -// Hls.MediaPlayer = MediaPlayer; +/** @const {string} */ +Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT; + +/** @const {string} */ +Hls.ErrorDetails.MANIFEST_PARSING_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.LEVEL_LOAD_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT; + +/** @const {string} */ +Hls.ErrorDetails.LEVEL_SWITCH_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.AUDIO_TRACK_LOAD_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT; + +/** @const {string} */ +Hls.ErrorDetails.FRAG_LOAD_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.FRAG_LOAD_TIMEOUT; + +/** @const {string} */ +Hls.ErrorDetails.FRAG_DECRYPT_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.FRAG_PARSING_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.REMUX_ALLOC_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.KEY_LOAD_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.KEY_LOAD_TIMEOUT; + +/** @const {string} */ +Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.BUFFER_APPEND_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.BUFFER_APPENDING_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.BUFFER_STALLED_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.BUFFER_FULL_ERROR; + +/** @const {string} */ +Hls.ErrorDetails.BUFFER_SEEK_OVER_HOLE; + +/** @const {string} */ +Hls.ErrorDetails.BUFFER_NUDGE_ON_STALL; + +/** @const {string} */ +Hls.ErrorDetails.INTERNAL_EXCEPTION; + +/** @const {string} */ +Hls.ErrorDetails.WEBVTT_EXCEPTION; /** - * @const + * @constructor + * @return {!LevelKey} */ -// Hls.MediaPlayer.events = MediaPlayerEvents; \ No newline at end of file +function LevelKey() {}; + From 247258867e33dd70b3f4904d9bc3f7e9d86886f2 Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Wed, 24 Jan 2018 13:10:20 +0100 Subject: [PATCH 15/19] Update video check into Device class --- src/system/Device.js | 53 ++++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/src/system/Device.js b/src/system/Device.js index 7efdd2f3..a4292df6 100755 --- a/src/system/Device.js +++ b/src/system/Device.js @@ -134,6 +134,7 @@ FORGE.Device = (function(c) this._browser = "chrome"; if (/CriOS\/(\d+)/.test(this._ua)) { + this._safari = false; this._browserVersion = this._chromeVersion = parseInt(RegExp.$1, 10); } else if (/Chrome\/(\d+)/.test(this._ua)) @@ -266,32 +267,36 @@ FORGE.Device = (function(c) { if (typeof videoElement.canPlayType === "function") { - if (videoElement.canPlayType("video/ogg; codecs=\"theora\"").replace(/^no$/, "")) + if (videoElement.canPlayType("video/ogg")) { this._oggVideo = true; } - if (videoElement.canPlayType("video/mp4; codecs=\"avc1.42E01E\"").replace(/^no$/, "")) + if (videoElement.canPlayType("video/mp4")) { - // without QuickTime, this value will be "undefined" - this._h264Video = true; this._mp4Video = true; } - if (videoElement.canPlayType("video/webm; codecs=\"vp8, vorbis\"").replace(/^no$/, "")) + if (videoElement.canPlayType("video/webm")) { this._webmVideo = true; } - if (videoElement.canPlayType("video/webm; codecs=\"vp9\"").replace(/^no$/, "")) + if (videoElement.canPlayType("application/x-mpegURL") || videoElement.canPlayType("application/vnd.apple.mpegurl")) { - this._vp9Video = true; + this._hlsVideo = true; } - if (videoElement.canPlayType("application/x-mpegURL; codecs=\"avc1.42E01E\"").replace(/^no$/, "")) + // native support + if ((this._iOS === true && this._osVersion >= 8) || (this._os === "macosx" && this._browser === "safari" && this._browserVersion >= 8) || (this._android === true && this._osVersion >= 5 && this._browser === "chrome")) { this._hlsVideo = true; } + + if (videoElement.canPlayType("application/dash+xml")) + { + this._dashVideo = true; + } } } catch (e) @@ -399,7 +404,7 @@ FORGE.Device = (function(c) this._localStorage = false; } - this._mediaSource = (typeof window.MediaSource === "function"); + this._mediaSource = (typeof (window.MediaSource || window.WebKitMediaSource) === "function"); this._encryptedMedia = (typeof window.HTMLMediaElement === "function" && typeof window.MediaKeys === "function" && typeof window.MediaKeySystemAccess === "function" && typeof navigator.requestMediaKeySystemAccess === "function"); @@ -811,10 +816,10 @@ FORGE.Device = (function(c) this._checkOS(); this._checkBrowsers(); this._checkDevice(); - this._checkAudio(); - this._checkVideo(); this._checkDeviceFeatures(); this._checkFeatures(); + this._checkAudio(); + this._checkVideo(); this._checkEnvironment(); this._checkBrowserApi(); this._checkFullscreenSupport(); @@ -914,16 +919,16 @@ FORGE.Device = (function(c) /** * Check If the device can play video files. * @method FORGE.Device#canPlayVideo - * @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. + * @param {string} type - One of 'mp4, 'ogg', 'webm', 'mpeg/m3u8', 'mpd'. * @return {boolean} */ Tmp.prototype.canPlayVideo = function(type) { - if (type === "webm" && (this._webmVideo === true || this._vp9Video === true)) + if (type === "webm" && this._webmVideo === true) { return true; } - else if (type === "mp4" && (this._mp4Video === true || this._h264Video === true)) + else if ((type === "mp4" || type === "m4v" || type === "mov") && (this._mp4Video === true || this._h264Video === true)) { return true; } @@ -931,7 +936,11 @@ FORGE.Device = (function(c) { return true; } - else if (type === "mpeg" && this._hlsVideo === true) + else if ((type === "mpeg" || type === "m3u8" || type === "hls") && this._hlsVideo === true) + { + return true; + } + else if ((type === "mpd" || type === "dash") && this._dashVideo === true) { return true; } @@ -2032,16 +2041,16 @@ FORGE.Device = (function(c) }); /** - * Can play vp9 video files? - * @name FORGE.Device#vp9Video + * Can play Dash video files? + * @name FORGE.Device#dashVideo * @type {boolean} * @readonly */ - Object.defineProperty(Tmp.prototype, "vp9Video", + Object.defineProperty(Tmp.prototype, "dashVideo", { get: function() { - return this._vp9Video; + return this._dashVideo; } }); @@ -3206,12 +3215,12 @@ FORGE.Device = (function(c) this._webmVideo = false; /** - * Can play vp9 video files? - * @name FORGE.Device#_vp9Video + * Can play dash video files? + * @name FORGE.Device#_dashVideo * @type {boolean} * @private */ - this._vp9Video = false; + this._dashVideo = false; /** * Can play hls video files? From d9e452aea9ff331e7d9c009eb857bbda9cb3b50a Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Wed, 24 Jan 2018 13:14:00 +0100 Subject: [PATCH 16/19] Better check of video streaming ability for devices prior to HLS/DASH video classes instanciation --- src/media/Media.js | 70 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 55 insertions(+), 15 deletions(-) diff --git a/src/media/Media.js b/src/media/Media.js index 48b8a6fc..d66e5e93 100644 --- a/src/media/Media.js +++ b/src/media/Media.js @@ -243,15 +243,53 @@ FORGE.Media.prototype._parseConfig = function(config) return; } - if (typeof source.streaming !== "undefined" && source.streaming.toLowerCase() === FORGE.VideoFormat.DASH) + var streamFallback = false; + var streamVideoHTML5 = true; + + if (typeof source.streaming !== "undefined") { - this._displayObject = new FORGE.VideoDash(this._viewer, this._uid); + if (FORGE.Device.mediaSource === true) + { + // check the canPlayType ability for HLS or DASH if fallback is required + if (source.streaming.toLowerCase() === FORGE.VideoFormat.DASH) + { + streamVideoHTML5 = false; + this._displayObject = new FORGE.VideoDash(this._viewer, this._uid); + } + else if (source.streaming.toLowerCase() === FORGE.VideoFormat.HLS) + { + // check HLS native support prior any video class creation + if (FORGE.Device.canPlayVideo(FORGE.VideoFormat.HLS) === true) + { + streamVideoHTML5 = true; + } + else + { + streamVideoHTML5 = false; + this._displayObject = new FORGE.VideoHls(this._viewer, this._uid); + } + } + } + else + { + streamFallback = true; + } } - else if (typeof source.streaming !== "undefined" && source.streaming.toLowerCase() === FORGE.VideoFormat.HLS) + + // check the canPlayType ability for HLS or DASH if native fallback is required + if (streamFallback === true) { - this._displayObject = new FORGE.VideoHls(this._viewer, this._uid); + if ((source.streaming.toLowerCase() === FORGE.VideoFormat.HLS && FORGE.Device.canPlayVideo(FORGE.VideoFormat.HLS) === true) || (source.streaming.toLowerCase() === FORGE.VideoFormat.DASH && FORGE.Device.canPlayVideo(FORGE.VideoFormat.DASH) === true)) + { + streamVideoHTML5 = true; + } + else + { + streamVideoHTML5 = false; + } } - else + + if (streamVideoHTML5 === true) { var scene = this._viewer.story.scene; @@ -259,16 +297,18 @@ FORGE.Media.prototype._parseConfig = function(config) this._displayObject = new FORGE.VideoHTML5(this._viewer, this._uid, null, null, (scene.hasSoundTarget(this._uid) === true && scene.isAmbisonic() === true ? true : false)); } - // At this point, source.url is either a streaming address, a simple - // url, or an array of url - this._displayObject.load(source.url); - - this._displayObject.onLoadedMetaData.addOnce(this._onLoadedMetaDataHandler, this); - this._displayObject.onPlay.add(this._onPlayHandler, this); - this._displayObject.onPause.add(this._onPauseHandler, this); - this._displayObject.onSeeked.add(this._onSeekedHandler, this); - this._displayObject.onEnded.add(this._onEndedHandler, this); - + if (this._displayObject !== null) + { + // At this point, source.url is either a streaming address, a simple + // url, or an array of url + this._displayObject.load(source.url); + + this._displayObject.onLoadedMetaData.addOnce(this._onLoadedMetaDataHandler, this); + this._displayObject.onPlay.add(this._onPlayHandler, this); + this._displayObject.onPause.add(this._onPauseHandler, this); + this._displayObject.onSeeked.add(this._onSeekedHandler, this); + this._displayObject.onEnded.add(this._onEndedHandler, this); + } return; } From 53921d906054ded22ad0dc24c2c3ba637c71959c Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Wed, 24 Jan 2018 13:17:58 +0100 Subject: [PATCH 17/19] Apply DASH and HLS mime types to video qualities --- src/display/video/VideoQuality.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/display/video/VideoQuality.js b/src/display/video/VideoQuality.js index 67af0aa8..5d752170 100644 --- a/src/display/video/VideoQuality.js +++ b/src/display/video/VideoQuality.js @@ -97,16 +97,21 @@ FORGE.VideoQuality.mimeTypeFromURL = function(url) { var types = ["mp4", "webm", "ogg"]; var parsedURL = FORGE.URL.parse(url); - + if(parsedURL.extension !== "" && types.indexOf(parsedURL.extension) !== -1) { return "video/" + parsedURL.extension; } - var streamingTypes = ["mpd"]; - if(parsedURL.extension !== "" && streamingTypes.indexOf(parsedURL.extension) !== -1) + var streamingTypes = ["mpd", "m3u8"]; + var streamingMimeTypes = ["application/dash+xml", "application/x-mpegURL"]; + if(parsedURL.extension !== "") { - return "application/dash+xml"; + var index = streamingTypes.indexOf(parsedURL.extension); + if (index !== -1) + { + return streamingMimeTypes[index]; + } } return ""; @@ -118,7 +123,7 @@ FORGE.VideoQuality.mimeTypeFromURL = function(url) * @type {string|number} * @readonly */ -Object.defineProperty(FORGE.VideoQuality.prototype, "id", +Object.defineProperty(FORGE.VideoQuality.prototype, "id", { /** @this {FORGE.VideoQuality} */ get: function() From c497106431a7ae064805038465a8e7fce0f5b2ac Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Wed, 31 Jan 2018 16:48:47 +0100 Subject: [PATCH 18/19] Update device test for HLS native support --- src/system/Device.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/system/Device.js b/src/system/Device.js index a4292df6..a1caa3ee 100755 --- a/src/system/Device.js +++ b/src/system/Device.js @@ -288,7 +288,8 @@ FORGE.Device = (function(c) } // native support - if ((this._iOS === true && this._osVersion >= 8) || (this._os === "macosx" && this._browser === "safari" && this._browserVersion >= 8) || (this._android === true && this._osVersion >= 5 && this._browser === "chrome")) + // TODO: Android native support : (this._android === true && this._osVersion >= 5 && this._browser === "chrome") + if ((this._iOS === true && this._osVersion >= 8) || this._edge === true || (this._os === "macosx" && this._browser === "safari" && this._browserVersion >= 8)) { this._hlsVideo = true; } From fa9003bdd904f75cfe8ea35ec3fbd011b5bf4930 Mon Sep 17 00:00:00 2001 From: Benjamin Baudel <bbaudel@gopro.com> Date: Wed, 31 Jan 2018 16:49:43 +0100 Subject: [PATCH 19/19] Add specific check to apply hls.js with MSE for Android Chrome browsers --- src/media/Media.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/media/Media.js b/src/media/Media.js index d66e5e93..da24e4c8 100644 --- a/src/media/Media.js +++ b/src/media/Media.js @@ -259,7 +259,8 @@ FORGE.Media.prototype._parseConfig = function(config) else if (source.streaming.toLowerCase() === FORGE.VideoFormat.HLS) { // check HLS native support prior any video class creation - if (FORGE.Device.canPlayVideo(FORGE.VideoFormat.HLS) === true) + // and add specific Android Chrome condition to support hls.js with MSE + if (FORGE.Device.canPlayVideo(FORGE.VideoFormat.HLS) === true && ((FORGE.Device.android === true && FORGE.Device.osVersion >= 5 && FORGE.Device.browser === "chrome") !== true)) { streamVideoHTML5 = true; }