diff --git a/README.md b/README.md index 920c8a2f0..2fd176552 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ ![Streama Banner](design/banner2.png) -# STREAMA +# STREAMA - HLS Playback diff --git a/bower.json b/bower.json index 0cef882da..f90ddb1f0 100644 --- a/bower.json +++ b/bower.json @@ -17,6 +17,7 @@ ], "dependencies": { "alertify": "~0.3.10", + "hls.js": " 0.10.1", "angular-ui-router": "~0.*", "angular-local-storage": "~0.2.2", "bootstrap": "~3.3.5", diff --git a/build.gradle b/build.gradle index a8f9a5e78..41e40886a 100644 --- a/build.gradle +++ b/build.gradle @@ -84,6 +84,7 @@ dependencies { compile "org.grails.plugins:grails-spring-websocket:2.4.1" compile "eu.bitwalker:UserAgentUtils:1.21" compile "org.grails.plugins:spring-security-ldap:3.0.2" + compile "org.webjars.bowergithub.video-dev:hls.js:0.10.1" // runtime runtime "com.h2database:h2" diff --git a/grails-app/assets/bower/hls.js/dist/hls-demo.js b/grails-app/assets/bower/hls.js/dist/hls-demo.js new file mode 100644 index 000000000..f40ab9a46 --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls-demo.js @@ -0,0 +1,1528 @@ +(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["HlsDemo"] = factory(); + else + root["HlsDemo"] = 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 = 0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demo_utils__ = __webpack_require__(1); +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; }; + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + + +var testStreams = __webpack_require__(2); +var defaultTestStreamUrl = testStreams['bbb'].url; +var sourceURL = decodeURIComponent(getURLParam('src', defaultTestStreamUrl)); + +var demoConfig = getURLParam('demoConfig', null); +if (demoConfig) { + demoConfig = JSON.parse(atob(demoConfig)); +} else { + demoConfig = {}; +} + +var enableStreaming = getDemoConfigPropOrDefault('enableStreaming', true); +var autoRecoverError = getDemoConfigPropOrDefault('autoRecoverError', true); +var enableWorker = getDemoConfigPropOrDefault('enableWorker', true); +var levelCapping = getDemoConfigPropOrDefault('levelCapping', -1); +var limitMetrics = getDemoConfigPropOrDefault('limitMetrics', -1); +var defaultAudioCodec = getDemoConfigPropOrDefault('defaultAudioCodec', undefined); +var widevineLicenseUrl = getDemoConfigPropOrDefault('widevineLicenseURL', undefined); +var dumpfMP4 = getDemoConfigPropOrDefault('dumpfMP4', false); + +var bufferingIdx = -1; +var selectedTestStream = null; +var video = $('#video')[0]; +var startTime = Date.now(); + +var lastSeekingIdx = void 0; +var lastStartPosition = void 0; +var lastDuration = void 0; +var lastAudioTrackSwitchingIdx = void 0; +var hls = void 0; +var url = void 0; +var events = void 0; +var stats = void 0; +var tracks = void 0; +var fmp4Data = void 0; + +$(document).ready(function () { + Object.keys(testStreams).forEach(function (key) { + var stream = testStreams[key]; + var option = new Option(stream.description, key); + $('#streamSelect').append(option); + }); + + $('#streamSelect').change(function () { + selectedTestStream = testStreams[$('#streamSelect').val()]; + var streamUrl = selectedTestStream.url; + $('#streamURL').val(streamUrl); + loadSelectedStream(); + }); + + $('#streamURL').change(function () { + selectedTestStream = null; + loadSelectedStream(); + }); + + $('#videoSize').change(function () { + $('#video').width($('#videoSize').val()); + $('#bufferedCanvas').width($('#videoSize').val()); + }); + + $('#enableStreaming').click(function () { + enableStreaming = this.checked; + loadSelectedStream(); + }); + + $('#autoRecoverError').click(function () { + autoRecoverError = this.checked; + onDemoConfigChanged(); + }); + + $('#enableWorker').click(function () { + enableWorker = this.checked; + onDemoConfigChanged(); + }); + + $('#dumpfMP4').click(function () { + dumpfMP4 = this.checked; + onDemoConfigChanged(); + }); + + $('#limitMetrics').change(function () { + limitMetrics = this.value; + onDemoConfigChanged(); + }); + + $('#levelCapping').change(function () { + levelCapping = this.value; + onDemoConfigChanged(); + }); + + $('#defaultAudioCodec').change(function () { + defaultAudioCodec = this.value; + onDemoConfigChanged(); + }); + + $('#limitMetrics').val(limitMetrics); + $('#enableStreaming').prop('checked', enableStreaming); + $('#autoRecoverError').prop('checked', autoRecoverError); + $('#enableWorker').prop('checked', enableWorker); + $('#dumpfMP4').prop('checked', dumpfMP4); + $('#levelCapping').val(levelCapping); + $('#defaultAudioCodec').val(defaultAudioCodec || 'undefined'); + + $('h2').append(' v' + Hls.version + ''); + $('#currentVersion').html('Hls version:' + Hls.version); + + $('#streamURL').val(sourceURL); + + video.volume = 0.05; + + hideAllTabs(); + + $('#metricsButtonWindow').toggle(windowSliding); + $('#metricsButtonFixed').toggle(!windowSliding); + + loadSelectedStream(); +}); + +function setupGlobals() { + window.events = events = { + url: url, + t0: performance.now(), + load: [], + buffer: [], + video: [], + level: [], + bitrate: [] + }; + + // actual values, only on window + window.recoverDecodingErrorDate = null; + window.recoverSwapAudioCodecDate = null; + + window.fmp4Data = fmp4Data = { + 'audio': [], + 'video': [] + }; + + window.onClickBufferedRange = onClickBufferedRange; + + window.updateLevelInfo = updateLevelInfo; + window.onDemoConfigChanged = onDemoConfigChanged; + window.createfMP4 = createfMP4; + window.goToMetricsPermaLink = goToMetricsPermaLink; + window.toggleTab = toggleTab; + window.onDemoConfigChanged = onDemoConfigChanged; +} + +function trimArray(target, limit) { + if (limit < 0) { + return; + } + + while (target.length > limit) { + target.shift(); + } +} + +function trimEventHistory() { + var x = limitMetrics; + + if (x < 0) { + return; + } + + trimArray(events.load, x); + trimArray(events.buffer, x); + trimArray(events.video, x); + trimArray(events.level, x); + trimArray(events.bitrate, x); +} + +function loadSelectedStream() { + + if (!Hls.isSupported()) { + handleUnsupported(); + return; + } + + url = $('#streamURL').val(); + + setupGlobals(); + hideCanvas(); + + if (hls) { + hls.destroy(); + if (hls.bufferTimer) { + clearInterval(hls.bufferTimer); + hls.bufferTimer = undefined; + } + hls = null; + } + + if (!enableStreaming) { + logStatus('Streaming disabled'); + return; + } + + logStatus('Loading ' + url); + + if (widevineLicenseUrl) { + widevineLicenseUrl = unescape(widevineLicenseUrl); + } + + var hlsConfig = { + debug: true, + enableWorker: enableWorker, + defaultAudioCodec: defaultAudioCodec, + widevineLicenseUrl: widevineLicenseUrl + }; + + if (selectedTestStream && selectedTestStream.config) { + _extends(hlsConfig, selectedTestStream.config); + } + + if (hlsConfig.widevineLicenseUrl) { + $('#widevineLicenseUrl').val(hlsConfig.widevineLicenseUrl); + } + + widevineLicenseUrl = hlsConfig.widevineLicenseUrl = $('#widevineLicenseUrl').val(); + + if (hlsConfig.widevineLicenseUrl) { + hlsConfig.emeEnabled = true; + } + + onDemoConfigChanged(); + console.log('Using Hls.js config:', hlsConfig); + + window.hls = hls = new Hls(hlsConfig); + + logStatus('Loading manifest and attaching video element...'); + + hls.loadSource(url); + hls.autoLevelCapping = levelCapping; + hls.attachMedia(video); + + hls.on(Hls.Events.MEDIA_ATTACHED, function () { + logStatus('Media element attached'); + bufferingIdx = -1; + events.video.push({ + time: performance.now() - events.t0, + type: 'Media attached' + }); + trimEventHistory(); + }); + + hls.on(Hls.Events.MEDIA_DETACHED, function () { + logStatus('Media element detached'); + bufferingIdx = -1; + tracks = []; + events.video.push({ + time: performance.now() - events.t0, + type: 'Media detached' + }); + trimEventHistory(); + }); + + hls.on(Hls.Events.FRAG_PARSING_INIT_SEGMENT, function (event, data) { + showCanvas(); + var event = { + time: performance.now() - events.t0, + type: data.id + ' init segment' + }; + events.video.push(event); + trimEventHistory(); + }); + + hls.on(Hls.Events.FRAG_PARSING_METADATA, function (event, data) { + //console.log("Id3 samples ", data.samples); + }); + + hls.on(Hls.Events.LEVEL_SWITCHING, function (event, data) { + events.level.push({ + time: performance.now() - events.t0, + id: data.level, + bitrate: Math.round(hls.levels[data.level].bitrate / 1000) + }); + trimEventHistory(); + updateLevelInfo(); + }); + + hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) { + var event = { + type: 'manifest', + name: '', + start: 0, + end: data.levels.length, + time: data.stats.trequest - events.t0, + latency: data.stats.tfirst - data.stats.trequest, + load: data.stats.tload - data.stats.tfirst, + duration: data.stats.tload - data.stats.tfirst + }; + events.load.push(event); + trimEventHistory(); + refreshCanvas(); + }); + + hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) { + logStatus('No of quality levels found: ' + hls.levels.length); + logStatus('Manifest successfully loaded'); + stats = { + levelNb: data.levels.length, + levelParsed: 0 + }; + trimEventHistory(); + updateLevelInfo(); + }); + + hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, function (event, data) { + logStatus('No of audio tracks found: ' + data.audioTracks.length); + updateAudioTrackInfo(); + }); + + hls.on(Hls.Events.AUDIO_TRACK_SWITCHING, function (event, data) { + logStatus('Audio track switching...'); + updateAudioTrackInfo(); + var event = { + time: performance.now() - events.t0, + type: 'audio switching', + name: '@' + data.id + }; + events.video.push(event); + trimEventHistory(); + lastAudioTrackSwitchingIdx = events.video.length - 1; + }); + + hls.on(Hls.Events.AUDIO_TRACK_SWITCHED, function (event, data) { + logStatus('Audio track switched'); + updateAudioTrackInfo(); + var event = { + time: performance.now() - events.t0, + type: 'audio switched', + name: '@' + data.id + }; + if (lastAudioTrackSwitchingIdx !== undefined) { + events.video[lastAudioTrackSwitchingIdx].duration = event.time - events.video[lastAudioTrackSwitchingIdx].time; + lastAudioTrackSwitchingIdx = undefined; + } + events.video.push(event); + trimEventHistory(); + }); + + hls.on(Hls.Events.LEVEL_LOADED, function (event, data) { + events.isLive = data.details.live; + var event = { + type: 'level', + id: data.level, + start: data.details.startSN, + end: data.details.endSN, + time: data.stats.trequest - events.t0, + latency: data.stats.tfirst - data.stats.trequest, + load: data.stats.tload - data.stats.tfirst, + parsing: data.stats.tparsed - data.stats.tload, + duration: data.stats.tload - data.stats.tfirst + }; + var parsingDuration = data.stats.tparsed - data.stats.tload; + if (stats.levelParsed) { + this.sumLevelParsingMs += parsingDuration; + } else { + this.sumLevelParsingMs = parsingDuration; + } + + stats.levelParsed++; + stats.levelParsingUs = Math.round(1000 * this.sumLevelParsingMs / stats.levelParsed); + + //console.log('parsing level duration :' + stats.levelParsingUs + 'us,count:' + stats.levelParsed); + + events.load.push(event); + trimEventHistory(); + refreshCanvas(); + }); + + hls.on(Hls.Events.AUDIO_TRACK_LOADED, function (event, data) { + events.isLive = data.details.live; + var event = { + type: 'audio track', + id: data.id, + start: data.details.startSN, + end: data.details.endSN, + time: data.stats.trequest - events.t0, + latency: data.stats.tfirst - data.stats.trequest, + load: data.stats.tload - data.stats.tfirst, + parsing: data.stats.tparsed - data.stats.tload, + duration: data.stats.tload - data.stats.tfirst + }; + events.load.push(event); + trimEventHistory(); + refreshCanvas(); + }); + + hls.on(Hls.Events.FRAG_BUFFERED, function (event, data) { + var event = { + type: data.frag.type + ' fragment', + id: data.frag.level, + id2: data.frag.sn, + time: data.stats.trequest - events.t0, + latency: data.stats.tfirst - data.stats.trequest, + load: data.stats.tload - data.stats.tfirst, + parsing: data.stats.tparsed - data.stats.tload, + buffer: data.stats.tbuffered - data.stats.tparsed, + duration: data.stats.tbuffered - data.stats.tfirst, + bw: Math.round(8 * data.stats.total / (data.stats.tbuffered - data.stats.trequest)), + size: data.stats.total + }; + events.load.push(event); + events.bitrate.push({ + time: performance.now() - events.t0, + bitrate: event.bw, + duration: data.frag.duration, + level: event.id + }); + if (hls.bufferTimer === undefined) { + events.buffer.push({ + time: 0, + buffer: 0, + pos: 0 + }); + hls.bufferTimer = window.setInterval(checkBuffer, 100); + } + trimEventHistory(); + refreshCanvas(); + updateLevelInfo(); + + var latency = data.stats.tfirst - data.stats.trequest, + parsing = data.stats.tparsed - data.stats.tload, + process = data.stats.tbuffered - data.stats.trequest, + bitrate = Math.round(8 * data.stats.length / (data.stats.tbuffered - data.stats.tfirst)); + if (stats.fragBuffered) { + stats.fragMinLatency = Math.min(stats.fragMinLatency, latency); + stats.fragMaxLatency = Math.max(stats.fragMaxLatency, latency); + stats.fragMinProcess = Math.min(stats.fragMinProcess, process); + stats.fragMaxProcess = Math.max(stats.fragMaxProcess, process); + stats.fragMinKbps = Math.min(stats.fragMinKbps, bitrate); + stats.fragMaxKbps = Math.max(stats.fragMaxKbps, bitrate); + stats.autoLevelCappingMin = Math.min(stats.autoLevelCappingMin, hls.autoLevelCapping); + stats.autoLevelCappingMax = Math.max(stats.autoLevelCappingMax, hls.autoLevelCapping); + stats.fragBuffered++; + } else { + stats.fragMinLatency = stats.fragMaxLatency = latency; + stats.fragMinProcess = stats.fragMaxProcess = process; + stats.fragMinKbps = stats.fragMaxKbps = bitrate; + stats.fragBuffered = 1; + stats.fragBufferedBytes = 0; + stats.autoLevelCappingMin = stats.autoLevelCappingMax = hls.autoLevelCapping; + this.sumLatency = 0; + this.sumKbps = 0; + this.sumProcess = 0; + this.sumParsing = 0; + } + stats.fraglastLatency = latency; + this.sumLatency += latency; + stats.fragAvgLatency = Math.round(this.sumLatency / stats.fragBuffered); + stats.fragLastProcess = process; + this.sumProcess += process; + this.sumParsing += parsing; + stats.fragAvgProcess = Math.round(this.sumProcess / stats.fragBuffered); + stats.fragLastKbps = bitrate; + this.sumKbps += bitrate; + stats.fragAvgKbps = Math.round(this.sumKbps / stats.fragBuffered); + stats.fragBufferedBytes += data.stats.total; + stats.fragparsingKbps = Math.round(8 * stats.fragBufferedBytes / this.sumParsing); + stats.fragparsingMs = Math.round(this.sumParsing); + stats.autoLevelCappingLast = hls.autoLevelCapping; + }); + + hls.on(Hls.Events.LEVEL_SWITCHED, function (event, data) { + var event = { + time: performance.now() - events.t0, + type: 'level switched', + name: data.level + }; + events.video.push(event); + trimEventHistory(); + refreshCanvas(); + updateLevelInfo(); + }); + + hls.on(Hls.Events.FRAG_CHANGED, function (event, data) { + var event = { + time: performance.now() - events.t0, + type: 'frag changed', + name: data.frag.sn + ' @ ' + data.frag.level + }; + events.video.push(event); + trimEventHistory(); + refreshCanvas(); + updateLevelInfo(); + stats.tagList = data.frag.tagList; + + var level = data.frag.level, + autoLevel = data.frag.autoLevel; + if (stats.levelStart === undefined) { + stats.levelStart = level; + } + + if (autoLevel) { + if (stats.fragChangedAuto) { + stats.autoLevelMin = Math.min(stats.autoLevelMin, level); + stats.autoLevelMax = Math.max(stats.autoLevelMax, level); + stats.fragChangedAuto++; + if (this.levelLastAuto && level !== stats.autoLevelLast) { + stats.autoLevelSwitch++; + } + } else { + stats.autoLevelMin = stats.autoLevelMax = level; + stats.autoLevelSwitch = 0; + stats.fragChangedAuto = 1; + this.sumAutoLevel = 0; + } + this.sumAutoLevel += level; + stats.autoLevelAvg = Math.round(1000 * this.sumAutoLevel / stats.fragChangedAuto) / 1000; + stats.autoLevelLast = level; + } else { + if (stats.fragChangedManual) { + stats.manualLevelMin = Math.min(stats.manualLevelMin, level); + stats.manualLevelMax = Math.max(stats.manualLevelMax, level); + stats.fragChangedManual++; + if (!this.levelLastAuto && level !== stats.manualLevelLast) { + stats.manualLevelSwitch++; + } + } else { + stats.manualLevelMin = stats.manualLevelMax = level; + stats.manualLevelSwitch = 0; + stats.fragChangedManual = 1; + } + stats.manualLevelLast = level; + } + this.levelLastAuto = autoLevel; + }); + + hls.on(Hls.Events.FRAG_LOAD_EMERGENCY_ABORTED, function (event, data) { + if (stats) { + if (stats.fragLoadEmergencyAborted === undefined) { + stats.fragLoadEmergencyAborted = 1; + } else { + stats.fragLoadEmergencyAborted++; + } + } + }); + + hls.on(Hls.Events.FRAG_DECRYPTED, function (event, data) { + if (!stats.fragDecrypted) { + stats.fragDecrypted = 0; + this.totalDecryptTime = 0; + stats.fragAvgDecryptTime = 0; + } + stats.fragDecrypted++; + this.totalDecryptTime += data.stats.tdecrypt - data.stats.tstart; + stats.fragAvgDecryptTime = this.totalDecryptTime / stats.fragDecrypted; + }); + + hls.on(Hls.Events.ERROR, function (event, data) { + console.warn('Error event:', data); + switch (data.details) { + case Hls.ErrorDetails.MANIFEST_LOAD_ERROR: + try { + $('#errorOut').html('Cannot load ' + url + '
HTTP response code:' + data.response.code + '
' + data.response.text); + if (data.response.code === 0) { + $('#errorOut').append('This might be a CORS issue, consider installing Allow-Control-Allow-Origin Chrome Extension'); + } + } catch (err) { + $('#errorOut').html('Cannot load ' + url + '
Response body: ' + data.response.text); + } + break; + case Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT: + logError('Timeout while loading manifest'); + break; + case Hls.ErrorDetails.MANIFEST_PARSING_ERROR: + logError('Error while parsing manifest:' + data.reason); + break; + case Hls.ErrorDetails.LEVEL_LOAD_ERROR: + logError('Error while loading level playlist'); + break; + case Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT: + logError('Timeout while loading level playlist'); + break; + case Hls.ErrorDetails.LEVEL_SWITCH_ERROR: + logError('Error while trying to switch to level ' + data.level); + break; + case Hls.ErrorDetails.FRAG_LOAD_ERROR: + logError('Error while loading fragment ' + data.frag.url); + break; + case Hls.ErrorDetails.FRAG_LOAD_TIMEOUT: + logError('Timeout while loading fragment ' + data.frag.url); + break; + case Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR: + logError('Fragment-loop loading error'); + break; + case Hls.ErrorDetails.FRAG_DECRYPT_ERROR: + logError('Decrypting error:' + data.reason); + break; + case Hls.ErrorDetails.FRAG_PARSING_ERROR: + logError('Parsing error:' + data.reason); + break; + case Hls.ErrorDetails.KEY_LOAD_ERROR: + logError('Error while loading key ' + data.frag.decryptdata.uri); + break; + case Hls.ErrorDetails.KEY_LOAD_TIMEOUT: + logError('Timeout while loading key ' + data.frag.decryptdata.uri); + break; + case Hls.ErrorDetails.BUFFER_APPEND_ERROR: + logError('Buffer append error'); + break; + case Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR: + logError('Buffer add codec error for ' + data.mimeType + ':' + data.err.message); + break; + case Hls.ErrorDetails.BUFFER_APPENDING_ERROR: + logError('Buffer appending error'); + break; + case Hls.ErrorDetails.BUFFER_STALLED_ERROR: + logError('Buffer stalled error'); + break; + default: + break; + } + if (data.fatal) { + console.error('Fatal error :' + data.details); + switch (data.type) { + case Hls.ErrorTypes.MEDIA_ERROR: + handleMediaError(); + break; + case Hls.ErrorTypes.NETWORK_ERROR: + logError('A network error occured'); + break; + default: + logError('An unrecoverable error occured'); + hls.destroy(); + break; + } + } + if (!stats) { + stats = {}; + } + // track all errors independently + if (stats[data.details] === undefined) { + stats[data.details] = 1; + } else { + stats[data.details] += 1; + } + + // track fatal error + if (data.fatal) { + if (stats.fatalError === undefined) { + stats.fatalError = 1; + } else { + stats.fatalError += 1; + } + } + $('#statisticsOut').text(JSON.stringify(Object(__WEBPACK_IMPORTED_MODULE_0__demo_utils__["b" /* sortObject */])(stats), null, '\t')); + }); + + hls.on(Hls.Events.BUFFER_CREATED, function (event, data) { + tracks = data.tracks; + }); + + hls.on(Hls.Events.BUFFER_APPENDING, function (event, data) { + if (dumpfMP4) { + fmp4Data[data.type].push(data.data); + } + }); + + hls.on(Hls.Events.FPS_DROP, function (event, data) { + var evt = { + time: performance.now() - events.t0, + type: 'frame drop', + name: data.currentDropped + '/' + data.currentDecoded + }; + events.video.push(evt); + trimEventHistory(); + if (stats) { + if (stats.fpsDropEvent === undefined) { + stats.fpsDropEvent = 1; + } else { + stats.fpsDropEvent++; + } + + stats.fpsTotalDroppedFrames = data.totalDroppedFrames; + } + }); + + video.addEventListener('resize', handleVideoEvent); + video.addEventListener('seeking', handleVideoEvent); + video.addEventListener('seeked', handleVideoEvent); + video.addEventListener('pause', handleVideoEvent); + video.addEventListener('play', handleVideoEvent); + video.addEventListener('canplay', handleVideoEvent); + video.addEventListener('canplaythrough', handleVideoEvent); + video.addEventListener('ended', handleVideoEvent); + video.addEventListener('playing', handleVideoEvent); + video.addEventListener('error', handleVideoEvent); + video.addEventListener('loadedmetadata', handleVideoEvent); + video.addEventListener('loadeddata', handleVideoEvent); + video.addEventListener('durationchange', handleVideoEvent); +} + +function handleUnsupported() { + if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) { + logStatus('You are using Firefox, it looks like MediaSource is not enabled,
please ensure the following keys are set appropriately in about:config
media.mediasource.enabled=true
media.mediasource.mp4.enabled=true
media.mediasource.whitelist=false'); + } else { + logStatus('Your Browser does not support MediaSourceExtension / MP4 mediasource'); + } +} + +function handleVideoEvent(evt) { + var data = ''; + switch (evt.type) { + case 'durationchange': + if (evt.target.duration - lastDuration <= 0.5) { + // some browsers report several duration change events with almost the same value ... avoid spamming video events + return; + } + lastDuration = evt.target.duration; + data = Math.round(evt.target.duration * 1000); + break; + case 'resize': + data = evt.target.videoWidth + '/' + evt.target.videoHeight; + break; + case 'loadedmetadata': + case 'loadeddata': + case 'canplay': + case 'canplaythrough': + case 'ended': + case 'seeking': + case 'seeked': + case 'play': + case 'playing': + lastStartPosition = evt.target.currentTime; + case 'pause': + case 'waiting': + case 'stalled': + case 'error': + data = Math.round(evt.target.currentTime * 1000); + if (evt.type === 'error') { + var errorTxt = void 0, + mediaError = evt.currentTarget.error; + switch (mediaError.code) { + case mediaError.MEDIA_ERR_ABORTED: + errorTxt = 'You aborted the video playback'; + break; + case mediaError.MEDIA_ERR_DECODE: + errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support'; + handleMediaError(); + break; + case mediaError.MEDIA_ERR_NETWORK: + errorTxt = 'A network error caused the video download to fail part-way'; + break; + case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED: + errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported'; + break; + } + + if (mediaError.message) { + errorTxt += ' - ' + mediaError.message; + } + + logStatus(errorTxt); + console.error(errorTxt); + } + break; + default: + break; + } + + var event = { + time: performance.now() - events.t0, + type: evt.type, + name: data + }; + + events.video.push(event); + if (evt.type === 'seeking') { + lastSeekingIdx = events.video.length - 1; + } + + if (evt.type === 'seeked') { + events.video[lastSeekingIdx].duration = event.time - events.video[lastSeekingIdx].time; + } + + trimEventHistory(); +} + +function handleMediaError() { + if (autoRecoverError) { + var now = performance.now(); + if (!recoverDecodingErrorDate || now - recoverDecodingErrorDate > 3000) { + recoverDecodingErrorDate = performance.now(); + $('#statusOut').append(', trying to recover media error.'); + hls.recoverMediaError(); + } else { + if (!recoverSwapAudioCodecDate || now - recoverSwapAudioCodecDate > 3000) { + recoverSwapAudioCodecDate = performance.now(); + $('#statusOut').append(', trying to swap audio codec and recover media error.'); + hls.swapAudioCodec(); + hls.recoverMediaError(); + } else { + $('#statusOut').append(', cannot recover. Last media error recovery failed.'); + } + } + } +} + +function timeRangesToString(r) { + var log = ''; + for (var i = 0; i < r.length; i++) { + log += '[' + r.start(i) + ', ' + r.end(i) + ']'; + log += ' '; + } + return log; +} + +function checkBuffer() { + var v = $('#video')[0]; + var canvas = $('#bufferedCanvas')[0]; + var ctx = canvas.getContext('2d'); + var r = v.buffered; + var bufferingDuration = void 0; + ctx.fillStyle = 'black'; + ctx.fillRect(0, 0, canvas.width, canvas.height); + ctx.fillStyle = 'gray'; + if (r) { + if (!canvas.width || canvas.width !== v.clientWidth) { + canvas.width = v.clientWidth; + } + + var pos = v.currentTime, + bufferLen; + for (var i = 0, bufferLen = 0; i < r.length; i++) { + var start = r.start(i) / v.duration * canvas.width; + var end = r.end(i) / v.duration * canvas.width; + ctx.fillRect(start, 3, Math.max(2, end - start), 10); + if (pos >= r.start(i) && pos < r.end(i)) { + // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length + bufferLen = r.end(i) - pos; + } + } + // check if we are in buffering / or playback ended state + if (bufferLen <= 0.1 && v.paused === false && pos - lastStartPosition > 0.5) { + // don't create buffering event if we are at the end of the playlist, don't report ended for live playlist + if (lastDuration - pos <= 0.5 && events.isLive === false) {} else { + // we are not at the end of the playlist ... real buffering + if (bufferingIdx !== -1) { + bufferingDuration = performance.now() - events.t0 - events.video[bufferingIdx].time; + events.video[bufferingIdx].duration = bufferingDuration; + events.video[bufferingIdx].name = bufferingDuration; + } else { + events.video.push({ + type: 'buffering', + time: performance.now() - events.t0 + }); + trimEventHistory(); + // we are in buffering state + bufferingIdx = events.video.length - 1; + } + } + } + + if (bufferLen > 0.1 && bufferingIdx != -1) { + bufferingDuration = performance.now() - events.t0 - events.video[bufferingIdx].time; + events.video[bufferingIdx].duration = bufferingDuration; + events.video[bufferingIdx].name = bufferingDuration; + // we are out of buffering state + bufferingIdx = -1; + } + + // update buffer/position for current Time + var event = { + time: performance.now() - events.t0, + buffer: Math.round(bufferLen * 1000), + pos: Math.round(pos * 1000) + }; + var bufEvents = events.buffer, + bufEventLen = bufEvents.length; + if (bufEventLen > 1) { + var event0 = bufEvents[bufEventLen - 2], + event1 = bufEvents[bufEventLen - 1]; + var slopeBuf0 = (event0.buffer - event1.buffer) / (event0.time - event1.time); + var slopeBuf1 = (event1.buffer - event.buffer) / (event1.time - event.time); + + var slopePos0 = (event0.pos - event1.pos) / (event0.time - event1.time); + var slopePos1 = (event1.pos - event.pos) / (event1.time - event.time); + // compute slopes. if less than 30% difference, remove event1 + if ((slopeBuf0 === slopeBuf1 || Math.abs(slopeBuf0 / slopeBuf1 - 1) <= 0.3) && (slopePos0 === slopePos1 || Math.abs(slopePos0 / slopePos1 - 1) <= 0.3)) { + bufEvents.pop(); + } + } + events.buffer.push(event); + trimEventHistory(); + refreshCanvas(); + + var log = 'Duration: ' + v.duration + '\n' + 'Buffered: ' + timeRangesToString(v.buffered) + '\n' + 'Seekable: ' + timeRangesToString(v.seekable) + '\n' + 'Played: ' + timeRangesToString(v.played) + '\n'; + + if (hls.media) { + for (var type in tracks) { + log += 'Buffer for ' + type + ' contains: ' + timeRangesToString(tracks[type].buffer.buffered) + '\n'; + } + + var videoPlaybackQuality = v.getVideoPlaybackQuality; + if (videoPlaybackQuality && (typeof videoPlaybackQuality === 'undefined' ? 'undefined' : _typeof(videoPlaybackQuality)) === (typeof Function === 'undefined' ? 'undefined' : _typeof(Function))) { + log += 'Dropped frames: ' + v.getVideoPlaybackQuality().droppedVideoFrames + '\n'; + log += 'Corrupted frames:' + v.getVideoPlaybackQuality().corruptedVideoFrames + '\n'; + } else if (v.webkitDroppedFrameCount) { + log += 'Dropped frames:' + v.webkitDroppedFrameCount + '\n'; + } + } + $('#bufferedOut').text(log); + + $('#statisticsOut').text(JSON.stringify(Object(__WEBPACK_IMPORTED_MODULE_0__demo_utils__["b" /* sortObject */])(stats), null, '\t')); + + ctx.fillStyle = 'blue'; + + var x = v.currentTime / v.duration * canvas.width; + ctx.fillRect(x, 0, 2, 15); + } +} + +function showCanvas() { + showMetrics(); + $('#bufferedOut').show(); + $('#bufferedCanvas').show(); +} + +function hideCanvas() { + hideMetrics(); + $('#bufferedOut').hide(); + $('#bufferedCanvas').hide(); +} + +function getMetrics() { + var json = JSON.stringify(events); + var jsonpacked = jsonpack.pack(json); + // console.log('packing JSON from ' + json.length + ' to ' + jsonpacked.length + ' bytes'); + return btoa(jsonpacked); +} + +function copyMetricsToClipBoard() { + Object(__WEBPACK_IMPORTED_MODULE_0__demo_utils__["a" /* copyTextToClipboard */])(getMetrics()); +} + +function goToMetrics() { + var url = document.URL; + url = url.substr(0, url.lastIndexOf('/') + 1) + 'metrics.html'; + // console.log(url); + window.open(url, '_blank'); +} + +function goToMetricsPermaLink() { + var url = document.URL; + var b64 = getMetrics(); + url = url.substr(0, url.lastIndexOf('/') + 1) + 'metrics.html#data=' + b64; + // console.log(url); + window.open(url, '_blank'); +} + +function minsecs(ts) { + var m = Math.floor(Math.floor(ts % 3600) / 60); + var s = Math.floor(ts % 60); + return m + ':' + (s < 10 ? '0' : '') + s; +} + +function onClickBufferedRange(event) { + var canvas = $('#bufferedCanvas')[0]; + var v = $('#video')[0]; + var target = (event.clientX - canvas.offsetLeft) / canvas.width * v.duration; + v.currentTime = target; +} + +function updateLevelInfo() { + + if (!hls.levels) { + return; + } + + var button_template = ''; + + html2 += button_template; + if (hls.loadLevel === i) { + html2 += button_enabled; + } else { + html2 += button_disabled; + } + + html2 += 'onclick="hls.loadLevel=' + i + '">' + levelName + ''; + + html3 += button_template; + if (hls.autoLevelCapping === i) { + html3 += button_enabled; + } else { + html3 += button_disabled; + } + + html3 += 'onclick="levelCapping=hls.autoLevelCapping=' + i + ';updateLevelInfo();onDemoConfigChanged();">' + levelName + ''; + + html4 += button_template; + if (hls.nextLevel === i) { + html4 += button_enabled; + } else { + html4 += button_disabled; + } + + html4 += 'onclick="hls.nextLevel=' + i + '">' + levelName + ''; + } + + var v = $('#video')[0]; + + if (v.videoWidth && v.videoHeight) { + $('#currentResolution').html(v.videoWidth + ' x ' + v.videoHeight); + } + + if ($('#currentLevelControl').html() != html1) { + $('#currentLevelControl').html(html1); + } + + if ($('#loadLevelControl').html() != html2) { + $('#loadLevelControl').html(html2); + } + + if ($('#levelCappingControl').html() != html3) { + $('#levelCappingControl').html(html3); + } + + if ($('#nextLevelControl').html() != html4) { + $('#nextLevelControl').html(html4); + } +} + +function updateAudioTrackInfo() { + var button_template = ''; + } + $('#audioTrackControl').html(html1); +} + +function level2label(index) { + if (hls && hls.levels.length - 1 >= index) { + var level = hls.levels[index]; + if (level.name) { + return level.name; + } else { + if (level.height) { + return level.height + 'p / ' + Math.round(level.bitrate / 1024) + 'kb'; + } else { + if (level.bitrate) { + return Math.round(level.bitrate / 1024) + 'kb'; + } else { + return null; + } + } + } + } +} + +function getDemoConfigPropOrDefault(propName, defaultVal) { + return typeof demoConfig[propName] !== 'undefined' ? demoConfig[propName] : defaultVal; +} + +function getURLParam(sParam, defaultValue) { + var sPageURL = window.location.search.substring(1); + var sURLVariables = sPageURL.split('&'); + for (var i = 0; i < sURLVariables.length; i++) { + var sParameterName = sURLVariables[i].split('='); + if (sParameterName[0] == sParam) { + return 'undefined' == sParameterName[1] ? undefined : 'false' == sParameterName[1] ? false : sParameterName[1]; + } + } + return defaultValue; +} + +function onDemoConfigChanged() { + var url = $('#streamURL').val(); + + demoConfig = { + enableStreaming: enableStreaming, + autoRecoverError: autoRecoverError, + enableWorker: enableWorker, + dumpfMP4: dumpfMP4, + levelCapping: levelCapping, + limitMetrics: limitMetrics, + defaultAudioCodec: defaultAudioCodec, + widevineLicenseUrl: escape(widevineLicenseUrl) + }; + + var serializedDemoConfig = btoa(JSON.stringify(demoConfig)); + + var baseURL = document.URL.split('?')[0]; + var permalinkURL = baseURL + ('?src=' + encodeURIComponent(url) + '&demoConfig=' + serializedDemoConfig); + + $('#StreamPermalink').html('' + permalinkURL + ''); +} + +function createfMP4(type) { + if (fmp4Data[type].length) { + var blob = new Blob([arrayConcat(fmp4Data[type])], { + type: 'application/octet-stream' + }); + var filename = type + '-' + new Date().toISOString() + '.mp4'; + saveAs(blob, filename); + //$('body').append('Download ' + filename + ' track
'); + } +} + +function arrayConcat(inputArray) { + var totalLength = inputArray.reduce(function (prev, cur) { + return prev + cur.length; + }, 0); + var result = new Uint8Array(totalLength); + var offset = 0; + inputArray.forEach(function (element) { + result.set(element, offset); + offset += element.length; + }); + return result; +} + +function hideAllTabs() { + $('#playbackControlTab').hide(); + $('#qualityLevelControlTab').hide(); + $('#audioTrackControlTab').hide(); + $('#metricsDisplayTab').hide(); + $('#statsDisplayTab').hide(); +} + +function toggleTab(tabElId) { + hideAllTabs(); + hideMetrics(); + $('#' + tabElId).show(); +} + +function appendLog(textElId, message) { + var el = $('#' + textElId); + var logText = el.text(); + if (logText.length) { + logText += '\n'; + } + var timestamp = (Date.now() - startTime) / 1000; + var newMessage = timestamp + ' | ' + message; + logText += newMessage; + // update + el.text(logText); +} + +function logStatus(message) { + appendLog('statusOut', message); +} + +function logError(message) { + appendLog('errorOut', message); +} + +/***/ }), +/* 1 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["b"] = sortObject; +/* harmony export (immutable) */ __webpack_exports__["a"] = copyTextToClipboard; +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 sortObject(obj) { + if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object') { + return obj; + } + var temp = {}; + var keys = []; + for (var key in obj) { + keys.push(key); + } + keys.sort(); + for (var index in keys) { + temp[keys[index]] = sortObject(obj[keys[index]]); + } + return temp; +} + +function copyTextToClipboard(text) { + var textArea = document.createElement('textarea'); + textArea.value = text; + document.body.appendChild(textArea); + textArea.select(); + try { + var successful = document.execCommand('copy'); + var msg = successful ? 'successful' : 'unsuccessful'; + console.log('Copying text command was ' + msg); + } catch (err) { + console.log('Oops, unable to copy'); + } + document.body.removeChild(textArea); +} + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + +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; }; + +/** + * Create test stream + * @param {string} url + * @param {string} description + * @param {boolean} [live] + * @param {boolean} [abr] + * @param {string[]} [blacklist_ua] + * @returns {{url: string, description: string, live: boolean, abr: boolean, blacklist_ua: string[]}} + */ +function createTestStream(url, description) { + var live = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var abr = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + var blacklist_ua = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; + + return { + url: url, + description: description, + live: live, + abr: abr, + blacklist_ua: blacklist_ua + }; +} + +/** + * @param {Object} target + * @param {Object} [config] + * @returns {{url: string, description: string, live: boolean, abr: boolean, blacklist_ua: string[]}} + */ +function createTestStreamWithConfig(target, config) { + if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object') { + throw new Error('target should be object'); + } + + var testStream = createTestStream(target.url, target.description, target.live, target.abr, target.blacklist_ua); + + testStream.config = config; + + return testStream; +} + +module.exports = { + bbb: createTestStreamWithConfig({ + url: 'https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8', + description: 'Big Buck Bunny - adaptive qualities' + }, { + // try to workaround test failing because of slow seek on Chrome/Win10 + nudgeMaxRetry: 5 + }), + bigBuckBunny480p: { + 'url': 'https://video-dev.github.io/streams/x36xhzz/url_6/193039199_mp4_h264_aac_hq_7.m3u8', + 'description': 'Big Buck Bunny - 480p only', + 'live': false, + 'abr': false, + 'blacklist_ua': ['internet explorer'] + }, + arte: { + 'url': 'https://video-dev.github.io/streams/test_001/stream.m3u8', + 'description': 'ARTE China,ABR', + 'live': false, + 'abr': true + }, + deltatreDAI: { + 'url': 'https://video-dev.github.io/streams/dai-discontinuity-deltatre/manifest.m3u8', + 'description': 'Ad-insertion in event stream', + 'live': false, + 'abr': false, + 'blacklist_ua': ['internet explorer'] + }, + issue666: { + 'url': 'https://video-dev.github.io/streams/issue666/playlists/cisq0gim60007xzvi505emlxx.m3u8', + 'description': 'hls.js/issues/666', + 'live': false, + 'abr': false, + 'blacklist_ua': ['internet explorer'] + }, + issue649: { + 'url': 'http://cdn3.screen9.com/media/c/W/cW87csHkxsgu5TV1qs78aA_auto_hls.m3u8?auth=qlUjeCtbVdtkDfZYrtveTIVUXX1yuSqgF8wfWabzKpX72r-d5upW88-FHuyRRdnZA_1PKRTGAtTt_6Z-aj22kw', + 'description': 'hls.js/issues/649', + 'live': false, + 'abr': false + }, + closedCaptions: { + 'url': 'http://playertest.longtailvideo.com/adaptive/captions/playlist.m3u8', + 'description': 'CNN special report, with CC', + 'live': false, + 'abr': false, + 'blacklist_ua': ['safari'] + }, + oceansAES: { + 'url': 'http://playertest.longtailvideo.com/adaptive/oceans_aes/oceans_aes.m3u8', + 'description': 'AES encrypted,ABR', + 'live': false, + 'abr': true + }, + /* + bbbAES: { + 'url': 'https://video-dev.github.io/streams/bbbAES/playlists/sample_aes/index.m3u8', + 'description': 'SAMPLE-AES encrypted', + 'live': false, + 'abr': false + }, + */ + mp3Audio: { + 'url': 'https://player.webvideocore.net/CL1olYogIrDWvwqiIKK7eLBkzvO18gwo9ERMzsyXzwt_t-ya8ygf2kQBZww38JJT/8i4vvznv8408.m3u8', + 'description': 'MP3 VOD demo', + 'live': false, + 'abr': false, + 'blacklist_ua': ['safari'] + }, + mpegAudioOnly: { + 'url': 'https://pl.streamingvideoprovider.com/mp3-playlist/playlist.m3u8', + 'description': 'MPEG Audio Only demo', + 'live': false, + 'abr': false, + 'blacklist_ua': ['internet explorer', 'MicrosoftEdge', 'safari', 'firefox'] + }, + fmp4: { + 'url': 'https://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8', + 'description': 'HLS fMP4 Angel-One multiple audio-tracks', + 'live': false, + 'abr': false, + 'blacklist_ua': ['safari', 'internet explorer'] + }, + fmp4Bitmovin: { + 'url': 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s-fmp4/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8', + 'description': 'HLS fMP4 by Bitmovin', + 'live': false, + 'abr': true, + 'blacklist_ua': ['safari', 'internet explorer'] + }, + offset_pts: { + 'url': 'https://video-dev.github.io/streams/pts_shift/master.m3u8', + 'description': 'DK Turntable, PTS shifted by 2.3s', + 'live': false, + 'abr': false + }, + /* + uspHLSAteam: createTestStream( + 'http://demo.unified-streaming.com/video/ateam/ateam.ism/ateam.m3u8?session_id=27199', + 'A-Team movie trailer - HLS by Unified Streaming Platform' + ), + */ + angelOneShakaWidevine: createTestStreamWithConfig({ + url: 'https://storage.googleapis.com/shaka-demo-assets/angel-one-widevine-hls/hls.m3u8', + description: 'Shaka-packager Widevine DRM (EME) HLS-fMP4 - Angel One Demo', + blacklist_ua: ['firefox', 'safari', 'internet explorer'] + }, { + widevineLicenseUrl: 'https://cwip-shaka-proxy.appspot.com/no_auth', + emeEnabled: true + }), + audioOnlyMultipleLevels: { + 'url': 'https://s3.amazonaws.com/bob.jwplayer.com/~alex/121628/new_master.m3u8', + 'description': 'Multiple non-alternate audio levels', + 'live': false, + 'abr': false + }, + pdtDuplicate: { + url: 'https://playertest.longtailvideo.com/adaptive/artbeats/manifest.m3u8', + description: 'Stream with duplicate sequential PDT values' + }, + pdtLargeGap: { + url: 'https://playertest.longtailvideo.com/adaptive/boxee/playlist.m3u8', + description: 'PDTs with large gaps following discontinuities' + }, + pdtBadValues: { + url: 'https://playertest.longtailvideo.com/adaptive/progdatime/playlist2.m3u8', + description: 'PDTs with bad values' + }, + pdtOneValue: { + url: 'https://playertest.longtailvideo.com/adaptive/aviion/manifest.m3u8', + description: 'One PDT, no discontinuities' + } +}; + +/***/ }) +/******/ ])["default"]; +}); +//# sourceMappingURL=hls-demo.js.map \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls-demo.js.map b/grails-app/assets/bower/hls.js/dist/hls-demo.js.map new file mode 100644 index 000000000..97e50d77a --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls-demo.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 4272408a55a30c66251b","webpack:///./demo/main.js","webpack:///./demo/demo-utils.js","webpack:///./tests/test-streams.js"],"names":["testStreams","require","defaultTestStreamUrl","url","sourceURL","decodeURIComponent","getURLParam","demoConfig","JSON","parse","atob","enableStreaming","getDemoConfigPropOrDefault","autoRecoverError","enableWorker","levelCapping","limitMetrics","defaultAudioCodec","undefined","widevineLicenseUrl","dumpfMP4","bufferingIdx","selectedTestStream","video","$","startTime","Date","now","lastSeekingIdx","lastStartPosition","lastDuration","lastAudioTrackSwitchingIdx","hls","events","stats","tracks","fmp4Data","document","ready","Object","keys","forEach","key","stream","option","Option","description","append","change","val","streamUrl","loadSelectedStream","width","click","checked","onDemoConfigChanged","value","prop","Hls","version","html","volume","hideAllTabs","toggle","windowSliding","setupGlobals","window","t0","performance","load","buffer","level","bitrate","recoverDecodingErrorDate","recoverSwapAudioCodecDate","onClickBufferedRange","updateLevelInfo","createfMP4","goToMetricsPermaLink","toggleTab","trimArray","target","limit","length","shift","trimEventHistory","x","isSupported","handleUnsupported","hideCanvas","destroy","bufferTimer","clearInterval","logStatus","unescape","hlsConfig","debug","config","emeEnabled","console","log","loadSource","autoLevelCapping","attachMedia","on","Events","MEDIA_ATTACHED","push","time","type","MEDIA_DETACHED","FRAG_PARSING_INIT_SEGMENT","event","data","showCanvas","id","FRAG_PARSING_METADATA","LEVEL_SWITCHING","Math","round","levels","MANIFEST_PARSED","name","start","end","trequest","latency","tfirst","tload","duration","refreshCanvas","levelNb","levelParsed","AUDIO_TRACKS_UPDATED","audioTracks","updateAudioTrackInfo","AUDIO_TRACK_SWITCHING","AUDIO_TRACK_SWITCHED","LEVEL_LOADED","isLive","details","live","startSN","endSN","parsing","tparsed","parsingDuration","sumLevelParsingMs","levelParsingUs","AUDIO_TRACK_LOADED","FRAG_BUFFERED","frag","id2","sn","tbuffered","bw","total","size","pos","setInterval","checkBuffer","process","fragBuffered","fragMinLatency","min","fragMaxLatency","max","fragMinProcess","fragMaxProcess","fragMinKbps","fragMaxKbps","autoLevelCappingMin","autoLevelCappingMax","fragBufferedBytes","sumLatency","sumKbps","sumProcess","sumParsing","fraglastLatency","fragAvgLatency","fragLastProcess","fragAvgProcess","fragLastKbps","fragAvgKbps","fragparsingKbps","fragparsingMs","autoLevelCappingLast","LEVEL_SWITCHED","FRAG_CHANGED","tagList","autoLevel","levelStart","fragChangedAuto","autoLevelMin","autoLevelMax","levelLastAuto","autoLevelLast","autoLevelSwitch","sumAutoLevel","autoLevelAvg","fragChangedManual","manualLevelMin","manualLevelMax","manualLevelLast","manualLevelSwitch","FRAG_LOAD_EMERGENCY_ABORTED","fragLoadEmergencyAborted","FRAG_DECRYPTED","fragDecrypted","totalDecryptTime","fragAvgDecryptTime","tdecrypt","tstart","ERROR","warn","ErrorDetails","MANIFEST_LOAD_ERROR","context","response","code","text","err","MANIFEST_LOAD_TIMEOUT","logError","MANIFEST_PARSING_ERROR","reason","LEVEL_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","LEVEL_SWITCH_ERROR","FRAG_LOAD_ERROR","FRAG_LOAD_TIMEOUT","FRAG_LOOP_LOADING_ERROR","FRAG_DECRYPT_ERROR","FRAG_PARSING_ERROR","KEY_LOAD_ERROR","decryptdata","uri","KEY_LOAD_TIMEOUT","BUFFER_APPEND_ERROR","BUFFER_ADD_CODEC_ERROR","mimeType","message","BUFFER_APPENDING_ERROR","BUFFER_STALLED_ERROR","fatal","error","ErrorTypes","MEDIA_ERROR","handleMediaError","NETWORK_ERROR","fatalError","stringify","sortObject","BUFFER_CREATED","BUFFER_APPENDING","FPS_DROP","evt","currentDropped","currentDecoded","fpsDropEvent","fpsTotalDroppedFrames","totalDroppedFrames","addEventListener","handleVideoEvent","navigator","userAgent","toLowerCase","indexOf","videoWidth","videoHeight","currentTime","errorTxt","mediaError","currentTarget","MEDIA_ERR_ABORTED","MEDIA_ERR_DECODE","MEDIA_ERR_NETWORK","MEDIA_ERR_SRC_NOT_SUPPORTED","recoverMediaError","swapAudioCodec","timeRangesToString","r","i","v","canvas","ctx","getContext","buffered","bufferingDuration","fillStyle","fillRect","height","clientWidth","bufferLen","paused","bufEvents","bufEventLen","event0","event1","slopeBuf0","slopeBuf1","slopePos0","slopePos1","abs","pop","seekable","played","media","videoPlaybackQuality","getVideoPlaybackQuality","Function","droppedVideoFrames","corruptedVideoFrames","webkitDroppedFrameCount","showMetrics","show","hideMetrics","hide","getMetrics","json","jsonpacked","jsonpack","pack","btoa","copyMetricsToClipBoard","copyTextToClipboard","goToMetrics","URL","substr","lastIndexOf","open","b64","minsecs","ts","m","floor","s","clientX","offsetLeft","button_template","button_enabled","button_disabled","html1","autoLevelEnabled","html2","html3","html4","currentLevel","levelName","label","level2label","loadLevel","nextLevel","audioTrackId","audioTrack","len","index","propName","defaultVal","sParam","defaultValue","sPageURL","location","search","substring","sURLVariables","split","sParameterName","escape","serializedDemoConfig","baseURL","permalinkURL","encodeURIComponent","blob","Blob","arrayConcat","filename","toISOString","saveAs","inputArray","totalLength","reduce","prev","cur","result","Uint8Array","offset","element","set","tabElId","appendLog","textElId","el","logText","timestamp","newMessage","obj","temp","sort","textArea","createElement","body","appendChild","select","successful","execCommand","msg","removeChild","createTestStream","abr","blacklist_ua","createTestStreamWithConfig","Error","testStream","module","exports","bbb","nudgeMaxRetry","bigBuckBunny480p","arte","deltatreDAI","issue666","issue649","closedCaptions","oceansAES","mp3Audio","mpegAudioOnly","fmp4","fmp4Bitmovin","offset_pts","angelOneShakaWidevine","audioOnlyMultipleLevels","pdtDuplicate","pdtLargeGap","pdtBadValues","pdtOneValue"],"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;;AAEA,IAAMA,cAAc,mBAAAC,CAAQ,CAAR,CAApB;AACA,IAAMC,uBAAuBF,YAAY,KAAZ,EAAmBG,GAAhD;AACA,IAAMC,YAAYC,mBAAmBC,YAAY,KAAZ,EAAmBJ,oBAAnB,CAAnB,CAAlB;;AAEA,IAAIK,aAAaD,YAAY,YAAZ,EAA0B,IAA1B,CAAjB;AACA,IAAIC,UAAJ,EAAgB;AACdA,eAAaC,KAAKC,KAAL,CAAWC,KAAKH,UAAL,CAAX,CAAb;AACD,CAFD,MAEO;AACLA,eAAa,EAAb;AACD;;AAED,IAAII,kBAAkBC,2BAA2B,iBAA3B,EAA8C,IAA9C,CAAtB;AACA,IAAIC,mBAAmBD,2BAA2B,kBAA3B,EAA+C,IAA/C,CAAvB;AACA,IAAIE,eAAeF,2BAA2B,cAA3B,EAA2C,IAA3C,CAAnB;AACA,IAAIG,e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B,C","file":"hls-demo.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[\"HlsDemo\"] = factory();\n\telse\n\t\troot[\"HlsDemo\"] = 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 = 0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 4272408a55a30c66251b","import {sortObject, copyTextToClipboard} from './demo-utils'\n\nconst testStreams = require('../tests/test-streams');\nconst defaultTestStreamUrl = testStreams['bbb'].url;\nconst sourceURL = decodeURIComponent(getURLParam('src', defaultTestStreamUrl))\n\nlet demoConfig = getURLParam('demoConfig', null)\nif (demoConfig) {\n demoConfig = JSON.parse(atob(demoConfig))\n} else {\n demoConfig = {}\n}\n\nlet enableStreaming = getDemoConfigPropOrDefault('enableStreaming', true);\nlet autoRecoverError = getDemoConfigPropOrDefault('autoRecoverError', true);\nlet enableWorker = getDemoConfigPropOrDefault('enableWorker', true);\nlet levelCapping = getDemoConfigPropOrDefault('levelCapping', -1);\nlet limitMetrics = getDemoConfigPropOrDefault('limitMetrics', -1);\nlet defaultAudioCodec = getDemoConfigPropOrDefault('defaultAudioCodec', undefined);\nlet widevineLicenseUrl = getDemoConfigPropOrDefault('widevineLicenseURL', undefined);\nlet dumpfMP4 = getDemoConfigPropOrDefault('dumpfMP4', false);\n\nlet bufferingIdx = -1;\nlet selectedTestStream = null;\nlet video = $('#video')[0];\nlet startTime = Date.now()\n\nlet lastSeekingIdx;\nlet lastStartPosition;\nlet lastDuration;\nlet lastAudioTrackSwitchingIdx;\nlet hls;\nlet url;\nlet events;\nlet stats;\nlet tracks;\nlet fmp4Data;\n\n$(document).ready(function() {\n Object.keys(testStreams).forEach((key) => {\n const stream = testStreams[key];\n const option = new Option(stream.description, key);\n $('#streamSelect').append(option);\n })\n\n $('#streamSelect').change(function() {\n selectedTestStream = testStreams[$('#streamSelect').val()];\n const streamUrl = selectedTestStream.url;\n $('#streamURL').val(streamUrl);\n loadSelectedStream();\n });\n\n $('#streamURL').change(function() {\n selectedTestStream = null;\n loadSelectedStream();\n });\n\n $('#videoSize').change(function() {\n $('#video').width($('#videoSize').val());\n $('#bufferedCanvas').width($('#videoSize').val());\n });\n\n $('#enableStreaming').click(function() {\n enableStreaming = this.checked;\n loadSelectedStream();\n });\n\n $('#autoRecoverError').click(function() {\n autoRecoverError = this.checked;\n onDemoConfigChanged();\n });\n\n $('#enableWorker').click(function() {\n enableWorker = this.checked;\n onDemoConfigChanged();\n });\n\n $('#dumpfMP4').click(function() {\n dumpfMP4 = this.checked;\n onDemoConfigChanged();\n });\n\n $('#limitMetrics').change(function() {\n limitMetrics = this.value;\n onDemoConfigChanged();\n })\n\n $('#levelCapping').change(function() {\n levelCapping = this.value;\n onDemoConfigChanged();\n });\n\n $('#defaultAudioCodec').change(function() {\n defaultAudioCodec = this.value;\n onDemoConfigChanged();\n });\n\n $('#limitMetrics').val(limitMetrics);\n $('#enableStreaming').prop('checked', enableStreaming );\n $('#autoRecoverError').prop('checked', autoRecoverError );\n $('#enableWorker').prop('checked', enableWorker );\n $('#dumpfMP4').prop('checked', dumpfMP4 );\n $('#levelCapping').val(levelCapping);\n $('#defaultAudioCodec').val(defaultAudioCodec || 'undefined');\n\n $('h2').append(' v' + Hls.version + '');\n $('#currentVersion').html('Hls version:' + Hls.version);\n\n $('#streamURL').val(sourceURL)\n\n video.volume = 0.05;\n\n hideAllTabs();\n\n $('#metricsButtonWindow').toggle(windowSliding);\n $('#metricsButtonFixed').toggle(!windowSliding);\n\n loadSelectedStream();\n\n});\n\nfunction setupGlobals() {\n window.events = events = {\n url : url,\n t0 : performance.now(),\n load : [],\n buffer : [],\n video : [],\n level : [],\n bitrate: []\n };\n\n // actual values, only on window\n window.recoverDecodingErrorDate = null;\n window.recoverSwapAudioCodecDate = null;\n\n window.fmp4Data = fmp4Data = {\n 'audio': [],\n 'video': []\n };\n\n window.onClickBufferedRange = onClickBufferedRange;\n\n window.updateLevelInfo = updateLevelInfo;\n window.onDemoConfigChanged = onDemoConfigChanged;\n window.createfMP4 = createfMP4;\n window.goToMetricsPermaLink = goToMetricsPermaLink;\n window.toggleTab = toggleTab;\n window.onDemoConfigChanged = onDemoConfigChanged;\n}\n\nfunction trimArray( target, limit ) {\n if( limit < 0 ) {\n return;\n }\n\n while(target.length > limit )\n {\n target.shift();\n }\n}\n\nfunction trimEventHistory() {\n const x = limitMetrics;\n\n if(x < 0) {\n return;\n }\n\n trimArray(events.load, x);\n trimArray(events.buffer, x);\n trimArray(events.video, x);\n trimArray(events.level, x);\n trimArray(events.bitrate, x);\n}\n\nfunction loadSelectedStream() {\n\n if (!Hls.isSupported()) {\n handleUnsupported();\n return;\n }\n\n url = $('#streamURL').val()\n\n setupGlobals();\n hideCanvas();\n\n if(hls) {\n hls.destroy();\n if(hls.bufferTimer) {\n clearInterval(hls.bufferTimer);\n hls.bufferTimer = undefined;\n }\n hls = null;\n }\n\n if(!enableStreaming) {\n logStatus('Streaming disabled');\n return;\n }\n\n logStatus('Loading ' + url);\n\n if (widevineLicenseUrl) {\n widevineLicenseUrl = unescape(widevineLicenseUrl)\n }\n\n const hlsConfig = {\n debug : true,\n enableWorker : enableWorker,\n defaultAudioCodec: defaultAudioCodec,\n widevineLicenseUrl: widevineLicenseUrl\n };\n\n if (selectedTestStream && selectedTestStream.config) {\n Object.assign(hlsConfig, selectedTestStream.config)\n }\n\n if (hlsConfig.widevineLicenseUrl) {\n $('#widevineLicenseUrl').val(hlsConfig.widevineLicenseUrl);\n }\n\n widevineLicenseUrl = hlsConfig.widevineLicenseUrl = $('#widevineLicenseUrl').val();\n\n if (hlsConfig.widevineLicenseUrl) {\n hlsConfig.emeEnabled = true;\n }\n\n onDemoConfigChanged();\n console.log('Using Hls.js config:', hlsConfig);\n\n window.hls = hls = new Hls(hlsConfig);\n\n logStatus('Loading manifest and attaching video element...');\n\n hls.loadSource(url);\n hls.autoLevelCapping = levelCapping;\n hls.attachMedia(video);\n\n hls.on(Hls.Events.MEDIA_ATTACHED, function() {\n logStatus('Media element attached');\n bufferingIdx = -1;\n events.video.push({\n time: performance.now() - events.t0,\n type: 'Media attached'\n });\n trimEventHistory();\n });\n\n hls.on(Hls.Events.MEDIA_DETACHED, function() {\n logStatus('Media element detached');\n bufferingIdx = -1;\n tracks = [];\n events.video.push({\n time: performance.now() - events.t0,\n type: 'Media detached'\n });\n trimEventHistory();\n });\n\n hls.on(Hls.Events.FRAG_PARSING_INIT_SEGMENT, function(event, data) {\n showCanvas();\n var event = {\n time: performance.now() - events.t0,\n type: data.id + ' init segment'\n };\n events.video.push(event);\n trimEventHistory();\n });\n\n hls.on(Hls.Events.FRAG_PARSING_METADATA, function(event, data) {\n //console.log(\"Id3 samples \", data.samples);\n });\n\n hls.on(Hls.Events.LEVEL_SWITCHING, function(event, data) {\n events.level.push({\n time : performance.now() - events.t0,\n id : data.level,\n bitrate: Math.round(hls.levels[data.level].bitrate/1000)\n });\n trimEventHistory();\n updateLevelInfo();\n });\n\n hls.on(Hls.Events.MANIFEST_PARSED, function(event, data) {\n var event = {\n type : 'manifest',\n name : '',\n start : 0,\n end : data.levels.length,\n time : data.stats.trequest - events.t0,\n latency : data.stats.tfirst - data.stats.trequest,\n load : data.stats.tload - data.stats.tfirst,\n duration: data.stats.tload - data.stats.tfirst,\n };\n events.load.push(event);\n trimEventHistory();\n refreshCanvas();\n });\n\n hls.on(Hls.Events.MANIFEST_PARSED, function(event, data) {\n logStatus('No of quality levels found: ' + hls.levels.length);\n logStatus('Manifest successfully loaded');\n stats = {\n levelNb : data.levels.length,\n levelParsed: 0\n };\n trimEventHistory();\n updateLevelInfo();\n });\n\n hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, function(event, data) {\n logStatus('No of audio tracks found: ' + data.audioTracks.length);\n updateAudioTrackInfo();\n });\n\n hls.on(Hls.Events.AUDIO_TRACK_SWITCHING, function(event, data) {\n logStatus('Audio track switching...');\n updateAudioTrackInfo();\n var event = {\n time: performance.now() - events.t0,\n type: 'audio switching',\n name: '@' + data.id\n };\n events.video.push(event);\n trimEventHistory();\n lastAudioTrackSwitchingIdx = events.video.length-1;\n });\n\n hls.on(Hls.Events.AUDIO_TRACK_SWITCHED, function(event, data) {\n logStatus('Audio track switched');\n updateAudioTrackInfo();\n var event = {\n time: performance.now() - events.t0,\n type: 'audio switched',\n name: '@' + data.id\n };\n if (lastAudioTrackSwitchingIdx !== undefined) {\n events.video[lastAudioTrackSwitchingIdx].duration = event.time - events.video[lastAudioTrackSwitchingIdx].time;\n lastAudioTrackSwitchingIdx = undefined;\n }\n events.video.push(event);\n trimEventHistory();\n });\n\n hls.on(Hls.Events.LEVEL_LOADED, function(event, data) {\n events.isLive = data.details.live;\n var event = {\n type : 'level',\n id : data.level,\n start : data.details.startSN,\n end : data.details.endSN,\n time : data.stats.trequest - events.t0,\n latency : data.stats.tfirst - data.stats.trequest,\n load : data.stats.tload - data.stats.tfirst,\n parsing : data.stats.tparsed - data.stats.tload,\n duration: data.stats.tload - data.stats.tfirst\n };\n const parsingDuration = data.stats.tparsed - data.stats.tload;\n if (stats.levelParsed)\n {this.sumLevelParsingMs += parsingDuration;}\n else\n {this.sumLevelParsingMs = parsingDuration;}\n\n stats.levelParsed++;\n stats.levelParsingUs = Math.round(1000*this.sumLevelParsingMs / stats.levelParsed);\n\n //console.log('parsing level duration :' + stats.levelParsingUs + 'us,count:' + stats.levelParsed);\n\n events.load.push(event);\n trimEventHistory();\n refreshCanvas();\n });\n\n hls.on(Hls.Events.AUDIO_TRACK_LOADED, function(event, data) {\n events.isLive = data.details.live;\n var event = {\n type : 'audio track',\n id : data.id,\n start : data.details.startSN,\n end : data.details.endSN,\n time : data.stats.trequest - events.t0,\n latency : data.stats.tfirst - data.stats.trequest,\n load : data.stats.tload - data.stats.tfirst,\n parsing : data.stats.tparsed - data.stats.tload,\n duration: data.stats.tload - data.stats.tfirst\n };\n events.load.push(event);\n trimEventHistory();\n refreshCanvas();\n });\n\n hls.on(Hls.Events.FRAG_BUFFERED, function(event, data) {\n var event = {\n type : data.frag.type + ' fragment',\n id : data.frag.level,\n id2 : data.frag.sn,\n time : data.stats.trequest - events.t0,\n latency : data.stats.tfirst - data.stats.trequest,\n load : data.stats.tload - data.stats.tfirst,\n parsing : data.stats.tparsed - data.stats.tload,\n buffer : data.stats.tbuffered - data.stats.tparsed,\n duration: data.stats.tbuffered - data.stats.tfirst,\n bw : Math.round(8*data.stats.total/(data.stats.tbuffered - data.stats.trequest)),\n size : data.stats.total\n };\n events.load.push(event);\n events.bitrate.push({\n time : performance.now() - events.t0,\n bitrate : event.bw,\n duration: data.frag.duration,\n level : event.id\n });\n if(hls.bufferTimer === undefined) {\n events.buffer.push({\n time : 0,\n buffer: 0,\n pos : 0\n });\n hls.bufferTimer = window.setInterval(checkBuffer, 100);\n }\n trimEventHistory();\n refreshCanvas();\n updateLevelInfo();\n\n let latency = data.stats.tfirst - data.stats.trequest,\n parsing = data.stats.tparsed - data.stats.tload,\n process = data.stats.tbuffered - data.stats.trequest,\n bitrate = Math.round(8 * data.stats.length / (data.stats.tbuffered - data.stats.tfirst));\n if (stats.fragBuffered) {\n stats.fragMinLatency = Math.min(stats.fragMinLatency, latency);\n stats.fragMaxLatency = Math.max(stats.fragMaxLatency, latency);\n stats.fragMinProcess = Math.min(stats.fragMinProcess, process);\n stats.fragMaxProcess = Math.max(stats.fragMaxProcess, process);\n stats.fragMinKbps = Math.min(stats.fragMinKbps, bitrate);\n stats.fragMaxKbps = Math.max(stats.fragMaxKbps, bitrate);\n stats.autoLevelCappingMin = Math.min(stats.autoLevelCappingMin, hls.autoLevelCapping);\n stats.autoLevelCappingMax = Math.max(stats.autoLevelCappingMax, hls.autoLevelCapping);\n stats.fragBuffered++;\n } else {\n stats.fragMinLatency = stats.fragMaxLatency = latency;\n stats.fragMinProcess = stats.fragMaxProcess = process;\n stats.fragMinKbps = stats.fragMaxKbps = bitrate;\n stats.fragBuffered = 1;\n stats.fragBufferedBytes = 0;\n stats.autoLevelCappingMin = stats.autoLevelCappingMax = hls.autoLevelCapping;\n this.sumLatency = 0;\n this.sumKbps = 0;\n this.sumProcess = 0;\n this.sumParsing = 0;\n }\n stats.fraglastLatency = latency;\n this.sumLatency += latency;\n stats.fragAvgLatency = Math.round(this.sumLatency / stats.fragBuffered);\n stats.fragLastProcess = process;\n this.sumProcess += process;\n this.sumParsing += parsing;\n stats.fragAvgProcess = Math.round(this.sumProcess / stats.fragBuffered);\n stats.fragLastKbps = bitrate;\n this.sumKbps += bitrate;\n stats.fragAvgKbps = Math.round(this.sumKbps / stats.fragBuffered);\n stats.fragBufferedBytes += data.stats.total;\n stats.fragparsingKbps = Math.round(8*stats.fragBufferedBytes / this.sumParsing);\n stats.fragparsingMs = Math.round(this.sumParsing);\n stats.autoLevelCappingLast = hls.autoLevelCapping;\n });\n\n hls.on(Hls.Events.LEVEL_SWITCHED, function(event, data) {\n var event = {\n time: performance.now() - events.t0,\n type: 'level switched',\n name: data.level\n };\n events.video.push(event);\n trimEventHistory();\n refreshCanvas();\n updateLevelInfo();\n });\n\n hls.on(Hls.Events.FRAG_CHANGED, function(event, data) {\n var event = {\n time: performance.now() - events.t0,\n type: 'frag changed',\n name: data.frag.sn + ' @ ' + data.frag.level\n };\n events.video.push(event);\n trimEventHistory();\n refreshCanvas();\n updateLevelInfo();\n stats.tagList = data.frag.tagList;\n\n let level = data.frag.level, autoLevel = data.frag.autoLevel;\n if (stats.levelStart === undefined)\n {stats.levelStart = level;}\n\n if (autoLevel) {\n if (stats.fragChangedAuto) {\n stats.autoLevelMin = Math.min(stats.autoLevelMin, level);\n stats.autoLevelMax = Math.max(stats.autoLevelMax, level);\n stats.fragChangedAuto++;\n if (this.levelLastAuto && level !== stats.autoLevelLast)\n {stats.autoLevelSwitch++;}\n\n } else {\n stats.autoLevelMin = stats.autoLevelMax = level;\n stats.autoLevelSwitch = 0;\n stats.fragChangedAuto = 1;\n this.sumAutoLevel = 0;\n }\n this.sumAutoLevel += level;\n stats.autoLevelAvg = Math.round(1000 * this.sumAutoLevel / stats.fragChangedAuto) / 1000;\n stats.autoLevelLast = level;\n } else {\n if (stats.fragChangedManual) {\n stats.manualLevelMin = Math.min(stats.manualLevelMin, level);\n stats.manualLevelMax = Math.max(stats.manualLevelMax, level);\n stats.fragChangedManual++;\n if (!this.levelLastAuto && level !== stats.manualLevelLast)\n {stats.manualLevelSwitch++;}\n\n } else {\n stats.manualLevelMin = stats.manualLevelMax = level;\n stats.manualLevelSwitch = 0;\n stats.fragChangedManual = 1;\n }\n stats.manualLevelLast = level;\n }\n this.levelLastAuto = autoLevel;\n });\n\n hls.on(Hls.Events.FRAG_LOAD_EMERGENCY_ABORTED, function(event, data) {\n if (stats) {\n if (stats.fragLoadEmergencyAborted === undefined)\n {stats.fragLoadEmergencyAborted = 1;}\n else\n {stats.fragLoadEmergencyAborted++;}\n\n }\n });\n\n hls.on(Hls.Events.FRAG_DECRYPTED, function(event, data) {\n if (!stats.fragDecrypted) {\n stats.fragDecrypted = 0;\n this.totalDecryptTime = 0;\n stats.fragAvgDecryptTime = 0;\n }\n stats.fragDecrypted++;\n this.totalDecryptTime += data.stats.tdecrypt - data.stats.tstart;\n stats.fragAvgDecryptTime = this.totalDecryptTime / stats.fragDecrypted;\n });\n\n hls.on(Hls.Events.ERROR, function(event, data) {\n console.warn('Error event:', data);\n switch(data.details) {\n case Hls.ErrorDetails.MANIFEST_LOAD_ERROR:\n try {\n $('#errorOut').html('Cannot load ' + url + '
HTTP response code:' + data.response.code + '
' + data.response.text);\n if(data.response.code === 0){\n $('#errorOut').append('This might be a CORS issue, consider installing Allow-Control-Allow-Origin Chrome Extension');\n }\n } catch(err) {\n $('#errorOut').html('Cannot load ' + url + '
Response body: ' + data.response.text);\n }\n break;\n case Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT:\n logError('Timeout while loading manifest');\n break;\n case Hls.ErrorDetails.MANIFEST_PARSING_ERROR:\n logError('Error while parsing manifest:' + data.reason);\n break;\n case Hls.ErrorDetails.LEVEL_LOAD_ERROR:\n logError('Error while loading level playlist');\n break;\n case Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT:\n logError('Timeout while loading level playlist');\n break;\n case Hls.ErrorDetails.LEVEL_SWITCH_ERROR:\n logError('Error while trying to switch to level ' + data.level);\n break;\n case Hls.ErrorDetails.FRAG_LOAD_ERROR:\n logError('Error while loading fragment ' + data.frag.url);\n break;\n case Hls.ErrorDetails.FRAG_LOAD_TIMEOUT:\n logError('Timeout while loading fragment ' + data.frag.url);\n break;\n case Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR:\n logError('Fragment-loop loading error');\n break;\n case Hls.ErrorDetails.FRAG_DECRYPT_ERROR:\n logError('Decrypting error:' + data.reason);\n break;\n case Hls.ErrorDetails.FRAG_PARSING_ERROR:\n logError('Parsing error:' + data.reason);\n break;\n case Hls.ErrorDetails.KEY_LOAD_ERROR:\n logError('Error while loading key ' + data.frag.decryptdata.uri);\n break;\n case Hls.ErrorDetails.KEY_LOAD_TIMEOUT:\n logError('Timeout while loading key ' + data.frag.decryptdata.uri);\n break;\n case Hls.ErrorDetails.BUFFER_APPEND_ERROR:\n logError('Buffer append error');\n break;\n case Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n logError('Buffer add codec error for ' + data.mimeType + ':' + data.err.message);\n break;\n case Hls.ErrorDetails.BUFFER_APPENDING_ERROR:\n logError('Buffer appending error');\n break;\n case Hls.ErrorDetails.BUFFER_STALLED_ERROR:\n logError('Buffer stalled error');\n break;\n default:\n break;\n }\n if(data.fatal) {\n console.error('Fatal error :' + data.details);\n switch(data.type) {\n case Hls.ErrorTypes.MEDIA_ERROR:\n handleMediaError();\n break;\n case Hls.ErrorTypes.NETWORK_ERROR:\n logError('A network error occured');\n break;\n default:\n logError('An unrecoverable error occured');\n hls.destroy();\n break;\n }\n }\n if(!stats) {\n stats = {};\n }\n // track all errors independently\n if (stats[data.details] === undefined)\n {stats[data.details] = 1;}\n else\n {stats[data.details] += 1;}\n\n // track fatal error\n if (data.fatal) {\n if (stats.fatalError === undefined) {\n stats.fatalError = 1;\n } else {\n stats.fatalError += 1;\n }\n }\n $('#statisticsOut').text(JSON.stringify(sortObject(stats), null, '\\t'));\n });\n\n hls.on(Hls.Events.BUFFER_CREATED, function(event, data) {\n tracks = data.tracks;\n });\n\n hls.on(Hls.Events.BUFFER_APPENDING, function(event, data) {\n if (dumpfMP4) {\n fmp4Data[data.type].push(data.data);\n }\n });\n\n hls.on(Hls.Events.FPS_DROP, function(event, data) {\n let evt = {\n time: performance.now() - events.t0,\n type: 'frame drop',\n name: data.currentDropped + '/' + data.currentDecoded\n };\n events.video.push(evt);\n trimEventHistory();\n if (stats) {\n if (stats.fpsDropEvent === undefined)\n {stats.fpsDropEvent = 1;}\n else\n {stats.fpsDropEvent++;}\n\n stats.fpsTotalDroppedFrames = data.totalDroppedFrames;\n }\n });\n\n video.addEventListener('resize', handleVideoEvent);\n video.addEventListener('seeking', handleVideoEvent);\n video.addEventListener('seeked', handleVideoEvent);\n video.addEventListener('pause', handleVideoEvent);\n video.addEventListener('play', handleVideoEvent);\n video.addEventListener('canplay', handleVideoEvent);\n video.addEventListener('canplaythrough', handleVideoEvent);\n video.addEventListener('ended', handleVideoEvent);\n video.addEventListener('playing', handleVideoEvent);\n video.addEventListener('error', handleVideoEvent);\n video.addEventListener('loadedmetadata', handleVideoEvent);\n video.addEventListener('loadeddata', handleVideoEvent);\n video.addEventListener('durationchange', handleVideoEvent);\n}\n\nfunction handleUnsupported() {\n if(navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) {\n logStatus('You are using Firefox, it looks like MediaSource is not enabled,
please ensure the following keys are set appropriately in about:config
media.mediasource.enabled=true
media.mediasource.mp4.enabled=true
media.mediasource.whitelist=false');\n } else {\n logStatus('Your Browser does not support MediaSourceExtension / MP4 mediasource');\n }\n}\n\nfunction handleVideoEvent(evt) {\n let data = '';\n switch(evt.type) {\n case 'durationchange':\n if(evt.target.duration - lastDuration <= 0.5) {\n // some browsers report several duration change events with almost the same value ... avoid spamming video events\n return;\n }\n lastDuration = evt.target.duration;\n data = Math.round(evt.target.duration*1000);\n break;\n case 'resize':\n data = evt.target.videoWidth + '/' + evt.target.videoHeight;\n break;\n case 'loadedmetadata':\n case 'loadeddata':\n case 'canplay':\n case 'canplaythrough':\n case 'ended':\n case 'seeking':\n case 'seeked':\n case 'play':\n case 'playing':\n lastStartPosition = evt.target.currentTime;\n case 'pause':\n case 'waiting':\n case 'stalled':\n case 'error':\n data = Math.round(evt.target.currentTime*1000);\n if(evt.type === 'error') {\n let errorTxt, mediaError=evt.currentTarget.error;\n switch(mediaError.code) {\n case mediaError.MEDIA_ERR_ABORTED:\n errorTxt = 'You aborted the video playback';\n break;\n case mediaError.MEDIA_ERR_DECODE:\n errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support';\n handleMediaError();\n break;\n case mediaError.MEDIA_ERR_NETWORK:\n errorTxt = 'A network error caused the video download to fail part-way';\n break;\n case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:\n errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported';\n break;\n }\n\n if (mediaError.message) {\n errorTxt += ' - ' + mediaError.message;\n }\n\n logStatus(errorTxt);\n console.error(errorTxt);\n }\n break;\n default:\n break;\n }\n\n let event = {\n time: performance.now() - events.t0,\n type: evt.type,\n name: data\n };\n\n events.video.push(event);\n if(evt.type === 'seeking') {\n lastSeekingIdx = events.video.length-1;\n }\n\n if(evt.type === 'seeked') {\n events.video[lastSeekingIdx].duration = event.time - events.video[lastSeekingIdx].time;\n }\n\n trimEventHistory();\n}\n\nfunction handleMediaError() {\n if(autoRecoverError) {\n let now = performance.now();\n if(!recoverDecodingErrorDate || (now - recoverDecodingErrorDate) > 3000) {\n recoverDecodingErrorDate = performance.now();\n $('#statusOut').append(', trying to recover media error.');\n hls.recoverMediaError();\n } else {\n if(!recoverSwapAudioCodecDate || (now - recoverSwapAudioCodecDate) > 3000) {\n recoverSwapAudioCodecDate = performance.now();\n $('#statusOut').append(', trying to swap audio codec and recover media error.');\n hls.swapAudioCodec();\n hls.recoverMediaError();\n } else {\n $('#statusOut').append(', cannot recover. Last media error recovery failed.');\n }\n }\n }\n}\n\nfunction timeRangesToString(r) {\n let log = '';\n for (let i=0; i= r.start(i) && pos < r.end(i)) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferLen = r.end(i) - pos;\n }\n }\n // check if we are in buffering / or playback ended state\n if(bufferLen <= 0.1 && v.paused === false && (pos-lastStartPosition) > 0.5) {\n // don't create buffering event if we are at the end of the playlist, don't report ended for live playlist\n if(lastDuration -pos <= 0.5 && events.isLive === false) {\n } else {\n // we are not at the end of the playlist ... real buffering\n if(bufferingIdx !== -1) {\n bufferingDuration = performance.now() - events.t0 - events.video[bufferingIdx].time;\n events.video[bufferingIdx].duration = bufferingDuration;\n events.video[bufferingIdx].name = bufferingDuration;\n } else {\n events.video.push({\n type: 'buffering',\n time: performance.now() - events.t0\n });\n trimEventHistory();\n // we are in buffering state\n bufferingIdx = events.video.length-1;\n }\n }\n }\n\n if(bufferLen > 0.1 && bufferingIdx !=-1) {\n bufferingDuration = performance.now() - events.t0 - events.video[bufferingIdx].time;\n events.video[bufferingIdx].duration = bufferingDuration;\n events.video[bufferingIdx].name = bufferingDuration;\n // we are out of buffering state\n bufferingIdx = -1;\n }\n\n // update buffer/position for current Time\n let event = {\n time : performance.now() - events.t0,\n buffer: Math.round(bufferLen*1000),\n pos : Math.round(pos*1000)\n };\n let bufEvents = events.buffer, bufEventLen = bufEvents.length;\n if(bufEventLen > 1) {\n let event0 = bufEvents[bufEventLen-2], event1 = bufEvents[bufEventLen-1];\n let slopeBuf0 = (event0.buffer - event1.buffer)/(event0.time-event1.time);\n let slopeBuf1 = (event1.buffer - event.buffer)/(event1.time-event.time);\n\n let slopePos0 = (event0.pos - event1.pos)/(event0.time-event1.time);\n let slopePos1 = (event1.pos - event.pos)/(event1.time-event.time);\n // compute slopes. if less than 30% difference, remove event1\n if((slopeBuf0 === slopeBuf1 || Math.abs(slopeBuf0/slopeBuf1 -1) <= 0.3) &&\n (slopePos0 === slopePos1 || Math.abs(slopePos0/slopePos1 -1) <= 0.3))\n {bufEvents.pop();}\n\n }\n events.buffer.push(event);\n trimEventHistory();\n refreshCanvas();\n\n let log = 'Duration: '\n + v.duration + '\\n'\n + 'Buffered: '\n + timeRangesToString(v.buffered) + '\\n'\n + 'Seekable: '\n + timeRangesToString(v.seekable) + '\\n'\n + 'Played: '\n + timeRangesToString(v.played) + '\\n';\n\n if (hls.media) {\n for(let type in tracks) {\n log += 'Buffer for ' + type + ' contains: ' + timeRangesToString(tracks[type].buffer.buffered) + '\\n';\n }\n\n const videoPlaybackQuality = v.getVideoPlaybackQuality;\n if(videoPlaybackQuality && typeof (videoPlaybackQuality) === typeof (Function)) {\n log += 'Dropped frames: '+ v.getVideoPlaybackQuality().droppedVideoFrames + '\\n';\n log += 'Corrupted frames:'+ v.getVideoPlaybackQuality().corruptedVideoFrames + '\\n';\n } else if(v.webkitDroppedFrameCount) {\n log+='Dropped frames:'+ v.webkitDroppedFrameCount + '\\n';\n }\n }\n $('#bufferedOut').text(log);\n\n $('#statisticsOut').text(JSON.stringify(sortObject(stats), null, '\\t'));\n\n ctx.fillStyle = 'blue';\n\n const x = v.currentTime / v.duration * canvas.width;\n ctx.fillRect(x, 0, 2, 15);\n }\n\n}\n\nfunction showCanvas() {\n showMetrics();\n $('#bufferedOut').show();\n $('#bufferedCanvas').show();\n}\n\nfunction hideCanvas() {\n hideMetrics();\n $('#bufferedOut').hide();\n $('#bufferedCanvas').hide();\n}\n\nfunction getMetrics() {\n let json = JSON.stringify(events);\n let jsonpacked = jsonpack.pack(json);\n // console.log('packing JSON from ' + json.length + ' to ' + jsonpacked.length + ' bytes');\n return btoa(jsonpacked);\n}\n\nfunction copyMetricsToClipBoard() {\n copyTextToClipboard(getMetrics());\n}\n\nfunction goToMetrics() {\n let url = document.URL;\n url = url.substr(0, url.lastIndexOf('/')+1) + 'metrics.html';\n // console.log(url);\n window.open(url, '_blank');\n}\n\nfunction goToMetricsPermaLink() {\n let url = document.URL;\n let b64 = getMetrics();\n url = url.substr(0, url.lastIndexOf('/')+1) + 'metrics.html#data=' + b64;\n // console.log(url);\n window.open(url, '_blank');\n}\n\nfunction minsecs(ts) {\n let m = Math.floor(Math.floor(ts % 3600) / 60);\n let s = Math.floor(ts % 60);\n return m + ':' + (s < 10 ? '0' : '') + s;\n}\n\nfunction onClickBufferedRange(event) {\n let canvas = $('#bufferedCanvas')[0];\n let v = $('#video')[0];\n let target = (event.clientX - canvas.offsetLeft) / canvas.width * v.duration;\n v.currentTime = target;\n}\n\nfunction updateLevelInfo() {\n\n if (!hls.levels) {\n return;\n }\n\n let button_template = '';\n\n html2 += button_template;\n if(hls.loadLevel === i) {\n html2 += button_enabled;\n } else {\n html2 += button_disabled;\n }\n\n html2 += 'onclick=\"hls.loadLevel=' + i + '\">' + levelName + '';\n\n html3 += button_template;\n if(hls.autoLevelCapping === i) {\n html3 += button_enabled;\n } else {\n html3 += button_disabled;\n }\n\n html3 += 'onclick=\"levelCapping=hls.autoLevelCapping=' + i + ';updateLevelInfo();onDemoConfigChanged();\">' + levelName + '';\n\n html4 += button_template;\n if(hls.nextLevel === i) {\n html4 += button_enabled;\n } else {\n html4 += button_disabled;\n }\n\n html4 += 'onclick=\"hls.nextLevel=' + i + '\">' + levelName + '';\n }\n\n let v = $('#video')[0];\n\n if(v.videoWidth && v.videoHeight) {\n $('#currentResolution').html(v.videoWidth + ' x ' + v.videoHeight);\n }\n\n if($('#currentLevelControl').html() != html1) {\n $('#currentLevelControl').html(html1);\n }\n\n if($('#loadLevelControl').html() != html2) {\n $('#loadLevelControl').html(html2);\n }\n\n if($('#levelCappingControl').html() != html3) {\n $('#levelCappingControl').html(html3);\n }\n\n if($('#nextLevelControl').html() != html4) {\n $('#nextLevelControl').html(html4);\n }\n}\n\nfunction updateAudioTrackInfo() {\n let button_template = '';\n }\n $('#audioTrackControl').html(html1);\n}\n\nfunction level2label(index) {\n if(hls && hls.levels.length-1 >= index) {\n let level = hls.levels[index];\n if (level.name) {\n return level.name;\n } else {\n if (level.height) {\n return(level.height + 'p / ' + Math.round(level.bitrate / 1024) + 'kb');\n } else {\n if(level.bitrate) {\n return(Math.round(level.bitrate / 1024) + 'kb');\n } else {\n return null;\n }\n }\n }\n }\n}\n\nfunction getDemoConfigPropOrDefault(propName, defaultVal) {\n return typeof demoConfig[propName] !== 'undefined' ? demoConfig[propName] : defaultVal;\n}\n\nfunction getURLParam(sParam, defaultValue) {\n let sPageURL = window.location.search.substring(1);\n let sURLVariables = sPageURL.split('&');\n for (let i = 0; i < sURLVariables.length; i++) {\n let sParameterName = sURLVariables[i].split('=');\n if (sParameterName[0] == sParam)\n {return 'undefined' == sParameterName[1] ? undefined : 'false' == sParameterName[1] ? false : sParameterName[1];}\n\n }\n return defaultValue;\n}\n\nfunction onDemoConfigChanged() {\n const url = $('#streamURL').val();\n\n demoConfig = {\n enableStreaming,\n autoRecoverError,\n enableWorker,\n dumpfMP4,\n levelCapping,\n limitMetrics,\n defaultAudioCodec,\n widevineLicenseUrl: escape(widevineLicenseUrl)\n }\n\n const serializedDemoConfig = btoa(JSON.stringify(demoConfig))\n\n const baseURL = document.URL.split('?')[0]\n const permalinkURL = baseURL + `?src=${encodeURIComponent(url)}&demoConfig=${serializedDemoConfig}`\n\n $('#StreamPermalink').html('' + permalinkURL + '');\n}\n\nfunction createfMP4(type) {\n if (fmp4Data[type].length) {\n let blob = new Blob([arrayConcat(fmp4Data[type])], {\n type: 'application/octet-stream'\n });\n let filename = type + '-' + new Date().toISOString() + '.mp4';\n saveAs(blob, filename);\n //$('body').append('Download ' + filename + ' track
');\n }\n}\n\nfunction arrayConcat(inputArray) {\n let totalLength = inputArray.reduce( function(prev, cur) { return prev+cur.length; }, 0);\n let result = new Uint8Array(totalLength);\n let offset = 0;\n inputArray.forEach(function(element) {\n result.set(element, offset);\n offset += element.length;\n });\n return result;\n}\n\nfunction hideAllTabs() {\n $('#playbackControlTab').hide();\n $('#qualityLevelControlTab').hide();\n $('#audioTrackControlTab').hide();\n $('#metricsDisplayTab').hide();\n $('#statsDisplayTab').hide();\n}\n\nfunction toggleTab(tabElId) {\n hideAllTabs();\n hideMetrics();\n $('#' + tabElId).show();\n}\n\nfunction appendLog(textElId, message) {\n const el = $('#' + textElId)\n let logText = el.text()\n if (logText.length) {\n logText += '\\n'\n }\n const timestamp = (Date.now() - startTime) / 1000\n const newMessage = timestamp + ' | ' + message\n logText += newMessage\n // update\n el.text(logText)\n}\n\nfunction logStatus(message) {\n appendLog('statusOut', message)\n}\n\nfunction logError(message) {\n appendLog('errorOut', message)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./demo/main.js","export function sortObject(obj) {\n if(typeof obj !== 'object') {\n return obj;\n }\n let temp = {};\n let keys = [];\n for(let key in obj) {\n keys.push(key);\n }\n keys.sort();\n for(let index in keys) {\n temp[keys[index]] = sortObject(obj[keys[index]]);\n }\n return temp;\n}\n\nexport function copyTextToClipboard(text) {\n let textArea = document.createElement('textarea');\n textArea.value = text;\n document.body.appendChild(textArea);\n textArea.select();\n try {\n let successful = document.execCommand('copy');\n let msg = successful ? 'successful' : 'unsuccessful';\n console.log('Copying text command was ' + msg);\n } catch (err) {\n console.log('Oops, unable to copy');\n }\n document.body.removeChild(textArea);\n}\n\n\n\n\n// WEBPACK FOOTER //\n// ./demo/demo-utils.js","/**\n * Create test stream\n * @param {string} url\n * @param {string} description\n * @param {boolean} [live]\n * @param {boolean} [abr]\n * @param {string[]} [blacklist_ua]\n * @returns {{url: string, description: string, live: boolean, abr: boolean, blacklist_ua: string[]}}\n */\nfunction createTestStream (url, description, live = false, abr = true, blacklist_ua = []) {\n return {\n url,\n description,\n live,\n abr,\n blacklist_ua\n };\n}\n\n/**\n * @param {Object} target\n * @param {Object} [config]\n * @returns {{url: string, description: string, live: boolean, abr: boolean, blacklist_ua: string[]}}\n */\nfunction createTestStreamWithConfig (target, config) {\n if (typeof target !== 'object') {\n throw new Error('target should be object');\n }\n\n const testStream = createTestStream(target.url, target.description, target.live, target.abr, target.blacklist_ua);\n\n testStream.config = config;\n\n return testStream;\n}\n\nmodule.exports = {\n bbb: createTestStreamWithConfig({\n url: 'https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8',\n description: 'Big Buck Bunny - adaptive qualities'\n },\n {\n // try to workaround test failing because of slow seek on Chrome/Win10\n nudgeMaxRetry: 5\n }\n ),\n bigBuckBunny480p: {\n 'url': 'https://video-dev.github.io/streams/x36xhzz/url_6/193039199_mp4_h264_aac_hq_7.m3u8',\n 'description': 'Big Buck Bunny - 480p only',\n 'live': false,\n 'abr': false,\n 'blacklist_ua': ['internet explorer']\n },\n arte: {\n 'url': 'https://video-dev.github.io/streams/test_001/stream.m3u8',\n 'description': 'ARTE China,ABR',\n 'live': false,\n 'abr': true\n },\n deltatreDAI: {\n 'url': 'https://video-dev.github.io/streams/dai-discontinuity-deltatre/manifest.m3u8',\n 'description': 'Ad-insertion in event stream',\n 'live': false,\n 'abr': false,\n 'blacklist_ua': ['internet explorer']\n },\n issue666: {\n 'url': 'https://video-dev.github.io/streams/issue666/playlists/cisq0gim60007xzvi505emlxx.m3u8',\n 'description': 'hls.js/issues/666',\n 'live': false,\n 'abr': false,\n 'blacklist_ua': ['internet explorer']\n },\n issue649: {\n 'url': 'http://cdn3.screen9.com/media/c/W/cW87csHkxsgu5TV1qs78aA_auto_hls.m3u8?auth=qlUjeCtbVdtkDfZYrtveTIVUXX1yuSqgF8wfWabzKpX72r-d5upW88-FHuyRRdnZA_1PKRTGAtTt_6Z-aj22kw',\n 'description': 'hls.js/issues/649',\n 'live': false,\n 'abr': false\n },\n closedCaptions: {\n 'url': 'http://playertest.longtailvideo.com/adaptive/captions/playlist.m3u8',\n 'description': 'CNN special report, with CC',\n 'live': false,\n 'abr': false,\n 'blacklist_ua': ['safari']\n },\n oceansAES: {\n 'url': 'http://playertest.longtailvideo.com/adaptive/oceans_aes/oceans_aes.m3u8',\n 'description': 'AES encrypted,ABR',\n 'live': false,\n 'abr': true\n },\n /*\n bbbAES: {\n 'url': 'https://video-dev.github.io/streams/bbbAES/playlists/sample_aes/index.m3u8',\n 'description': 'SAMPLE-AES encrypted',\n 'live': false,\n 'abr': false\n },\n */\n mp3Audio: {\n 'url': 'https://player.webvideocore.net/CL1olYogIrDWvwqiIKK7eLBkzvO18gwo9ERMzsyXzwt_t-ya8ygf2kQBZww38JJT/8i4vvznv8408.m3u8',\n 'description': 'MP3 VOD demo',\n 'live': false,\n 'abr': false,\n 'blacklist_ua': ['safari']\n },\n mpegAudioOnly: {\n 'url': 'https://pl.streamingvideoprovider.com/mp3-playlist/playlist.m3u8',\n 'description': 'MPEG Audio Only demo',\n 'live': false,\n 'abr': false,\n 'blacklist_ua': ['internet explorer', 'MicrosoftEdge', 'safari', 'firefox']\n },\n fmp4: {\n 'url': 'https://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8',\n 'description': 'HLS fMP4 Angel-One multiple audio-tracks',\n 'live': false,\n 'abr': false,\n 'blacklist_ua': ['safari', 'internet explorer']\n },\n fmp4Bitmovin: {\n 'url': 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s-fmp4/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8',\n 'description': 'HLS fMP4 by Bitmovin',\n 'live': false,\n 'abr': true,\n 'blacklist_ua': ['safari', 'internet explorer']\n },\n offset_pts: {\n 'url': 'https://video-dev.github.io/streams/pts_shift/master.m3u8',\n 'description': 'DK Turntable, PTS shifted by 2.3s',\n 'live': false,\n 'abr': false\n },\n /*\n uspHLSAteam: createTestStream(\n 'http://demo.unified-streaming.com/video/ateam/ateam.ism/ateam.m3u8?session_id=27199',\n 'A-Team movie trailer - HLS by Unified Streaming Platform'\n ),\n */\n angelOneShakaWidevine: createTestStreamWithConfig({\n url: 'https://storage.googleapis.com/shaka-demo-assets/angel-one-widevine-hls/hls.m3u8',\n description: 'Shaka-packager Widevine DRM (EME) HLS-fMP4 - Angel One Demo',\n blacklist_ua: ['firefox', 'safari', 'internet explorer']\n },\n {\n widevineLicenseUrl: 'https://cwip-shaka-proxy.appspot.com/no_auth',\n emeEnabled: true\n }\n ),\n audioOnlyMultipleLevels: {\n 'url': 'https://s3.amazonaws.com/bob.jwplayer.com/~alex/121628/new_master.m3u8',\n 'description': 'Multiple non-alternate audio levels',\n 'live': false,\n 'abr': false\n },\n pdtDuplicate: {\n url: 'https://playertest.longtailvideo.com/adaptive/artbeats/manifest.m3u8',\n description: 'Stream with duplicate sequential PDT values'\n },\n pdtLargeGap: {\n url: 'https://playertest.longtailvideo.com/adaptive/boxee/playlist.m3u8',\n description: 'PDTs with large gaps following discontinuities'\n },\n pdtBadValues: {\n url: 'https://playertest.longtailvideo.com/adaptive/progdatime/playlist2.m3u8',\n description: 'PDTs with bad values'\n },\n pdtOneValue: {\n url: 'https://playertest.longtailvideo.com/adaptive/aviion/manifest.m3u8',\n description: 'One PDT, no discontinuities'\n }\n};\n\n\n\n// WEBPACK FOOTER //\n// ./tests/test-streams.js"],"sourceRoot":""} \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls.js b/grails-app/assets/bower/hls.js/dist/hls.js new file mode 100644 index 000000000..aa1f390d5 --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls.js @@ -0,0 +1,18922 @@ +(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 = 10); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 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; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__get_self_scope__ = __webpack_require__(3); +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; + +// 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; +} + +var global = Object(__WEBPACK_IMPORTED_MODULE_0__get_self_scope__["a" /* getSelfScope */])(); + +function consolePrintFn(type) { + var func = global.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(global.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"; +/** + * @readonly + * @enum {string} + */ +var HlsEvents = { + // 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 } + 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 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' +}; + +/* harmony default export */ __webpack_exports__["a"] = (HlsEvents); + +/***/ }), +/* 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', + // EME (encrypted media extensions) errors + KEY_SYSTEM_ERROR: 'keySystemError', + // Identifier for a mux Error (demuxing/remuxing) + MUX_ERROR: 'muxError', + // Identifier for all other errors + OTHER_ERROR: 'otherError' +}; + +/** + * @enum {ErrorDetails} + * @typedef {string} ErrorDetail + */ +var ErrorDetails = { + KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys', + KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess', + KEY_SYSTEM_NO_SESSION: 'keySystemNoSession', + KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed', + // 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 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 (immutable) */ __webpack_exports__["a"] = getSelfScope; +function getSelfScope() { + // see https://stackoverflow.com/a/11237259/589493 + if (typeof window === 'undefined') { + /* eslint-disable-next-line no-undef */ + return self; + } else { + return window; + } +} + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +// see https://tools.ietf.org/html/rfc1808 + +/* jshint ignore:start */ +(function(root) { +/* jshint ignore:end */ + + var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/; + 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 (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 */ + + +/***/ }), +/* 5 */ +/***/ (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, true); + 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 exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + 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 (c === 0x00 && exitOnNull) { + return out; + } else if (c === 0x00 || c === 0x03) { + // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it + 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); + + + +/***/ }), +/* 6 */ +/***/ (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; +} + + +/***/ }), +/* 7 */ +/***/ (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"); } } + +// PKCS7 +function removePadding(buffer) { + var outputBytes = buffer.byteLength; + var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1); + if (paddingBytes) { + return buffer.slice(0, outputBytes - paddingBytes); + } else { + return buffer; + } +} + +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, removePKCS7Padding) { + 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 = void 0, + i = void 0; + 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 removePKCS7Padding ? removePadding(outputInt32.buffer) : 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); + +// EXTERNAL MODULE: ./src/events.js +var events = __webpack_require__(1); + +// EXTERNAL MODULE: ./src/utils/get-self-scope.js +var get_self_scope = __webpack_require__(3); + +// 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"); } } + + + + + + + + + + + + +// see https://stackoverflow.com/a/11237259/589493 +var global = Object(get_self_scope["a" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread + +var decrypter_Decrypter = function () { + function Decrypter(observer, config) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$removePKCS7Paddi = _ref.removePKCS7Padding, + removePKCS7Padding = _ref$removePKCS7Paddi === undefined ? true : _ref$removePKCS7Paddi; + + decrypter__classCallCheck(this, Decrypter); + + this.logEnabled = true; + this.observer = observer; + this.config = config; + this.removePKCS7Padding = removePKCS7Padding; + // built in decryptor expects PKCS7 padding + if (removePKCS7Padding) { + try { + var browserCrypto = global.crypto; + if (browserCrypto) { + 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, this.removePKCS7Padding)); + } 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(events["a" /* default */].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); + +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1); +function _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 = function () { + function MP4Demuxer(observer, remuxer) { + _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(__WEBPACK_IMPORTED_MODULE_1__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.readUint16 = function readUint16(buffer, offset) { + if (buffer.data) { + offset += buffer.start; + buffer = buffer.data; + } + + var val = buffer[offset] << 8 | buffer[offset + 1]; + + return val < 0 ? 65536 + val : val; + }; + + 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 = void 0, + size = void 0, + type = void 0, + end = void 0, + subresults = void 0, + start = void 0, + endbox = void 0; + + 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; + }; + + MP4Demuxer.parseSegmentIndex = function parseSegmentIndex(initSegment) { + var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0]; + var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data + + var index = 0; + var sidx = MP4Demuxer.findBox(initSegment, ['sidx']); + var references = void 0; + + if (!sidx || !sidx[0]) { + return null; + } + + references = []; + sidx = sidx[0]; + + var version = sidx.data[0]; + + // set initial offset, we skip the reference ID (not needed) + index = version === 0 ? 8 : 16; + + var timescale = MP4Demuxer.readUint32(sidx, index); + index += 4; + + // TODO: parse earliestPresentationTime and firstOffset + // usually zero in our case + var earliestPresentationTime = 0; + var firstOffset = 0; + + if (version === 0) { + index += 8; + } else { + index += 16; + } + + // skip reserved + index += 2; + + var startByte = sidx.end + firstOffset; + + var referencesCount = MP4Demuxer.readUint16(sidx, index); + index += 2; + + for (var i = 0; i < referencesCount; i++) { + var referenceIndex = index; + + var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex); + referenceIndex += 4; + + var referenceSize = referenceInfo & 0x7FFFFFFF; + var referenceType = (referenceInfo & 0x80000000) >>> 31; + + if (referenceType === 1) { + console.warn('SIDX has hierarchical references (not supported)'); + return; + } + + var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex); + referenceIndex += 4; + + references.push({ + referenceSize: referenceSize, + subsegmentDuration: subsegmentDuration, // unscaled + info: { + duration: subsegmentDuration / timescale, + start: startByte, + end: startByte + referenceSize - 1 + } + }); + + startByte += referenceSize; + + // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits + // for |sapDelta|. + referenceIndex += 4; + + // skip to next ref + index = referenceIndex; + } + + return { + earliestPresentationTime: earliestPresentationTime, + timescale: timescale, + version: version, + referencesCount: referencesCount, + references: references, + moovEndOffset: moovEndOffset + }; + }; + + /** + * 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)); + __WEBPACK_IMPORTED_MODULE_0__utils_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 = void 0, + baseTimes = void 0, + result = void 0; + + // 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 = void 0, + scale = void 0, + baseTime = void 0; + + // 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 = void 0, + result = void 0; + + 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, false); + 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(__WEBPACK_IMPORTED_MODULE_1__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 */ __webpack_exports__["a"] = (MP4Demuxer); + +/***/ }), +/* 9 */ +/***/ (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__(7); + +// EXTERNAL MODULE: ./src/utils/logger.js +var logger = __webpack_require__(0); + +// EXTERNAL MODULE: ./src/utils/get-self-scope.js +var get_self_scope = __webpack_require__(3); + +// CONCATENATED MODULE: ./src/demux/adts.js +/** + * ADTS parser helper + */ + + + + + + + +function getAudioConfig(observer, data, offset, audioCodec) { + var adtsObjectType = void 0, + // :int + adtsSampleingIndex = void 0, + // :int + adtsExtensionSampleingIndex = void 0, + // :int + adtsChanelConfig = void 0, + // :int + config = void 0, + 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(events["a" /* default */].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 = void 0, + frameLength = void 0, + stamp = void 0; + 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__(5); + +// 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); +// EXTERNAL MODULE: ./src/demux/mp4demuxer.js +var mp4demuxer = __webpack_require__(8); + +// 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], + + SamplesCoefficients: [ + // MPEG 2.5 + [0, // Reserved + 72, // Layer3 + 144, // Layer2 + 12 // Layer1 + ], + // Reserved + [0, // Reserved + 0, // Layer3 + 0, // Layer2 + 0 // Layer1 + ], + // MPEG 2 + [0, // Reserved + 72, // Layer3 + 144, // Layer2 + 12 // Layer1 + ], + // MPEG 1 + [0, // Reserved + 144, // Layer3 + 144, // Layer2 + 12 // Layer1 + ]], + + BytesInSlot: [0, // Reserved + 1, // Layer3 + 1, // Layer2 + 4 // Layer1 + ], + + 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 = header.samplesPerFrame * 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] >> 1 & 1; + 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 channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono) + var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC]; + var bytesInSlot = MpegAudio.BytesInSlot[headerC]; + var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot; + var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot; + + return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame }; + } + + 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 = void 0; // :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 = void 0; // :uint + for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { + if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) { + // 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 this.readBits(1) === 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 = void 0, + deltaScale = void 0; + 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 = void 0, + profileCompat = void 0, + levelIdc = void 0, + numRefFramesInPicOrderCntCycle = void 0, + picWidthInMbsMinus1 = void 0, + picHeightInMapUnitsMinus1 = void 0, + frameMbsOnlyFlag = void 0, + scalingListCount = void 0, + i = void 0, + 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, { removePKCS7Padding: false }); + } + + 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: 1, + audio: 2, + id3: 3, + text: 4 +}; + +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 = void 0, + len = data.length, + stt = void 0, + pid = void 0, + atf = void 0, + offset = void 0, + pes = void 0, + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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 = void 0, + tableEnd = void 0, + programInfoLength = void 0, + pid = void 0, + 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 = void 0, + pesFlags = void 0, + pesPrefix = void 0, + pesLen = void 0, + pesHdrLen = void 0, + pesData = void 0, + pesPts = void 0, + pesDts = void 0, + payloadStartOffset = void 0, + 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 = void 0, + avcSample = this.avcSample, + push = void 0, + spsfound = false, + i = void 0, + 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 = void 0, + overflow = void 0, + track = this._avcTrack, + state = track.naluState || 0, + lastState = state; + var units = [], + unit = void 0, + unitType = void 0, + lastUnitStart = -1, + lastUnitType = void 0; + // 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 = void 0, + newData = void 0; + + // 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 = void 0, + frameIndex = void 0, + offset = void 0, + stamp = void 0, + len = void 0; + 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 = void 0, + fatal = void 0; + 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 = void 0, + length = void 0; + 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 timestamp = id3["a" /* default */].getTimeStamp(id3Data); + var pts = timestamp ? 90 * timestamp : timeOffset * 90000; + 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/remux/aac-helper.js +function aac_helper__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_helper__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_helper = (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 +*/ + +var 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 = void 0; + 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 // sample_count + ]); + 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 = void 0; + // 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 / (UINT32_MAX + 1)); + var lowerWordDuration = Math.floor(duration % (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 / (UINT32_MAX + 1)); + var lowerWordDuration = Math.floor(duration % (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 = void 0, + i = void 0; + // 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 = void 0, + data = void 0, + len = void 0; + // 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 = sps.concat(Array.prototype.slice.call(data)); + } + + // 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]; + + 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 / (UINT32_MAX + 1)), + lowerWordDuration = Math.floor(duration % (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 / (UINT32_MAX + 1)), + lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (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 = void 0, + sample = void 0, + duration = void 0, + size = void 0, + flags = void 0, + cts = void 0; + 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 = void 0; + 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 { + // logger.log('nb AVC samples:' + videoTrack.samples.length); + if (nbVideoSamples) { + var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, 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 = void 0, + initDTS = void 0; + + 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 = void 0, + mdat = void 0, + moof = void 0, + firstPTS = void 0, + firstDTS = void 0, + nextDTS = void 0, + lastPTS = void 0, + lastDTS = void 0, + 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; + + if (nbSamples === 0) { + return; + } + + // 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 || 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 maxBufferHole. + // 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, + gapTolerance = Math.floor(maxBufferHole * 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 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', + hasAudio: false, + hasVideo: true, + 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 = void 0, + mp4Sample = void 0, + fillFrame = void 0, + mdat = void 0, + moof = void 0, + firstPTS = void 0, + lastPTS = void 0, + 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); + + // compute normalized PTS + inputSamples.forEach(function (sample) { + sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale); + }); + + // filter out sample with negative PTS that are not playable anyway + // if we don't remove these negative samples, they will shift all audio samples forward. + // leading to audio overlap between current / next fragment + inputSamples = inputSamples.filter(function (sample) { + return sample.pts >= 0; + }); + + // in case all samples have negative PTS, and have been filtered out, return now + if (inputSamples.length === 0) { + return; + } + + if (!contiguous) { + if (!accurateTimeOffset) { + // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS + nextAudioPts = inputSamples[0].pts; + } else { + // if timeOffset is accurate, let's use it as predicted next audio PTS + nextAudioPts = timeOffset * inputTimeScale; + } + } + + // 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. + + if (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; + + 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 + } // eslint-disable-line brace-style + + // 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_helper.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_helper.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 + firstPTS = _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_helper.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', + hasAudio: true, + hasVideo: false, + 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_helper.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 = void 0; + 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 = void 0; + 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 = void 0; + 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, + hasAudio: !!audioTrack, + hasVideo: !!videoTrack, + 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, ...) + * + */ + + + + + + + + + + + + + +// see https://stackoverflow.com/a/11237259/589493 +var global = Object(get_self_scope["a" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread +var performance = global; + +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 = void 0; + try { + startTime = performance.now(); + } catch (error) { + startTime = Date.now(); + } + decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) { + var endTime = void 0; + 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, or track switch + // we might switch from content type (AAC container to TS container, or TS to fmp4 for example) + // so let's check that current demuxer is still valid + (discontinuity || trackSwitch) && !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: mp4demuxer["a" /* default */], remux: passthrough_remuxer }, { demux: aacdemuxer, remux: mp4_remuxer }, { demux: mp3demuxer, remux: mp4_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); + +/***/ }), +/* 10 */ +/***/ (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__(4); +var url_toolkit_default = /*#__PURE__*/__webpack_require__.n(url_toolkit); + +// EXTERNAL MODULE: ./src/errors.js +var errors = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/events.js +var events = __webpack_require__(1); + +// 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 FORBIDDEN_EVENT_NAMES = new Set(['hlsEventGeneric', 'hlsHandlerDestroying', 'hlsHandlerDestroyed']); + +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.onHandlerDestroying(); + this.unregisterListeners(); + this.onHandlerDestroyed(); + }; + + EventHandler.prototype.onHandlerDestroying = function onHandlerDestroying() {}; + + EventHandler.prototype.onHandlerDestroyed = function onHandlerDestroyed() {}; + + 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 (FORBIDDEN_EVENT_NAMES.has(event)) { + 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('An internal error happened while handling event ' + event + '. Error message: "' + err.message + '". Here is a stacktrace:', err); + 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); +// EXTERNAL MODULE: ./src/demux/mp4demuxer.js +var mp4demuxer = __webpack_require__(8); + +// CONCATENATED MODULE: ./src/loader/level-key.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 level_key__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + +var level_key_LevelKey = function () { + function LevelKey() { + level_key__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; +}(); + +/* harmony default export */ var level_key = (level_key_LevelKey); +// CONCATENATED MODULE: ./src/loader/fragment.js +var fragment__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 fragment__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + +var fragment_Fragment = function () { + function Fragment() { + var _elementaryStreams; + + fragment__classCallCheck(this, Fragment); + + this._url = null; + this._byteRange = null; + this._decryptdata = null; + this.tagList = []; + + // Holds the types of data this fragment supports + this._elementaryStreams = (_elementaryStreams = {}, _elementaryStreams[Fragment.ElementaryStreamTypes.AUDIO] = false, _elementaryStreams[Fragment.ElementaryStreamTypes.VIDEO] = false, _elementaryStreams); + } + + /** + * `type` property for this._elementaryStreams + * + * @enum + */ + + + /** + * @param {ElementaryStreamType} type + */ + Fragment.prototype.addElementaryStream = function addElementaryStream(type) { + this._elementaryStreams[type] = true; + }; + + /** + * @param {ElementaryStreamType} type + */ + + + Fragment.prototype.hasElementaryStream = function hasElementaryStream(type) { + return this._elementaryStreams[type] === true; + }; + + /** + * 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 level_key(); + decryptdata.method = levelkey.method; + decryptdata.baseuri = levelkey.baseuri; + decryptdata.reluri = levelkey.reluri; + decryptdata.iv = this.createInitializationVector(segmentNumber); + } + + return decryptdata; + }; + + fragment__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 && !this.rawByteRange) { + return []; + } + + if (this._byteRange) { + return this._byteRange; + } + + var byteRange = []; + if (this.rawByteRange) { + var params = this.rawByteRange.split('@', 2); + if (params.length === 1) { + var lastByteRangeEndOffset = this.lastByteRangeEndOffset; + byteRange[0] = lastByteRangeEndOffset || 0; + } else { + byteRange[0] = parseInt(params[1]); + } + byteRange[1] = parseInt(params[0]) + byteRange[0]; + this._byteRange = byteRange; + } + return byteRange; + } + + /** + * @type {number} + */ + + }, { + 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; + } + }, { + key: 'encrypted', + get: function get() { + return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null); + } + }], [{ + key: 'ElementaryStreamTypes', + get: function get() { + return { + AUDIO: 'audio', + VIDEO: 'video' + }; + } + }]); + + return Fragment; +}(); + +/* harmony default export */ var loader_fragment = (fragment_Fragment); +// 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+)$/; // eslint-disable-line no-useless-escape +var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape + +// 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 = void 0, + 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 window.MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs="' + codec + '"'); +} + + +// CONCATENATED MODULE: ./src/loader/m3u8-parser.js +function m3u8_parser__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + + + + + + +/** + * M3U8 parser + * @module + */ + +// 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 MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i; + +var m3u8_parser_M3U8Parser = function () { + function M3U8Parser() { + m3u8_parser__classCallCheck(this, M3U8Parser); + } + + M3U8Parser.findGroup = 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; + }; + + M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) { + var result = void 0, + 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; + }; + + M3U8Parser.resolve = function resolve(url, baseUrl) { + return url_toolkit_default.a.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true }); + }; + + M3U8Parser.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 = M3U8Parser.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 = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec); + } + + levels.push(level); + } + return levels; + }; + + M3U8Parser.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 = M3U8Parser.resolve(attrs.URI, baseurl); + } + + media.lang = attrs.LANGUAGE; + if (!media.name) { + media.name = media.lang; + } + + if (audioGroups.length) { + var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId); + media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec; + } + media.id = id++; + medias.push(media); + } + } + return medias; + }; + + M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) { + var currentSN = 0, + totalduration = 0, + level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 }, + levelkey = new level_key(), + cc = 0, + prevFrag = null, + frag = new loader_fragment(), + result = void 0, + i = void 0; + + 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 || 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.urlId = levelUrlId; + frag.baseurl = baseurl; + // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 + frag.relurl = (' ' + result[3]).slice(1); + + if (level.programDateTime) { + if (prevFrag) { + if (frag.rawProgramDateTime) { + // PDT discontinuity found + frag.pdt = Date.parse(frag.rawProgramDateTime); + } else { + // Contiguous fragment + frag.pdt = prevFrag.pdt + prevFrag.duration * 1000; + } + } else { + // First fragment + frag.pdt = Date.parse(level.programDateTime); + } + frag.endPdt = frag.pdt + frag.duration * 1000; + } + + level.fragments.push(frag); + prevFrag = frag; + totalduration += frag.duration; + + frag = new 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 level_key(); + if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].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 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; + + if (!level.initSegment && level.fragments.length) { + // this is a bit lurky but HLS really has no other way to tell us + // if the fragments are TS or MP4, except if we download them :/ + // but this is to be able to handle SIDX. + if (level.fragments.every(function (frag) { + return MP4_REGEX_SUFFIX.test(frag.relurl); + })) { + logger["b" /* logger */].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX'); + + frag = new loader_fragment(); + frag.relurl = level.fragments[0].relurl; + frag.baseurl = baseurl; + frag.level = id; + frag.type = type; + frag.sn = 'initSegment'; + + level.initSegment = frag; + level.needSidxRanges = true; + } + } + + return level; + }; + + return M3U8Parser; +}(); + +/* harmony default export */ var m3u8_parser = (m3u8_parser_M3U8Parser); +// CONCATENATED MODULE: ./src/loader/playlist-loader.js +var playlist_loader__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 playlist_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +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; } + +/** + * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models. + * + * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks. + * + * Uses loader(s) set in config to do actual internal loading of resource tasks. + * + * @module + * + */ + + + + + + + + + + +var _window = window, + performance = _window.performance; + +/** + * `type` property values for this loaders' context object + * @enum + * + */ + +var ContextType = { + MANIFEST: 'manifest', + LEVEL: 'level', + AUDIO_TRACK: 'audioTrack', + SUBTITLE_TRACK: 'subtitleTrack' +}; + +/** + * @enum {string} + */ +var LevelType = { + MAIN: 'main', + AUDIO: 'audio', + SUBTITLE: 'subtitle' +}; + +/** + * @constructor + */ + +var playlist_loader_PlaylistLoader = function (_EventHandler) { + _inherits(PlaylistLoader, _EventHandler); + + /** + * @constructs + * @param {Hls} hls + */ + 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; + } + + /** + * @param {ContextType} type + * @returns {boolean} + */ + PlaylistLoader.canHaveQualityLevels = function canHaveQualityLevels(type) { + return type !== ContextType.AUDIO_TRACK && type !== ContextType.SUBTITLE_TRACK; + }; + + /** + * Map context.type to LevelType + * @param {{type: ContextType}} context + * @returns {LevelType} + */ + + + PlaylistLoader.mapContextToLevelType = function mapContextToLevelType(context) { + var type = context.type; + + + switch (type) { + case ContextType.AUDIO_TRACK: + return LevelType.AUDIO; + case ContextType.SUBTITLE_TRACK: + return LevelType.SUBTITLE; + default: + return LevelType.MAIN; + } + }; + + PlaylistLoader.getResponseUrl = function getResponseUrl(response, context) { + var url = response.url; + // 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; + } + return url; + }; + + /** + * Returns defaults or configured loader-type overloads (pLoader and loader config params) + * Default loader is XHRLoader (see utils) + * @param {object} context + * @returns {XHRLoader} or other compatible configured overload + */ + + + PlaylistLoader.prototype.createInternalLoader = function createInternalLoader(context) { + var config = this.hls.config; + var PLoader = config.pLoader; + var Loader = config.loader; + var InternalLoader = PLoader || Loader; + + var loader = new InternalLoader(config); + + context.loader = loader; + this.loaders[context.type] = loader; + + return loader; + }; + + PlaylistLoader.prototype.getInternalLoader = function getInternalLoader(context) { + return this.loaders[context.type]; + }; + + PlaylistLoader.prototype.resetInternalLoader = function resetInternalLoader(contextType) { + if (this.loaders[contextType]) { + delete this.loaders[contextType]; + } + }; + + /** + * Call `destroy` on all internal loader instances mapped (one per context type) + */ + + + PlaylistLoader.prototype.destroyInternalLoaders = function destroyInternalLoaders() { + for (var contextType in this.loaders) { + var loader = this.loaders[contextType]; + if (loader) { + loader.destroy(); + } + + this.resetInternalLoader(contextType); + } + }; + + PlaylistLoader.prototype.destroy = function destroy() { + this.destroyInternalLoaders(); + + _EventHandler.prototype.destroy.call(this); + }; + + PlaylistLoader.prototype.onManifestLoading = function onManifestLoading(data) { + this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null }); + }; + + PlaylistLoader.prototype.onLevelLoading = function onLevelLoading(data) { + this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id }); + }; + + PlaylistLoader.prototype.onAudioTrackLoading = function onAudioTrackLoading(data) { + this.load(data.url, { type: ContextType.AUDIO_TRACK, level: 0, id: data.id }); + }; + + PlaylistLoader.prototype.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) { + this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: 0, id: data.id }); + }; + + PlaylistLoader.prototype.load = function load(url, context) { + var config = this.hls.config; + + logger["b" /* logger */].debug('Loading playlist of type ' + context.type + ', level: ' + context.level + ', id: ' + context.id); + + // Check if a loader for this context already exists + var loader = this.getInternalLoader(context); + if (loader) { + var loaderContext = loader.context; + if (loaderContext && loaderContext.url === url) { + // same URL can't overlap + logger["b" /* logger */].trace('playlist request ongoing'); + return false; + } else { + logger["b" /* logger */].warn('aborting previous loader for type: ' + context.type); + loader.abort(); + } + } + + var maxRetry = void 0, + timeout = void 0, + retryDelay = void 0, + maxRetryDelay = void 0; + + // apply different configs for retries depending on + // context (manifest, level, audio/subs playlist) + switch (context.type) { + case ContextType.MANIFEST: + maxRetry = config.manifestLoadingMaxRetry; + timeout = config.manifestLoadingTimeOut; + retryDelay = config.manifestLoadingRetryDelay; + maxRetryDelay = config.manifestLoadingMaxRetryTimeout; + break; + case ContextType.LEVEL: + // Disable internal loader retry logic, since we are managing retries in Level Controller + maxRetry = 0; + timeout = config.levelLoadingTimeOut; + // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config + break; + default: + maxRetry = config.levelLoadingMaxRetry; + timeout = config.levelLoadingTimeOut; + retryDelay = config.levelLoadingRetryDelay; + maxRetryDelay = config.levelLoadingMaxRetryTimeout; + break; + } + + loader = this.createInternalLoader(context); + + context.url = url; + context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this) + + var loaderConfig = { + timeout: timeout, + maxRetry: maxRetry, + retryDelay: retryDelay, + maxRetryDelay: maxRetryDelay + }; + + var loaderCallbacks = { + onSuccess: this.loadsuccess.bind(this), + onError: this.loaderror.bind(this), + onTimeout: this.loadtimeout.bind(this) + }; + + logger["b" /* logger */].debug('Calling internal loader delegate for URL: ' + url); + + loader.load(context, loaderConfig, loaderCallbacks); + + return true; + }; + + PlaylistLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) { + var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + + if (context.isSidxRequest) { + this._handleSidxRequest(response, context); + this._handlePlaylistLoaded(response, stats, context, networkDetails); + return; + } + + this.resetInternalLoader(context.type); + + var string = response.data; + + stats.tload = performance.now(); + // stats.mtime = new Date(target.getResponseHeader('Last-Modified')); + + // Validate if it is an M3U8 at all + if (string.indexOf('#EXTM3U') !== 0) { + this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails); + return; + } + + // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present) + if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) { + this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails); + } else { + this._handleMasterPlaylist(response, stats, context, networkDetails); + } + }; + + PlaylistLoader.prototype.loaderror = function loaderror(response, context) { + var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + this._handleNetworkError(context, networkDetails); + }; + + PlaylistLoader.prototype.loadtimeout = function loadtimeout(stats, context) { + var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + this._handleNetworkError(context, networkDetails, true); + }; + + PlaylistLoader.prototype._handleMasterPlaylist = function _handleMasterPlaylist(response, stats, context, networkDetails) { + var hls = this.hls; + var string = response.data; + + var url = PlaylistLoader.getResponseUrl(response, context); + + var levels = m3u8_parser.parseMasterPlaylist(string, url); + if (!levels.length) { + this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails); + return; + } + + // multi level playlist, parse level info + + var audioGroups = levels.map(function (level) { + return { + id: level.attrs.AUDIO, + codec: level.audioCodec + }; + }); + + var audioTracks = m3u8_parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups); + var subtitles = m3u8_parser.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 + }); + }; + + PlaylistLoader.prototype._handleTrackOrLevelPlaylist = function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) { + var hls = this.hls; + + var id = context.id, + level = context.level, + type = context.type; + + + var url = PlaylistLoader.getResponseUrl(response, context); + + var levelUrlId = isNaN(id) ? 0 : id; + var levelId = isNaN(level) ? levelUrlId : level; // level -> id -> 0 + var levelType = PlaylistLoader.mapContextToLevelType(context); + + var levelDetails = m3u8_parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId); + + // set stats on level structure + levelDetails.tload = stats.tload; + + // We have done our first request (Manifest-type) and receive + // not a master playlist but a chunk-list (track/level) + // We fire the manifest-loaded event anyway with the parsed level-details + // by creating a single-level structure for it. + if (type === ContextType.MANIFEST) { + var singleLevel = { + url: url, + details: levelDetails + }; + + hls.trigger(events["a" /* default */].MANIFEST_LOADED, { + levels: [singleLevel], + audioTracks: [], + url: url, + stats: stats, + networkDetails: networkDetails + }); + } + + // save parsing time + stats.tparsed = performance.now(); + + // in case we need SIDX ranges + // return early after calling load for + // the SIDX box. + if (levelDetails.needSidxRanges) { + var sidxUrl = levelDetails.initSegment.url; + this.load(sidxUrl, { + isSidxRequest: true, + type: type, + level: level, + levelDetails: levelDetails, + id: id, + rangeStart: 0, + rangeEnd: 2048, + responseType: 'arraybuffer' + }); + return; + } + + // extend the context with the new levelDetails property + context.levelDetails = levelDetails; + + this._handlePlaylistLoaded(response, stats, context, networkDetails); + }; + + PlaylistLoader.prototype._handleSidxRequest = function _handleSidxRequest(response, context) { + var sidxInfo = mp4demuxer["a" /* default */].parseSegmentIndex(new Uint8Array(response.data)); + sidxInfo.references.forEach(function (segmentRef, index) { + var segRefInfo = segmentRef.info; + var frag = context.levelDetails.fragments[index]; + + if (frag.byteRange.length === 0) { + frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start); + } + }); + + context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0'; + }; + + PlaylistLoader.prototype._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) { + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].NETWORK_ERROR, + details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, + fatal: true, + url: response.url, + reason: reason, + networkDetails: networkDetails + }); + }; + + PlaylistLoader.prototype._handleNetworkError = function _handleNetworkError(context, networkDetails) { + var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + logger["b" /* logger */].info('A network error occured while loading a ' + context.type + '-type playlist'); + + var details = void 0; + var fatal = void 0; + + var loader = this.getInternalLoader(context); + + switch (context.type) { + case ContextType.MANIFEST: + details = timeout ? errors["a" /* ErrorDetails */].MANIFEST_LOAD_TIMEOUT : errors["a" /* ErrorDetails */].MANIFEST_LOAD_ERROR; + fatal = true; + break; + case ContextType.LEVEL: + details = timeout ? errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT : errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR; + fatal = false; + break; + case ContextType.AUDIO_TRACK: + details = timeout ? errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT : errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR; + fatal = false; + break; + default: + // details = ...? + fatal = false; + } + + if (loader) { + loader.abort(); + this.resetInternalLoader(context.type); + } + + 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 + }); + }; + + PlaylistLoader.prototype._handlePlaylistLoaded = function _handlePlaylistLoaded(response, stats, context, networkDetails) { + var type = context.type, + level = context.level, + id = context.id, + levelDetails = context.levelDetails; + + + if (!levelDetails.targetduration) { + this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails); + return; + } + + var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type); + if (canHaveLevels) { + this.hls.trigger(events["a" /* default */].LEVEL_LOADED, { + details: levelDetails, + level: level || 0, + id: id || 0, + stats: stats, + networkDetails: networkDetails + }); + } else { + switch (type) { + case ContextType.AUDIO_TRACK: + this.hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADED, { + details: levelDetails, + id: id, + stats: stats, + networkDetails: networkDetails + }); + break; + case ContextType.SUBTITLE_TRACK: + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADED, { + details: levelDetails, + id: id, + stats: stats, + networkDetails: networkDetails + }); + break; + } + } + }; + + playlist_loader__createClass(PlaylistLoader, null, [{ + key: 'ContextType', + get: function get() { + return ContextType; + } + }, { + key: 'LevelType', + get: function get() { + return LevelType; + } + }]); + + 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 = {}; + + _EventHandler.prototype.destroy.call(this); + }; + + FragmentLoader.prototype.onFragLoading = function onFragLoading(data) { + var frag = data.frag, + type = frag.type, + loaders = this.loaders, + config = this.hls.config, + FragmentILoader = config.fLoader, + DefaultILoader = config.loader; + + // reset fragment state + frag.loaded = 0; + + var loader = loaders[type]; + if (loader) { + logger["b" /* logger */].warn('abort previous fragment loader for type: ' + type); + loader.abort(); + } + + loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(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/controller/fragment-tracker.js +function fragment_tracker__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function fragment_tracker__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_tracker__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; } + + + + +var FragmentState = { + NOT_LOADED: 'NOT_LOADED', + APPENDING: 'APPENDING', + PARTIAL: 'PARTIAL', + OK: 'OK' +}; + +var fragment_tracker_FragmentTracker = function (_EventHandler) { + fragment_tracker__inherits(FragmentTracker, _EventHandler); + + function FragmentTracker(hls) { + fragment_tracker__classCallCheck(this, FragmentTracker); + + var _this = fragment_tracker__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].FRAG_BUFFERED, events["a" /* default */].FRAG_LOADED)); + + _this.bufferPadding = 0.2; + + _this.fragments = Object.create(null); + _this.timeRanges = Object.create(null); + + _this.config = hls.config; + return _this; + } + + FragmentTracker.prototype.destroy = function destroy() { + this.fragments = null; + this.timeRanges = null; + this.config = null; + event_handler.prototype.destroy.call(this); + _EventHandler.prototype.destroy.call(this); + }; + + /** + * Return a Fragment that match the position and levelType. + * If not found any Fragment, return null + * @param {number} position + * @param {LevelType} levelType + * @returns {Fragment|null} + */ + + + FragmentTracker.prototype.getBufferedFrag = function getBufferedFrag(position, levelType) { + var fragments = this.fragments; + var bufferedFrags = Object.keys(fragments).filter(function (key) { + var fragmentEntity = fragments[key]; + if (fragmentEntity.body.type !== levelType) { + return false; + } + + if (!fragmentEntity.buffered) { + return false; + } + + var frag = fragmentEntity.body; + return frag.startPTS <= position && position <= frag.endPTS; + }); + if (bufferedFrags.length === 0) { + return null; + } else { + // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566 + var bufferedFragKey = bufferedFrags.pop(); + return fragments[bufferedFragKey].body; + } + }; + + /** + * Partial fragments effected by coded frame eviction will be removed + * The browser will unload parts of the buffer to free up memory for new buffer data + * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable) + * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio) + * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer + */ + + + FragmentTracker.prototype.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) { + var _this2 = this; + + var fragmentTimes = void 0, + time = void 0; + // Check if any flagged fragments have been unloaded + Object.keys(this.fragments).forEach(function (key) { + var fragmentEntity = _this2.fragments[key]; + if (fragmentEntity.buffered === true) { + var esData = fragmentEntity.range[elementaryStream]; + if (esData) { + fragmentTimes = esData.time; + for (var i = 0; i < fragmentTimes.length; i++) { + time = fragmentTimes[i]; + + if (_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) { + // Unregister partial fragment as it needs to load again to be reused + _this2.removeFragment(fragmentEntity.body); + break; + } + } + } + } + }); + }; + + /** + * Checks if the fragment passed in is loaded in the buffer properly + * Partially loaded fragments will be registered as a partial fragment + * @param {Object} fragment Check the fragment against all sourceBuffers loaded + */ + + + FragmentTracker.prototype.detectPartialFragments = function detectPartialFragments(fragment) { + var _this3 = this; + + var fragKey = this.getFragmentKey(fragment); + var fragmentEntity = this.fragments[fragKey]; + if (fragmentEntity) { + fragmentEntity.buffered = true; + + Object.keys(this.timeRanges).forEach(function (elementaryStream) { + if (fragment.hasElementaryStream(elementaryStream) === true) { + var timeRange = _this3.timeRanges[elementaryStream]; + // Check for malformed fragments + // Gaps need to be calculated for each elementaryStream + fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange); + } + }); + } + }; + + FragmentTracker.prototype.getBufferedTimes = function getBufferedTimes(startPTS, endPTS, timeRange) { + var fragmentTimes = []; + var startTime = void 0, + endTime = void 0; + var fragmentPartial = false; + for (var i = 0; i < timeRange.length; i++) { + startTime = timeRange.start(i) - this.bufferPadding; + endTime = timeRange.end(i) + this.bufferPadding; + if (startPTS >= startTime && endPTS <= endTime) { + // Fragment is entirely contained in buffer + // No need to check the other timeRange times since it's completely playable + fragmentTimes.push({ + startPTS: Math.max(startPTS, timeRange.start(i)), + endPTS: Math.min(endPTS, timeRange.end(i)) + }); + break; + } else if (startPTS < endTime && endPTS > startTime) { + // Check for intersection with buffer + // Get playable sections of the fragment + fragmentTimes.push({ + startPTS: Math.max(startPTS, timeRange.start(i)), + endPTS: Math.min(endPTS, timeRange.end(i)) + }); + fragmentPartial = true; + } else if (endPTS <= startTime) { + // No need to check the rest of the timeRange as it is in order + break; + } + } + + return { + time: fragmentTimes, + partial: fragmentPartial + }; + }; + + FragmentTracker.prototype.getFragmentKey = function getFragmentKey(fragment) { + return fragment.type + '_' + fragment.level + '_' + fragment.urlId + '_' + fragment.sn; + }; + + /** + * Gets the partial fragment for a certain time + * @param {Number} time + * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment + */ + + + FragmentTracker.prototype.getPartialFragment = function getPartialFragment(time) { + var _this4 = this; + + var timePadding = void 0, + startTime = void 0, + endTime = void 0; + var bestFragment = null; + var bestOverlap = 0; + Object.keys(this.fragments).forEach(function (key) { + var fragmentEntity = _this4.fragments[key]; + if (_this4.isPartial(fragmentEntity)) { + startTime = fragmentEntity.body.startPTS - _this4.bufferPadding; + endTime = fragmentEntity.body.endPTS + _this4.bufferPadding; + if (time >= startTime && time <= endTime) { + // Use the fragment that has the most padding from start and end time + timePadding = Math.min(time - startTime, endTime - time); + if (bestOverlap <= timePadding) { + bestFragment = fragmentEntity.body; + bestOverlap = timePadding; + } + } + } + }); + return bestFragment; + }; + + /** + * @param {Object} fragment The fragment to check + * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded + */ + + + FragmentTracker.prototype.getState = function getState(fragment) { + var fragKey = this.getFragmentKey(fragment); + var fragmentEntity = this.fragments[fragKey]; + var state = FragmentState.NOT_LOADED; + + if (fragmentEntity !== undefined) { + if (!fragmentEntity.buffered) { + state = FragmentState.APPENDING; + } else if (this.isPartial(fragmentEntity) === true) { + state = FragmentState.PARTIAL; + } else { + state = FragmentState.OK; + } + } + + return state; + }; + + FragmentTracker.prototype.isPartial = function isPartial(fragmentEntity) { + return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true); + }; + + FragmentTracker.prototype.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) { + var startTime = void 0, + endTime = void 0; + for (var i = 0; i < timeRange.length; i++) { + startTime = timeRange.start(i) - this.bufferPadding; + endTime = timeRange.end(i) + this.bufferPadding; + if (startPTS >= startTime && endPTS <= endTime) { + return true; + } + + if (endPTS <= startTime) { + // No need to check the rest of the timeRange as it is in order + return false; + } + } + + return false; + }; + + /** + * Fires when a fragment loading is completed + */ + + + FragmentTracker.prototype.onFragLoaded = function onFragLoaded(e) { + var fragment = e.frag; + // don't track initsegment (for which sn is not a number) + // don't track frags used for bitrateTest, they're irrelevant. + if (!isNaN(fragment.sn) && !fragment.bitrateTest) { + var fragKey = this.getFragmentKey(fragment); + var fragmentEntity = { + body: fragment, + range: Object.create(null), + buffered: false + }; + this.fragments[fragKey] = fragmentEntity; + } + }; + + /** + * Fires when the buffer is updated + */ + + + FragmentTracker.prototype.onBufferAppended = function onBufferAppended(e) { + var _this5 = this; + + // Store the latest timeRanges loaded in the buffer + this.timeRanges = e.timeRanges; + Object.keys(this.timeRanges).forEach(function (elementaryStream) { + var timeRange = _this5.timeRanges[elementaryStream]; + _this5.detectEvictedFragments(elementaryStream, timeRange); + }); + }; + + /** + * Fires after a fragment has been loaded into the source buffer + */ + + + FragmentTracker.prototype.onFragBuffered = function onFragBuffered(e) { + this.detectPartialFragments(e.frag); + }; + + /** + * Return true if fragment tracker has the fragment. + * @param {Object} fragment + * @returns {boolean} + */ + + + FragmentTracker.prototype.hasFragment = function hasFragment(fragment) { + var fragKey = this.getFragmentKey(fragment); + return this.fragments[fragKey] !== undefined; + }; + + /** + * Remove a fragment from fragment tracker until it is loaded again + * @param {Object} fragment The fragment to remove + */ + + + FragmentTracker.prototype.removeFragment = function removeFragment(fragment) { + var fragKey = this.getFragmentKey(fragment); + delete this.fragments[fragKey]; + }; + + /** + * Remove all fragments from fragment tracker. + */ + + + FragmentTracker.prototype.removeAllFragments = function removeAllFragments() { + this.fragments = Object.create(null); + }; + + return FragmentTracker; +}(event_handler); +// 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/utils/buffer-helper.js +function buffer_helper__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @module BufferHelper + * + * Providing methods dealing with buffer length retrieval for example. + * + * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property. + * + * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered +*/ + +var BufferHelper = function () { + function BufferHelper() { + buffer_helper__classCallCheck(this, BufferHelper); + } + + /** + * Return true if `media`'s buffered include `position` + * @param {HTMLMediaElement|SourceBuffer} media + * @param {number} position + * @returns {boolean} + */ + BufferHelper.isBuffered = function isBuffered(media, position) { + try { + 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; + } + } + } + } catch (error) { + // this is to catch + // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': + // This SourceBuffer has been removed from the parent media source + } + return false; + }; + + BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) { + try { + if (media) { + var vbuffered = media.buffered, + buffered = [], + i = void 0; + for (i = 0; i < vbuffered.length; i++) { + buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) }); + } + + return this.bufferedInfo(buffered, pos, maxHoleDuration); + } + } catch (error) { + // this is to catch + // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': + // This SourceBuffer has been removed from the parent media source + } + return { len: 0, start: pos, end: pos, nextStart: undefined }; + }; + + BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) { + var buffered2 = [], + + // bufferStart and bufferEnd are buffer boundaries around current video position + bufferLen = void 0, + bufferStart = void 0, + bufferEnd = void 0, + bufferStartNext = void 0, + i = void 0; + // 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 }; + }; + + return BufferHelper; +}(); +// EXTERNAL MODULE: ./node_modules/events/events.js +var events_events = __webpack_require__(6); +var events_default = /*#__PURE__*/__webpack_require__.n(events_events); + +// EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js +var webworkify_webpack = __webpack_require__(11); +var webworkify_webpack_default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack); + +// EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 11 modules +var demuxer_inline = __webpack_require__(9); + +// CONCATENATED MODULE: ./src/utils/mediasource-helper.js +/** + * MediaSource helper + */ + +function getMediaSource() { + if (typeof window !== 'undefined') { + return window.MediaSource || window.WebKitMediaSource; + } +} +// EXTERNAL MODULE: ./src/utils/get-self-scope.js +var get_self_scope = __webpack_require__(3); + +// 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"); } } + + + + + + + + + + + +// see https://stackoverflow.com/a/11237259/589493 +var global = Object(get_self_scope["a" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread +var 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: MediaSource.isTypeSupported('video/mp4'), + mpeg: MediaSource.isTypeSupported('audio/mpeg'), + mp3: 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*/(12)); + 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 + global.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; + switch (data.event) { + case 'init': + // revoke the Object URL that was used to create demuxer worker, so as not to leak it + global.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/controller/level-helper.js +/** + * @module LevelHelper + * + * Providing methods dealing with playlist sliding and drift + * + * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner. + * + * */ + + + +function addGroupId(level, type, id) { + switch (type) { + case 'audio': + if (!level.audioGroupIds) { + level.audioGroupIds = []; + } + level.audioGroupIds.push(id); + break; + case 'text': + if (!level.textGroupIds) { + level.textGroupIds = []; + } + level.textGroupIds.push(id); + break; + } +} + +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 = void 0, + fragments = void 0, + i = void 0; + 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 = void 0; + + // potentially retrieve cached initsegment + if (newDetails.initSegment && oldDetails.initSegment) { + newDetails.initSegment = oldDetails.initSegment; + } + + // 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/time-ranges.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 time_ranges = (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 && lastLevel.details.fragments && lastLevel.details.fragments.length) { + // 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/task-loop.js +function task_loop__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function task_loop__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 task_loop__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; } + + + +/** + * Sub-class specialization of EventHandler base class. + * + * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop, + * scheduled asynchroneously, avoiding recursive calls in the same tick. + * + * The task itself is implemented in `doTick`. It can be requested and called for single execution + * using the `tick` method. + * + * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick", + * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly. + * + * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`, + * and cancelled with `clearNextTick`. + * + * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`). + * + * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine. + * + * Further explanations: + * + * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously + * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks. + * + * When the task execution (`tick` method) is called in re-entrant way this is detected and + * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further + * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo). + */ + +var TaskLoop = function (_EventHandler) { + task_loop__inherits(TaskLoop, _EventHandler); + + function TaskLoop(hls) { + task_loop__classCallCheck(this, TaskLoop); + + for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + events[_key - 1] = arguments[_key]; + } + + var _this = task_loop__possibleConstructorReturn(this, _EventHandler.call.apply(_EventHandler, [this, hls].concat(events))); + + _this._tickInterval = null; + _this._tickTimer = null; + _this._tickCallCount = 0; + _this._boundTick = _this.tick.bind(_this); + return _this; + } + + /** + * @override + */ + + + TaskLoop.prototype.onHandlerDestroying = function onHandlerDestroying() { + // clear all timers before unregistering from event bus + this.clearNextTick(); + this.clearInterval(); + }; + + /** + * @returns {boolean} + */ + + + TaskLoop.prototype.hasInterval = function hasInterval() { + return !!this._tickInterval; + }; + + /** + * @returns {boolean} + */ + + + TaskLoop.prototype.hasNextTick = function hasNextTick() { + return !!this._tickTimer; + }; + + /** + * @param {number} millis Interval time (ms) + * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect) + */ + + + TaskLoop.prototype.setInterval = function (_setInterval) { + function setInterval(_x) { + return _setInterval.apply(this, arguments); + } + + setInterval.toString = function () { + return _setInterval.toString(); + }; + + return setInterval; + }(function (millis) { + if (!this._tickInterval) { + this._tickInterval = setInterval(this._boundTick, millis); + return true; + } + return false; + }); + + /** + * @returns {boolean} True when interval was cleared, false when none was set (no effect) + */ + + + TaskLoop.prototype.clearInterval = function (_clearInterval) { + function clearInterval() { + return _clearInterval.apply(this, arguments); + } + + clearInterval.toString = function () { + return _clearInterval.toString(); + }; + + return clearInterval; + }(function () { + if (this._tickInterval) { + clearInterval(this._tickInterval); + this._tickInterval = null; + return true; + } + return false; + }); + + /** + * @returns {boolean} True when timeout was cleared, false when none was set (no effect) + */ + + + TaskLoop.prototype.clearNextTick = function clearNextTick() { + if (this._tickTimer) { + clearTimeout(this._tickTimer); + this._tickTimer = null; + return true; + } + return false; + }; + + /** + * Will call the subclass doTick implementation in this main loop tick + * or in the next one (via setTimeout(,0)) in case it has already been called + * in this tick (in case this is a re-entrant call). + */ + + + TaskLoop.prototype.tick = function tick() { + this._tickCallCount++; + if (this._tickCallCount === 1) { + this.doTick(); + // re-entrant call to tick from previous doTick call stack + // -> schedule a call on the next main loop iteration to process this task processing request + if (this._tickCallCount > 1) { + // make sure only one timer exists at any time at max + this.clearNextTick(); + this._tickTimer = setTimeout(this._boundTick, 0); + } + this._tickCallCount = 0; + } + }; + + /** + * For subclass to implement task logic + * @abstract + */ + + + TaskLoop.prototype.doTick = function doTick() {}; + + return TaskLoop; +}(event_handler); + +/* harmony default export */ var task_loop = (TaskLoop); +// CONCATENATED MODULE: ./src/controller/fragment-finders.js + + +/** + * Calculates the PDT of the next load position. + * bufferEnd in this function is usually the position of the playhead. + * @param {number} [start = 0] - The PTS of the first fragment within the level + * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within + * @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level + * @returns {number} nextPdt - The computed PDT + */ +function calculateNextPDT() { + var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var bufferEnd = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var levelDetails = arguments[2]; + + var pdt = 0; + if (levelDetails.programDateTime) { + var parsedDateInt = Date.parse(levelDetails.programDateTime); + if (!isNaN(parsedDateInt)) { + pdt = bufferEnd * 1000 + parsedDateInt - 1000 * start; + } + } + return pdt; +} + +/** + * Finds the first fragment whose endPDT value exceeds the given PDT. + * @param {Array<Fragment>} fragments - The array of candidate fragments + * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded + * @returns {*|null} fragment - The best matching fragment + */ +function findFragmentByPDT(fragments) { + var PDTValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + + if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) { + return null; + } + + // if less than start + var firstSegment = fragments[0]; + + if (PDTValue < firstSegment.pdt) { + return null; + } + + var lastSegment = fragments[fragments.length - 1]; + + if (PDTValue >= lastSegment.endPdt) { + return null; + } + + for (var seg = 0; seg < fragments.length; ++seg) { + var frag = fragments[seg]; + if (PDTValue < frag.endPdt) { + return frag; + } + } + return null; +} + +/** + * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer. + * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus + * breaking any traps which would cause the same fragment to be continuously selected within a small range. + * @param {*} fragPrevious - The last frag successfully appended + * @param {Array<Fragment>} fragments - The array of candidate fragments + * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within + * @param {number} [end = 0] - The computed end time of the stream + * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous + * @returns {*} foundFrag - The best matching fragment + */ +function findFragmentBySN(fragPrevious, fragments) { + var bufferEnd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var maxFragLookUpTolerance = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + + var foundFrag = void 0; + var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null; + if (bufferEnd < end) { + if (bufferEnd > end - maxFragLookUpTolerance) { + maxFragLookUpTolerance = 0; + } + + // Prefer the next fragment if it's within tolerance + if (fragNext && !fragment_finders_fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) { + foundFrag = fragNext; + } else { + foundFrag = binary_search.search(fragments, fragment_finders_fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance)); + } + } + return foundFrag; +} + +/** + * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions. + * @param {*} candidate - The fragment to test + * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within + * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous + * @returns {number} - 0 if it matches, 1 if too low, -1 if too high + */ +function fragment_finders_fragmentWithinToleranceTest() { + var bufferEnd = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var maxFragLookUpTolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var candidate = arguments[2]; + + // 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; + } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { + // if maxFragLookUpTolerance will have negative value then don't return -1 for first element + return -1; + } + + return 0; +} +// 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 (_TaskLoop) { + stream_controller__inherits(StreamController, _TaskLoop); + + function StreamController(hls, fragmentTracker) { + stream_controller__classCallCheck(this, StreamController); + + var _this = stream_controller__possibleConstructorReturn(this, _TaskLoop.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.fragmentTracker = fragmentTracker; + _this.config = hls.config; + _this.audioCodecSwap = false; + _this._state = State.STOPPED; + _this.stallReported = false; + return _this; + } + + StreamController.prototype.onHandlerDestroying = function onHandlerDestroying() { + this.stopLoad(); + _TaskLoop.prototype.onHandlerDestroying.call(this); + }; + + StreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() { + this.state = State.STOPPED; + this.fragmentTracker = null; + _TaskLoop.prototype.onHandlerDestroyed.call(this); + }; + + StreamController.prototype.startLoad = function startLoad(startPosition) { + if (this.levels) { + var lastCurrentTime = this.lastCurrentTime, + hls = this.hls; + this.stopLoad(); + this.setInterval(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.fragmentTracker.removeFragment(frag); + this.fragCurrent = null; + } + this.fragPrevious = null; + if (this.demuxer) { + this.demuxer.destroy(); + this.demuxer = null; + } + this.clearInterval(); + this.state = State.STOPPED; + this.forceStartLoad = false; + }; + + StreamController.prototype.doTick = function doTick() { + switch (this.state) { + 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 = window.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 = BufferHelper.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 (!levelDetails || 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) { + if (frag.encrypted) { + logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level); + this._loadKey(frag); + } else { + logger["b" /* logger */].log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3)); + this._loadFragment(frag); + } + } + }; + + 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) { + if (!levelDetails.programDateTime) { + // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE) + 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); + } + } + } else { + // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE) + frag = findFragmentByPDT(fragments, fragPrevious.endPdt + 1); + } + } + 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 fragBySN = function fragBySN() { + return findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance); + }; + var frag = void 0; + var foundFrag = void 0; + + if (bufferEnd < end) { + if (!levelDetails.programDateTime) { + // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE) + foundFrag = findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance); + } else { + // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE) + foundFrag = findFragmentByPDT(fragments, calculateNextPDT(start, bufferEnd, levelDetails)); + if (!foundFrag || fragment_finders_fragmentWithinToleranceTest(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) { + // Fall back to SN order if finding by PDT returns a frag which won't fit within the stream + // fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise + logger["b" /* logger */].warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN'); + foundFrag = fragBySN(); + } + } + } 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'); + } 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) { + frag = prevFrag; + frag.backtracked = true; + } else if (curSNIdx) { + // can't backtrack on very first fragment + frag = null; + } + } + } + } + } + return frag; + }; + + StreamController.prototype._loadKey = function _loadKey(frag) { + this.state = State.KEY_LOADING; + this.hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag }); + }; + + StreamController.prototype._loadFragment = function _loadFragment(frag) { + // Check if fragment is not loaded + var fragState = this.fragmentTracker.getState(frag); + + 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; + } + + // Allow backtracked fragments to load + if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) { + frag.autoLevel = this.hls.autoLevelEnabled; + frag.bitrateTest = this.bitrateTest; + + this.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(this.hls, 'main'); + } + + this.state = State.FRAG_LOADING; + } else if (fragState === FragmentState.APPENDING) { + // Lower the buffer size and try again + if (this._reduceMaxBufferLength(frag.duration)) { + this.fragmentTracker.removeFragment(frag); + } + } + }; + + StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) { + return this.fragmentTracker.getBufferedFrag(position, playlist_loader.LevelType.MAIN); + }; + + 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 = void 0, + currentTime = void 0, + 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 > this.lastCurrentTime) { + this.lastCurrentTime = currentTime; + } + + if (BufferHelper.isBuffered(video, currentTime)) { + fragPlayingCurrent = this.getBufferedFrag(currentTime); + } else if (BufferHelper.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; + // 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 (BufferHelper.isBuffered(media, media.currentTime)) { + // only nudge if currentTime is buffered + media.currentTime -= 0.0001; + } + if (!this.previouslyPaused) { + media.play(); + } + } + }; + + /** + * 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 + */ + + + StreamController.prototype.nextLevelSwitch = function nextLevelSwitch() { + 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; + 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 backtracked flag + var levels = this.levels; + if (levels) { + levels.forEach(function (level) { + if (level.details) { + level.details.fragments.forEach(function (fragment) { + 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 = BufferHelper.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; + } + + // 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.fragmentTracker.removeAllFragments(); + this.stalled = false; + this.startPosition = this.lastCurrentTime = 0; + }; + + StreamController.prototype.onManifestParsed = function onManifestParsed(data) { + var aac = false, + heaac = false, + codec = void 0; + 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; + var currentLevel = this.levels[fragCurrent.level]; + var 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 = window.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 = window.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 = void 0, + track = void 0; + + // 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; + } + + if (data.hasAudio === true) { + frag.addElementaryStream(loader_fragment.ElementaryStreamTypes.AUDIO); + } + + if (data.hasVideo === true) { + frag.addElementaryStream(loader_fragment.ElementaryStreamTypes.VIDEO); + } + + 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', frag.sn); + } else { + logger["b" /* logger */].warn('missing video frame(s), backtracking fragment', frag.sn); + // 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 + this.fragmentTracker.removeFragment(frag); + 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', frag.sn); + } + } 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 = window.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 : ' + time_ranges.toString(media.buffered)); + this.fragPrevious = frag; + var stats = this.stats; + stats.tbuffered = window.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 && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.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); + logger["b" /* logger */].warn('mediaController: frag loading failed, retry in ' + delay + ' ms'); + this.retryDate = window.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 */].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'); + return true; + } + return false; + }; + + /** + * Checks the health of the buffer and attempts to resolve playback stalls. + * @private + */ + + + StreamController.prototype._checkBuffer = function _checkBuffer() { + var config = this.config, + media = this.media; + + var stallDebounceInterval = 1000; + if (!media || media.readyState === 0) { + // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0) + return; + } + + var currentTime = media.currentTime; + var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media; + var buffered = mediaBuffer.buffered; + + if (!this.loadedmetadata && buffered.length) { + this.loadedmetadata = true; + this._seekToStartPos(); + } else if (this.immediateSwitch) { + this.immediateLevelSwitchEnd(); + } else { + var expectedPlaying = !(media.paused && media.readyState > 1 || // not playing when media is paused and sufficiently buffered + media.ended || // not playing when media is ended + media.buffered.length === 0); // not playing if nothing buffered + var tnow = window.performance.now(); + + if (currentTime !== this.lastCurrentTime) { + // The playhead is now moving, but was previously stalled + if (this.stallReported) { + logger["b" /* logger */].warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(tnow - this.stalled) + 'ms'); + this.stallReported = false; + } + this.stalled = null; + this.nudgeRetry = 0; + } else if (expectedPlaying) { + // The playhead isn't moving but it should be + // Allow some slack time to for small stalls to resolve themselves + var stalledDuration = tnow - this.stalled; + var bufferInfo = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole); + if (!this.stalled) { + this.stalled = tnow; + return; + } else if (stalledDuration >= stallDebounceInterval) { + // Report stalling after trying to fix + this._reportStall(bufferInfo.len); + } + + this._tryFixBufferStall(bufferInfo, stalledDuration); + } + } + }; + + 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; + if (media) { + // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams + this.fragmentTracker.detectEvictedFragments(loader_fragment.ElementaryStreamTypes.VIDEO, media.buffered); + } + // 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); + }; + + /** + * Detects and attempts to fix known buffer stalling issues. + * @param bufferInfo - The properties of the current buffer. + * @param stalledDuration - The amount of time Hls.js has been stalling for. + * @private + */ + + + StreamController.prototype._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDuration) { + var config = this.config, + media = this.media; + + var currentTime = media.currentTime; + var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end + + var partial = this.fragmentTracker.getPartialFragment(currentTime); + if (partial) { + // Try to skip over the buffer hole caused by a partial fragment + // This method isn't limited by the size of the gap between buffered ranges + this._trySkipBufferHole(partial); + } + + if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) { + // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds + // We only try to jump the hole if it's under the configured size + // Reset stalled so to rearm watchdog timer + this.stalled = null; + this._tryNudgeBuffer(); + } + }; + + /** + * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period. + * @param bufferLen - The playhead distance from the end of the current buffer segment. + * @private + */ + + + StreamController.prototype._reportStall = function _reportStall(bufferLen) { + var hls = this.hls, + media = this.media, + stallReported = this.stallReported; + + if (!stallReported) { + // Report stalled error once + this.stallReported = true; + logger["b" /* logger */].warn('Playback stalling at @' + media.currentTime + ' due to low buffer'); + hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].MEDIA_ERROR, + details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, + fatal: false, + buffer: bufferLen + }); + } + }; + + /** + * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments + * @param partial - The partial fragment found at the current time (where playback is stalling). + * @private + */ + + + StreamController.prototype._trySkipBufferHole = function _trySkipBufferHole(partial) { + var hls = this.hls, + media = this.media; + + var currentTime = media.currentTime; + var lastEndTime = 0; + // Check if currentTime is between unbuffered regions of partial fragments + for (var i = 0; i < media.buffered.length; i++) { + var startTime = media.buffered.start(i); + if (currentTime >= lastEndTime && currentTime < startTime) { + media.currentTime = Math.max(startTime, media.currentTime + 0.1); + logger["b" /* logger */].warn('skipping hole, adjusting currentTime from ' + currentTime + ' to ' + media.currentTime); + this.stalled = null; + hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].MEDIA_ERROR, + details: errors["a" /* ErrorDetails */].BUFFER_SEEK_OVER_HOLE, + fatal: false, + reason: 'fragment loaded with buffer holes, seeking from ' + currentTime + ' to ' + media.currentTime, + frag: partial + }); + return; + } + lastEndTime = media.buffered.end(i); + } + }; + + /** + * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount. + * @private + */ + + + StreamController.prototype._tryNudgeBuffer = function _tryNudgeBuffer() { + var config = this.config, + hls = this.hls, + media = this.media; + + var currentTime = media.currentTime; + var nudgeRetry = (this.nudgeRetry || 0) + 1; + this.nudgeRetry = nudgeRetry; + + if (nudgeRetry < config.nudgeMaxRetry) { + 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 + }); + } + }; + + /** + * Seeks to the set startPosition if not equal to the mediaElement's current time. + * @private + */ + + + StreamController.prototype._seekToStartPos = function _seekToStartPos() { + var media = this.media; + + var currentTime = media.currentTime; + // 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; + // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered + if (currentTime !== startPosition) { + // if startPosition not buffered, let's seek to buffered.start(0) + logger["b" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition + ' from current time ' + currentTime + ' '); + media.currentTime = startPosition; + } + }; + + 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; +}(task_loop); + +/* harmony default export */ var stream_controller = (stream_controller_StreamController); +// CONCATENATED MODULE: ./src/controller/level-controller.js +var level_controller__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; }; + +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__window = window, + level_controller_performance = level_controller__window.performance; + +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 */].AUDIO_TRACK_SWITCHED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].ERROR)); + + _this.canload = false; + _this.currentLevelIndex = null; + _this.manualLevelIndex = -1; + _this.timer = null; + return _this; + } + + LevelController.prototype.onHandlerDestroying = function onHandlerDestroying() { + this.clearTimer(); + this.manualLevelIndex = -1; + }; + + LevelController.prototype.clearTimer = function clearTimer() { + 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 !== null) { + this.loadLevel(); + } + }; + + 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 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) { + level.audioCodec = undefined; + } + + levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here + + if (!levelFromSet) { + level.url = [level.url]; + level.urlId = 0; + levelSet[level.bitrate] = level; + levels.push(level); + } else { + levelFromSet.url.push(level.url); + } + + if (level.attrs && level.attrs.AUDIO) { + addGroupId(levelFromSet || level, 'audio', level.attrs.AUDIO); + } + + if (level.attrs && level.attrs.SUBTITLES) { + addGroupId(levelFromSet || level, 'text', level.attrs.SUBTITLES); + } + }); + + // remove audio-only level if we also have levels with audio+video codecs signalled + if (videoCodecFound && audioCodecFound) { + 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 > 0) { + // 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 && videoCodecFound + }); + } 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.clearTimer(); + if (this.currentLevelIndex !== newLevel) { + logger["b" /* logger */].log('switching to level ' + newLevel); + this.currentLevelIndex = newLevel; + var levelProperties = levels[newLevel]; + levelProperties.level = newLevel; + hls.trigger(events["a" /* default */].LEVEL_SWITCHING, levelProperties); + } + var level = levels[newLevel]; + var levelDetails = level.details; + + // check if we need to load playlist for this level + if (!levelDetails || levelDetails.live) { + // 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) { + if (data.fatal) { + if (data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) { + this.clearTimer(); + } + + return; + } + + var levelError = false, + fragmentError = false; + var levelIndex = void 0; + + // try to recover not fatal errors + 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: + 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; + levelError = true; + break; + } + + if (levelIndex !== undefined) { + this.recoverLevel(data, levelIndex, levelError, fragmentError); + } + }; + + /** + * Switch to a redundant stream if any available. + * If redundant stream is not available, emergency switch down if ABR mode is enabled. + * + * @param {Object} errorEvent + * @param {Number} levelIndex current level index + * @param {Boolean} levelError + * @param {Boolean} fragmentError + */ + // FIXME Find a better abstraction where fragment/level retry management is well decoupled + + + LevelController.prototype.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) { + var _this2 = this; + + var config = this.hls.config; + var errorDetails = errorEvent.details; + + var level = this._levels[levelIndex]; + var redundantLevels = void 0, + delay = void 0, + nextLevel = void 0; + + level.loadError++; + level.fragmentError = fragmentError; + + if (levelError) { + if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) { + // exponential backoff capped to max retry timeout + delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); + // Schedule level reload + this.timer = setTimeout(function () { + return _this2.loadLevel(); + }, delay); + // boolean used to inform stream controller not to switch back to IDLE on non fatal error + errorEvent.levelRetry = true; + this.levelRetryCount++; + logger["b" /* logger */].warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount); + } else { + logger["b" /* logger */].error('level controller, cannot recover from ' + errorDetails + ' error'); + this.currentLevelIndex = null; + // stopping live reloading timer if any + this.clearTimer(); + // switch error to fatal + errorEvent.fatal = true; + return; + } + } + + // Try any redundant streams if available for both errors: level and fragment + // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down + if (levelError || fragmentError) { + 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, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant URL-id ' + level.urlId); + + // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId); + // console.log('New video quality level audio group id:', level.attrs.AUDIO); + } else { + // Search for available level + if (this.manualLevelIndex === -1) { + // When lowest level has been reached, let's start hunt from the top + nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1; + logger["b" /* logger */].warn('level controller, ' + errorDetails + ': switch to ' + nextLevel); + this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel; + } else if (fragmentError) { + // Allow fragment retry as long as configuration allows. + // reset this._level so that another call to set level() will trigger again a frag load + logger["b" /* logger */].warn('level controller, ' + errorDetails + ': reload a fragment'); + this.currentLevelIndex = null; + } + } + } + }; + + // 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.currentLevelIndex) { + return; + } + + 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) { + 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 targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration); + var reloadInterval = targetdurationMs, + 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 -= level_controller_performance.now() - data.stats.trequest; + // in any case, don't reload more than half of target duration + reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval)); + logger["b" /* logger */].log('live playlist, reload in ' + Math.round(reloadInterval) + ' ms'); + this.timer = setTimeout(function () { + return _this3.loadLevel(); + }, reloadInterval); + } else { + this.clearTimer(); + } + }; + + LevelController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) { + var audioGroupId = this.hls.audioTracks[data.id].groupId; + + var currentLevel = this.hls.levels[this.currentLevelIndex]; + if (!currentLevel) { + return; + } + + if (currentLevel.audioGroupIds) { + var urlId = currentLevel.audioGroupIds.findIndex(function (groupId) { + return groupId === audioGroupId; + }); + if (urlId !== currentLevel.urlId) { + currentLevel.urlId = urlId; + this.startLoad(); + } + } + }; + + LevelController.prototype.loadLevel = function loadLevel() { + logger["b" /* logger */].debug('call to loadLevel'); + + if (this.currentLevelIndex !== null && this.canload) { + var levelObject = this._levels[this.currentLevelIndex]; + + if ((typeof levelObject === 'undefined' ? 'undefined' : level_controller__typeof(levelObject)) === 'object' && levelObject.url.length > 0) { + var level = this.currentLevelIndex; + var id = levelObject.urlId; + var url = levelObject.url[id]; + + logger["b" /* logger */].log('Attempt loading level index ' + level + ' with URL-id ' + id); + + // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId); + // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level); + + this.hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: url, level: level, id: id }); + } + } + }; + + level_controller__createClass(LevelController, [{ + key: 'levels', + get: function get() { + return this._levels; + } + }, { + key: 'level', + get: function get() { + return this.currentLevelIndex; + }, + set: function set(newLevel) { + var levels = this._levels; + if (levels) { + newLevel = Math.min(newLevel, levels.length - 1); + if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) { + this.setLevelInternal(newLevel); + } + } + } + }, { + key: 'manualLevel', + get: function get() { + return this.manualLevelIndex; + }, + set: function set(newLevel) { + this.manualLevelIndex = 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.manualLevelIndex !== -1) { + return this.manualLevelIndex; + } else { + return this.hls.nextAutoLevel; + } + }, + set: function set(nextLevel) { + this.level = nextLevel; + if (this.manualLevelIndex === -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__(5); + +// CONCATENATED MODULE: ./src/utils/texttrack-utils.js + +function sendAddTrackEvent(track, videoEl) { + var event = null; + try { + event = new window.Event('addtrack'); + } catch (err) { + // for IE11 + event = document.createEvent('Event'); + event.initEvent('addtrack', false, false); + } + event.track = track; + videoEl.dispatchEvent(event); +} + +function clearCurrentCues(track) { + if (track && track.cues) { + while (track.cues.length > 0) { + track.removeCue(track.cues[0]); + } + } +} +// 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) {} + }; + + ID3TrackController.prototype.onMediaDetaching = function onMediaDetaching() { + clearCurrentCues(this.id3Track); + this.id3Track = undefined; + this.media = undefined; + }; + + ID3TrackController.prototype.getID3Track = function getID3Track(textTracks) { + for (var i = 0; i < textTracks.length; i++) { + var textTrack = textTracks[i]; + if (textTrack.kind === 'metadata' && textTrack.label === 'id3') { + // send 'addtrack' when reusing the textTrack for metadata, + // same as what we do for captions + sendAddTrackEvent(textTrack, this.media); + + return textTrack; + } + } + return this.media.addTextTrack('metadata', 'id3'); + }; + + ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) { + var fragment = data.frag; + var samples = data.samples; + + // create track dynamically + if (!this.id3Track) { + this.id3Track = this.getID3Track(this.media.textTracks); + 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/is-supported.js + + +function is_supported_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; +} +// 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__window = window, + abr_controller_performance = abr_controller__window.performance; + +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.fragCurrent = frag; + this.timer = setInterval(this.onCheck, 100); + } + + // lazy init of BwEstimator, 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; + var config = hls.config; + var level = frag.level; + var isLive = hls.levels[level].details.live; + + var 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); + } + } + }; + + 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; + var video = hls.media; + var frag = this.fragCurrent; + + if (!frag) { + return; + } + + var loader = frag.loader; + var 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(); + // reset forced auto level value so that next level will be selected + this._nextAutoLevel = -1; + 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 (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) { + var requestDelay = abr_controller_performance.now() - stats.trequest, + playbackRate = Math.abs(video.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 = video.currentTime, + fragLoadedDelay = (expectedLen - stats.loaded) / loadRate, + bufferStarvationDelay = (BufferHelper.bufferInfo(video, 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; + var 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.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 video = hls.media, + currentLevel = this.lastLoadedFragLevel, + currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0, + pos = video ? video.currentTime : 0, + + // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as + // if we're playing back at the normal rate. + playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.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 = (BufferHelper.bufferInfo(video, 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; + // current stream state: true - for live broadcast, false - for VoD content + _this._live = null; + // cache the self generated object url to detect hijack of video tag + _this._objectUrl = 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.altAudio, + 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 = window.URL.createObjectURL(ms); + // cache the locally generated object url + this._objectUrl = media.src; + } + }; + + 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) { + window.URL.revokeObjectURL(this._objectUrl); + + // clean up video tag src only if it's our own url. some external libraries might + // hijack the video tag and change its 'src' without destroying the Hls instance first + if (this.media.src === this._objectUrl) { + this.media.removeAttribute('src'); + this.media.load(); + } else { + logger["b" /* logger */].warn('media.src was changed by a third party - skip cleanup'); + } + } + + this.mediaSource = null; + this.media = null; + this._objectUrl = 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.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments + var timeRanges = {}; + var sourceBuffer = this.sourceBuffer; + for (var streamType in sourceBuffer) { + timeRanges[streamType] = sourceBuffer[streamType].buffered; + } + + this.hls.trigger(events["a" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges }); + // 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 immediately + this.flushBufferCounter = 0; + this.doFlush(); + }; + + BufferController.prototype.onLevelUpdated = function onLevelUpdated(_ref) { + var details = _ref.details; + + if (details.fragments.length > 0) { + this._levelDuration = details.totalduration + details.fragments[0].start; + this._live = details.live; + this.updateMediaElementDuration(); + } + }; + + /** + * Update Media Source duration to current level duration or override to Infinity if configuration parameter + * 'liveDurationInfinity` is set to `true` + * More details: https://github.com/video-dev/hls.js/issues/355 + */ + + + BufferController.prototype.updateMediaElementDuration = function updateMediaElementDuration() { + var config = this.hls.config; + + var duration = void 0; + + if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') { + return; + } + + for (var type in this.sourceBuffer) { + if (this.sourceBuffer[type].updating === true) { + // can't set duration whilst a buffer is updating + return; + } + } + + duration = this.media.duration; + // initialise to the value that the media source is reporting + if (this._msDuration === null) { + this._msDuration = this.mediaSource.duration; + } + + if (this._live === true && config.liveDurationInfinity === true) { + // Override duration to Infinity + logger["b" /* logger */].log('Media Source duration is set to Infinity'); + this._msDuration = this.mediaSource.duration = Infinity; + } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || duration === Infinity || isNaN(duration)) { + // levelDuration was the last value we set. + // not using mediaSource.duration as the browser may tweak this value + // only update Media Source duration if its value increase, this is to avoid + // flushing already buffered portion when switching between quality level + logger["b" /* logger */].log('Updating Media Source duration to ' + this._levelDuration.toFixed(3)); + this._msDuration = this.mediaSource.duration = this._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); + } 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); + } + } + } + } + }; + + /* + 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 = void 0, + i = void 0, + bufStart = void 0, + bufEnd = void 0, + flushStart = void 0, + flushEnd = void 0, + 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); + + var _this = 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, events["a" /* default */].BUFFER_CODECS)); + + _this.autoLevelCapping = Number.POSITIVE_INFINITY; + _this.firstLevel = null; + _this.levels = []; + _this.media = null; + _this.restrictedLevels = []; + _this.timer = null; + return _this; + } + + CapLevelController.prototype.destroy = function destroy() { + if (this.hls.config.capLevelToPlayerSize) { + this.media = null; + this._stopCapping(); + } + }; + + 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 window.HTMLVideoElement ? data.media : null; + }; + + CapLevelController.prototype.onManifestParsed = function onManifestParsed(data) { + var hls = this.hls; + this.restrictedLevels = []; + this.levels = data.levels; + this.firstLevel = data.firstLevel; + if (hls.config.capLevelToPlayerSize && (data.video || data.levels.length && data.altAudio)) { + // Start capping immediately if the manifest has signaled video codecs + this._startCapping(); + } + }; + + // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted + // to the first level + + + CapLevelController.prototype.onBufferCodecs = function onBufferCodecs(data) { + var hls = this.hls; + if (hls.config.capLevelToPlayerSize && data.video) { + // If the manifest did not signal a video codec capping has been deferred until we're certain video is present + this._startCapping(); + } + }; + + CapLevelController.prototype.onLevelsUpdated = function onLevelsUpdated(data) { + this.levels = data.levels; + }; + + 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.prototype._startCapping = function _startCapping() { + if (this.timer) { + // Don't reset capping if started twice; this can happen if the manifest signals a video codec + return; + } + this.autoLevelCapping = Number.POSITIVE_INFINITY; + this.hls.firstLevel = this.getMaxLevel(this.firstLevel); + clearInterval(this.timer); + this.timer = setInterval(this.detectPlayerSize.bind(this), 1000); + this.detectPlayerSize(); + }; + + CapLevelController.prototype._stopCapping = function _stopCapping() { + this.restrictedLevels = []; + this.firstLevel = null; + this.autoLevelCapping = Number.POSITIVE_INFINITY; + if (this.timer) { + this.timer = clearInterval(this.timer); + this.timer = null; + } + }; + + 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__window = window, + fps_controller_performance = fps_controller__window.performance; + +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 window.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 = fps_controller_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__window = window, + xhr_loader_performance = xhr_loader__window.performance, + XMLHttpRequest = xhr_loader__window.XMLHttpRequest; + +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: xhr_loader_performance.now(), retry: 0 }; + this.retryDelay = config.retryDelay; + this.loadInternal(); + }; + + XhrLoader.prototype.loadInternal = function loadInternal() { + var xhr = void 0, + 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(xhr_loader_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, xhr_loader_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; } + + + + + + +/** + * @class AudioTrackController + * @implements {EventHandler} + * + * Handles main manifest and audio-track metadata loaded, + * owns and exposes the selectable audio-tracks data-models. + * + * Exposes internal interface to select available audio-tracks. + * + * Handles errors on loading audio-track playlists. Manages fallback mechanism + * with redundants tracks (group-IDs). + * + * Handles level-loading and group-ID switches for video (fallback on video levels), + * and eventually adapts the audio-track group-ID to match. + * + * @fires AUDIO_TRACK_LOADING + * @fires AUDIO_TRACK_SWITCHING + * @fires AUDIO_TRACKS_UPDATED + * @fires ERROR + * + */ + +var audio_track_controller_AudioTrackController = function (_TaskLoop) { + audio_track_controller__inherits(AudioTrackController, _TaskLoop); + + function AudioTrackController(hls) { + audio_track_controller__classCallCheck(this, AudioTrackController); + + /** + * @private + * Currently selected index in `tracks` + * @member {number} trackId + */ + var _this = audio_track_controller__possibleConstructorReturn(this, _TaskLoop.call(this, hls, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].AUDIO_TRACK_LOADED, events["a" /* default */].AUDIO_TRACK_SWITCHED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].ERROR)); + + _this.trackId = -1; + + /** + * @public + * All tracks available + * @member {AudioTrack[]} + */ + _this.tracks = []; + + /** + * @public + * List of blacklisted audio track IDs (that have caused failure) + * @member {number[]} + */ + _this.trackIdBlacklist = Object.create(null); + + /** + * @public + * The currently running group ID for audio + * (we grab this on manifest-parsed and new level-loaded) + * @member {string} + */ + _this.audioGroupId = null; + return _this; + } + + /** + * Reset audio tracks on new manifest loading. + */ + + + AudioTrackController.prototype.onManifestLoading = function onManifestLoading() { + this.tracks = []; + this.trackId = -1; + }; + + /** + * Store tracks data from manifest parsed data. + * + * Trigger AUDIO_TRACKS_UPDATED event. + * + * @param {*} data + */ + + + AudioTrackController.prototype.onManifestParsed = function onManifestParsed(data) { + var tracks = this.tracks = data.audioTracks || []; + this.hls.trigger(events["a" /* default */].AUDIO_TRACKS_UPDATED, { audioTracks: tracks }); + }; + + /** + * Store track details of loaded track in our data-model. + * + * Set-up metadata update interval task for live-mode streams. + * + * @param {} data + */ + + + AudioTrackController.prototype.onAudioTrackLoaded = function onAudioTrackLoaded(data) { + if (data.id >= this.tracks.length) { + logger["b" /* logger */].warn('Invalid audio track id:', data.id); + return; + } + + logger["b" /* logger */].log('audioTrack ' + data.id + ' loaded'); + + this.tracks[data.id].details = data.details; + + // check if current playlist is a live playlist + // and if we have already our reload interval setup + if (data.details.live && !this.hasInterval()) { + // if live playlist we will have to reload it periodically + // set reload period to playlist target duration + var updatePeriodMs = data.details.targetduration * 1000; + this.setInterval(updatePeriodMs); + } + + if (!data.details.live && this.hasInterval()) { + // playlist is not live and timer is scheduled: cancel it + this.clearInterval(); + } + }; + + /** + * Update the internal group ID to any audio-track we may have set manually + * or because of a failure-handling fallback. + * + * Quality-levels should update to that group ID in this case. + * + * @param {*} data + */ + + + AudioTrackController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) { + var audioGroupId = this.tracks[data.id].groupId; + if (audioGroupId && this.audioGroupId !== audioGroupId) { + this.audioGroupId = audioGroupId; + } + }; + + /** + * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs) + * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set. + * + * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently + * selected one (based on NAME property). + * + * @param {*} data + */ + + + AudioTrackController.prototype.onLevelLoaded = function onLevelLoaded(data) { + // FIXME: crashes because currentLevel is undefined + // const levelInfo = this.hls.levels[this.hls.currentLevel]; + + var levelInfo = this.hls.levels[data.level]; + + if (!levelInfo.audioGroupIds) { + return; + } + + var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId]; + if (this.audioGroupId !== audioGroupId) { + this.audioGroupId = audioGroupId; + this._selectInitialAudioTrack(); + } + }; + + /** + * Handle network errors loading audio track manifests + * and also pausing on any netwok errors. + * + * @param {ErrorEventData} data + */ + + + AudioTrackController.prototype.onError = function onError(data) { + // Only handle network errors + if (data.type !== errors["b" /* ErrorTypes */].NETWORK_ERROR) { + return; + } + + // If fatal network error, cancel update task + if (data.fatal) { + this.clearInterval(); + } + + // If not an audio-track loading error don't handle further + if (data.details !== errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR) { + return; + } + + logger["b" /* logger */].warn('Network failure on audio-track id:', data.context.id); + this._handleLoadError(); + }; + + /** + * @type {AudioTrack[]} Audio-track list we own + */ + + + /** + * @override + */ + AudioTrackController.prototype.doTick = function doTick() { + this._updateTrack(this.trackId); + }; + + /** + * Select initial track + * @private + */ + + + AudioTrackController.prototype._selectInitialAudioTrack = function _selectInitialAudioTrack() { + var _this2 = this; + + var tracks = this.tracks; + if (!tracks.length) { + return; + } + + var currentAudioTrack = this.tracks[this.trackId]; + + var name = null; + if (currentAudioTrack) { + name = currentAudioTrack.name; + } + + // Pre-select default tracks if there are any + var defaultTracks = tracks.filter(function (track) { + return track.default; + }); + if (defaultTracks.length) { + tracks = defaultTracks; + } else { + logger["b" /* logger */].warn('No default audio tracks defined'); + } + + var trackFound = false; + + var traverseTracks = function traverseTracks() { + // Select track with right group ID + tracks.forEach(function (track) { + if (trackFound) { + return; + } + // We need to match the (pre-)selected group ID + // and the NAME of the current track. + if ((!_this2.audioGroupId || track.groupId === _this2.audioGroupId) && (!name || name === track.name)) { + // If there was a previous track try to stay with the same `NAME`. + // It should be unique across tracks of same group, and consistent through redundant track groups. + _this2.audioTrack = track.id; + trackFound = true; + } + }); + }; + + traverseTracks(); + + if (!trackFound) { + name = null; + traverseTracks(); + } + + if (!trackFound) { + logger["b" /* logger */].error('No track found for running audio group-ID: ' + this.audioGroupId); + + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].MEDIA_ERROR, + details: errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR, + fatal: true + }); + } + }; + + /** + * @private + * @param {AudioTrack} audioTrack + * @returns {boolean} + */ + + + AudioTrackController.prototype._needsTrackLoading = function _needsTrackLoading(audioTrack) { + var details = audioTrack.details; + + + if (!details) { + return true; + } else if (details.live) { + return true; + } + }; + + /** + * @private + * @param {AudioTrack} audioTrack + */ + + + AudioTrackController.prototype._loadTrackDetailsIfNeeded = function _loadTrackDetailsIfNeeded(audioTrack) { + if (this._needsTrackLoading(audioTrack)) { + var url = audioTrack.url, + id = audioTrack.id; + // track not retrieved yet, or live playlist we need to (re)load it + + logger["b" /* logger */].log('loading audio-track playlist for id: ' + id); + this.hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADING, { url: url, id: id }); + } + }; + + /** + * @private + * @param {number} newId + */ + + + AudioTrackController.prototype._updateTrack = function _updateTrack(newId) { + // check if level idx is valid + if (newId < 0 || newId >= this.tracks.length) { + return; + } + + // stopping live reloading timer if any + this.clearInterval(); + this.trackId = newId; + logger["b" /* logger */].log('trying to update audio-track ' + newId); + var audioTrack = this.tracks[newId]; + this._loadTrackDetailsIfNeeded(audioTrack); + }; + + /** + * @private + */ + + + AudioTrackController.prototype._handleLoadError = function _handleLoadError() { + // First, let's black list current track id + this.trackIdBlacklist[this.trackId] = true; + + // Let's try to fall back on a functional audio-track with the same group ID + var previousId = this.trackId; + var _tracks$previousId = this.tracks[previousId], + name = _tracks$previousId.name, + language = _tracks$previousId.language, + groupId = _tracks$previousId.groupId; + + + logger["b" /* logger */].warn('Loading failed on audio track id: ' + previousId + ', group-id: ' + groupId + ', name/language: "' + name + '" / "' + language + '"'); + + // Find a non-blacklisted track ID with the same NAME + // At least a track that is not blacklisted, thus on another group-ID. + var newId = previousId; + for (var i = 0; i < this.tracks.length; i++) { + if (this.trackIdBlacklist[i]) { + continue; + } + var newTrack = this.tracks[i]; + if (newTrack.name === name) { + newId = i; + break; + } + } + + if (newId === previousId) { + logger["b" /* logger */].warn('No fallback audio-track found for name/language: "' + name + '" / "' + language + '"'); + return; + } + + logger["b" /* logger */].log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId); + + this.audioTrack = newId; + }; + + audio_track_controller__createClass(AudioTrackController, [{ + key: 'audioTracks', + get: function get() { + return this.tracks; + } + + /** + * @type {number} Index into audio-tracks list of currently selected track. + */ + + }, { + key: 'audioTrack', + get: function get() { + return this.trackId; + } + + /** + * Select current track by index + */ + , + set: function set(newId) { + // noop on same audio track id as already set + if (this.trackId === newId && this.tracks[this.trackId].details) { + logger["b" /* logger */].debug('Same id as current audio-track passed, and track details available -> no-op'); + return; + } + + // check if level idx is valid + if (newId < 0 || newId >= this.tracks.length) { + logger["b" /* logger */].warn('Invalid id passed to audio-track controller'); + return; + } + + var audioTrack = this.tracks[newId]; + + logger["b" /* logger */].log('Now switching to audio-track index ' + newId); + + // stopping live reloading timer if any + this.clearInterval(); + this.trackId = newId; + + var url = audioTrack.url, + type = audioTrack.type, + id = audioTrack.id; + + this.hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHING, { id: id, type: type, url: url }); + this._loadTrackDetailsIfNeeded(audioTrack); + } + }]); + + return AudioTrackController; +}(task_loop); + +/* 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__window = window, + audio_stream_controller_performance = audio_stream_controller__window.performance; + + +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 (_TaskLoop) { + audio_stream_controller__inherits(AudioStreamController, _TaskLoop); + + function AudioStreamController(hls, fragmentTracker) { + audio_stream_controller__classCallCheck(this, AudioStreamController); + + var _this = audio_stream_controller__possibleConstructorReturn(this, _TaskLoop.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_RESET, events["a" /* default */].BUFFER_CREATED, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].BUFFER_FLUSHED, events["a" /* default */].INIT_PTS_FOUND)); + + _this.fragmentTracker = fragmentTracker; + _this.config = hls.config; + _this.audioCodecSwap = false; + _this._state = audio_stream_controller_State.STOPPED; + _this.initPTS = []; + _this.waitingFragment = null; + _this.videoTrackCC = null; + return _this; + } + + AudioStreamController.prototype.onHandlerDestroying = function onHandlerDestroying() { + this.stopLoad(); + _TaskLoop.prototype.onHandlerDestroying.call(this); + }; + + AudioStreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() { + this.state = audio_stream_controller_State.STOPPED; + this.fragmentTracker = null; + _TaskLoop.prototype.onHandlerDestroyed.call(this); + }; + + // 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(); + this.setInterval(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.fragmentTracker.removeFragment(frag); + this.fragCurrent = null; + } + this.fragPrevious = null; + if (this.demuxer) { + this.demuxer.destroy(); + this.demuxer = null; + } + this.state = audio_stream_controller_State.STOPPED; + }; + + AudioStreamController.prototype.doTick = function doTick() { + var pos = void 0, + track = void 0, + trackDetails = void 0, + 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 = BufferHelper.bufferInfo(media, pos, config.maxBufferHole), + mainBufferInfo = BufferHelper.bufferInfo(videoBuffer, pos, config.maxBufferHole), + bufferLen = bufferInfo.len, + bufferEnd = bufferInfo.end, + fragPrevious = this.fragPrevious, + + // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s) + // whichever is smaller. + // once we reach that threshold, don't buffer more than video (mainBufferInfo.len) + maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength), + maxBufLen = Math.max(maxConfigBuffer, 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; + } + + // check if we need to finalize media stream + // 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 + if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN && !bufferInfo.nextStart) { + // 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; + } // eslint-disable-line brace-style + // 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; + } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { + // if maxFragLookUpTolerance will have negative value then don't return -1 for first element + 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.encrypted) { + 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)); + // only load if fragment is not loaded or if in audio switch + // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch + if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) { + 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 = audio_stream_controller_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; + } + + // 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; + } + + // 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 + this.setInterval(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; + } + 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 = audio_stream_controller_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; + } + + fragCurrent.addElementaryStream(loader_fragment.ElementaryStreamTypes.AUDIO); + + 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 (!pendingData) { + logger["b" /* logger */].warn('Apparently attempt to enqueue media payload without codec initialization data upfront'); + hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: null, fatal: true }); + return; + } + + 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 = audio_stream_controller_performance.now(); + this.state = audio_stream_controller_State.PARSED; + this._checkAppendedParsed(); + } + }; + + AudioStreamController.prototype.onBufferReset = function onBufferReset() { + // reset reference to sourcebuffers + this.mediaBuffer = this.videoBuffer = null; + this.loadedmetadata = false; + }; + + 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 = audio_stream_controller_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 : ' + time_ranges.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: + var _frag = data.frag; + // don't handle frag error not related to audio fragment + if (_frag && _frag.type !== 'audio') { + break; + } + + if (!data.fatal) { + var loadError = this.fragLoadError; + if (loadError) { + loadError++; + } else { + loadError = 1; + } + + var config = this.config; + if (loadError <= config.fragLoadingMaxRetry) { + this.fragLoadError = loadError; + // 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 = audio_stream_controller_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 */].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, now switching 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 && BufferHelper.isBuffered(media, currentTime) && BufferHelper.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('AudioStreamController: reduce max buffer length to ' + _config.maxMaxBufferLength + 's'); + } + 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('AudioStreamController: 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('AudioStreamController: appending pending audio data after 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; +}(task_loop); + +/* 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 = void 0; + 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 = void 0; + 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 = void 0; + var cue = void 0; + var indenting = void 0; + var indent = void 0; + var text = void 0; + 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 = void 0; + 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) + + }; + + Cea608Channel.prototype.ccAON = function ccAON() {// Reserved (formerly Alarm On) + + }; + + 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 = void 0, + a = void 0, + b = void 0, + 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) && b >= 0x20 && b <= 0x2F; + var cond2 = (a === 0x17 || a === 0x1F) && b >= 0x21 && 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) && b >= 0x20 && 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 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1F) && b >= 0x40 && b <= 0x7F; + var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && 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 (b >= 0x40 && 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 (charCode1 >= 0x11 && 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 (a >= 0x20 && 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 = void 0, + index = void 0, + chNr = void 0, + channel = void 0; + + var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f; + var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && 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, trackName) { + output_filter__classCallCheck(this, OutputFilter); + + this.timelineController = timelineController; + this.trackName = trackName; + this.startTime = null; + this.endTime = null; + this.screen = null; + } + + OutputFilter.prototype.dispatchCue = function dispatchCue() { + if (this.startTime === null) { + return; + } + + this.timelineController.addCues(this.trackName, 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.trackName); + }; + + 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 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 = []; + _this.captionsTracks = {}; + + _this.captionsProperties = { + textTrack1: { + label: _this.config.captionsTextTrack1Label, + languageCode: _this.config.captionsTextTrack1LanguageCode + }, + textTrack2: { + label: _this.config.captionsTextTrack2Label, + languageCode: _this.config.captionsTextTrack2LanguageCode + } + }; + + if (_this.config.enableCEA708Captions) { + var channel1 = new output_filter(_this, 'textTrack1'); + var channel2 = new output_filter(_this, 'textTrack2'); + + _this.cea608Parser = new cea_608_parser(0, channel1, channel2); + } + return _this; + } + + TimelineController.prototype.addCues = function addCues(trackName, 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.captionsTracks[trackName], 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(trackName) { + var media = this.media; + + if (media) { + for (var i = 0; i < media.textTracks.length; i++) { + var textTrack = media.textTracks[i]; + if (textTrack[trackName]) { + return textTrack; + } + } + } + return null; + }; + + TimelineController.prototype.createCaptionsTrack = function createCaptionsTrack(trackName) { + var _captionsProperties$t = this.captionsProperties[trackName], + label = _captionsProperties$t.label, + languageCode = _captionsProperties$t.languageCode; + + var captionsTracks = this.captionsTracks; + if (!captionsTracks[trackName]) { + // Enable reuse of existing text track. + var existingTrack = this.getExistingTrack(trackName); + if (!existingTrack) { + var textTrack = this.createTextTrack('captions', label, languageCode); + if (textTrack) { + // Set a special property on the track so we know it's managed by Hls.js + textTrack[trackName] = true; + captionsTracks[trackName] = textTrack; + } + } else { + captionsTracks[trackName] = existingTrack; + clearCurrentCues(captionsTracks[trackName]); + sendAddTrackEvent(captionsTracks[trackName], 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() { + var captionsTracks = this.captionsTracks; + + Object.keys(captionsTracks).forEach(function (trackName) { + clearCurrentCues(captionsTracks[trackName]); + delete captionsTracks[trackName]; + }); + }; + + 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); + } + + if (track.default) { + textTrack.mode = _this3.hls.subtitleDisplay ? 'showing' : 'hidden'; + } else { + textTrack.mode = 'disabled'; + } + + _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; + } // eslint-disable-line brace-style + // 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]; + // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled" + // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null + // and trying to access getCueById method of cues will throw an exception + if (currentTrack.mode === 'disabled') { + hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag }); + return; + } + // 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 = void 0, + ccbyte1 = void 0, + ccbyte2 = void 0, + ccValid = void 0, + ccType = void 0; + 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 = null; + + /** + * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering + */ + _this.subtitleDisplay = true; + 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 === 'hidden') { + // Do not break in case there is a following track with showing. + trackId = id; + } else if (tracks[id].mode === 'showing') { + trackId = id; + break; + } + } + + // 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) { + 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 = null; + }; + + // 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 || details.live) { + // 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 + this._stopTimer(); + } + } + }; + + /** get alternate subtitle tracks list from playlist **/ + + + /** + * This method is responsible for validating the subtitle index and periodically reloading if live. + * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track. + * @param newId - The id of the subtitle track to activate. + */ + SubtitleTrackController.prototype.setSubtitleTrackInternal = function setSubtitleTrackInternal(newId) { + var hls = this.hls, + tracks = this.tracks; + + if (typeof newId !== 'number' || newId < -1 || newId >= tracks.length) { + return; + } + + this._stopTimer(); + this.trackId = newId; + logger["b" /* logger */].log('switching to subtitle track ' + newId); + hls.trigger(events["a" /* default */].SUBTITLE_TRACK_SWITCH, { id: newId }); + if (newId === -1) { + return; + } + + // check if we need to load playlist for this subtitle Track + var subtitleTrack = tracks[newId]; + var details = subtitleTrack.details; + if (!details || details.live) { + // track not retrieved yet, or live playlist we need to (re)load it + logger["b" /* logger */].log('(re)loading playlist for subtitle track ' + newId); + hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId }); + } + }; + + SubtitleTrackController.prototype._stopTimer = function _stopTimer() { + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + }; + + /** + * Disables the old subtitleTrack and sets current mode on the next subtitleTrack. + * This operates on the DOM textTracks. + * A value of -1 will disable all subtitle tracks. + * @param newId - The id of the next track to enable + * @private + */ + + + SubtitleTrackController.prototype._toggleTrackModes = function _toggleTrackModes(newId) { + var media = this.media, + subtitleDisplay = this.subtitleDisplay, + trackId = this.trackId; + + if (!media) { + return; + } + + var textTracks = filterSubtitleTracks(media.textTracks); + if (newId === -1) { + [].slice.call(textTracks).forEach(function (track) { + track.mode = 'disabled'; + }); + } else { + var oldTrack = textTracks[trackId]; + if (oldTrack) { + oldTrack.mode = 'disabled'; + } + } + + var nextTrack = textTracks[newId]; + if (nextTrack) { + nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden'; + } + }; + + 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._toggleTrackModes(subtitleTrackId); + 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__(7); + +// 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__window = window, + subtitle_stream_controller_performance = subtitle_stream_controller__window.performance; + + +var subtitle_stream_controller_State = { + STOPPED: 'STOPPED', + IDLE: 'IDLE', + KEY_LOADING: 'KEY_LOADING', + FRAG_LOADING: 'FRAG_LOADING' +}; + +var subtitle_stream_controller_SubtitleStreamController = function (_TaskLoop) { + subtitle_stream_controller__inherits(SubtitleStreamController, _TaskLoop); + + function SubtitleStreamController(hls) { + subtitle_stream_controller__classCallCheck(this, SubtitleStreamController); + + var _this = subtitle_stream_controller__possibleConstructorReturn(this, _TaskLoop.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.decrypter = new decrypter["a" /* default */](hls.observer, hls.config); + return _this; + } + + SubtitleStreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() { + 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.doTick = function doTick() { + var _this3 = 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.encrypted) { + logger["b" /* logger */].log('Loading key for ' + frag.sn); + _this3.state = subtitle_stream_controller_State.KEY_LOADING; + _this3.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); + _this3.nextFrag(); + } + } + }); + } + }; + + // Got all new subtitle tracks. + + + SubtitleStreamController.prototype.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(data) { + var _this4 = this; + + logger["b" /* logger */].log('subtitle tracks updated'); + this.tracks = data.subtitleTracks; + this.clearVttFragQueues(); + this.vttFragSNsProcessed = {}; + this.tracks.forEach(function (track) { + _this4.vttFragSNsProcessed[track.id] = []; + }); + }; + + SubtitleStreamController.prototype.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(data) { + this.currentTrackId = data.id; + if (!this.tracks || this.currentTrackId === -1) { + return; + } + + // Check if track was already loaded and if so make sure we finish + // downloading its frags, if not all have been downloaded yet + var currentTrack = this.tracks[this.currentTrackId]; + if (currentTrack && currentTrack.details) { + this.tick(); + } + }; + + // 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 = void 0; + try { + startTime = subtitle_stream_controller_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 = void 0; + try { + endTime = subtitle_stream_controller_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; +}(task_loop); + +/* harmony default export */ var subtitle_stream_controller = (subtitle_stream_controller_SubtitleStreamController); +// CONCATENATED MODULE: ./src/controller/eme-controller.js +var eme_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 eme_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function eme_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 eme_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; } + +/** + * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com> + * + * DRM support for Hls.js + */ + + + + + + + +var eme_controller__window = window, + eme_controller_XMLHttpRequest = eme_controller__window.XMLHttpRequest; + + +var MAX_LICENSE_REQUEST_FAILURES = 3; + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess + */ +var KeySystems = { + WIDEVINE: 'com.widevine.alpha', + PLAYREADY: 'com.microsoft.playready' +}; + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration + * @param {Array<string>} audioCodecs List of required audio codecs to support + * @param {Array<string>} videoCodecs List of required video codecs to support + * @param {object} drmSystemOptions Optional parameters/requirements for the key-system + * @returns {Array<MediaSystemConfiguration>} An array of supported configurations + */ + +var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) { + /* jshint ignore:line */ + var baseConfig = { + // initDataTypes: ['keyids', 'mp4'], + // label: "", + // persistentState: "not-allowed", // or "required" ? + // distinctiveIdentifier: "not-allowed", // or "required" ? + // sessionTypes: ['temporary'], + videoCapabilities: [ + // { contentType: 'video/mp4; codecs="avc1.42E01E"' } + ] + }; + + videoCodecs.forEach(function (codec) { + baseConfig.videoCapabilities.push({ + contentType: 'video/mp4; codecs="' + codec + '"' + }); + }); + + return [baseConfig]; +}; + +/** + * The idea here is to handle key-system (and their respective platforms) specific configuration differences + * in order to work with the local requestMediaKeySystemAccess method. + * + * We can also rule-out platform-related key-system support at this point by throwing an error or returning null. + * + * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum + * @param {Array<string>} audioCodecs List of required audio codecs to support + * @param {Array<string>} videoCodecs List of required video codecs to support + * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null` + */ +var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs) { + switch (keySystem) { + case KeySystems.WIDEVINE: + return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs); + default: + throw Error('Unknown key-system: ' + keySystem); + } +}; + +/** + * Controller to deal with encrypted media extensions (EME) + * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API + * + * @class + * @constructor + */ + +var eme_controller_EMEController = function (_EventHandler) { + eme_controller__inherits(EMEController, _EventHandler); + + /** + * @constructs + * @param {Hls} hls Our Hls.js instance + */ + function EMEController(hls) { + eme_controller__classCallCheck(this, EMEController); + + var _this = eme_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MANIFEST_PARSED)); + + _this._widevineLicenseUrl = hls.config.widevineLicenseUrl; + _this._licenseXhrSetup = hls.config.licenseXhrSetup; + _this._emeEnabled = hls.config.emeEnabled; + + _this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc; + + _this._mediaKeysList = []; + _this._media = null; + + _this._hasSetMediaKeys = false; + _this._isMediaEncrypted = false; + + _this._requestLicenseFailureCount = 0; + return _this; + } + + /** + * + * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum + * @returns {string} License server URL for key-system (if any configured, otherwise causes error) + */ + + + EMEController.prototype.getLicenseServerUrl = function getLicenseServerUrl(keySystem) { + var url = void 0; + switch (keySystem) { + case KeySystems.WIDEVINE: + url = this._widevineLicenseUrl; + break; + default: + url = null; + break; + } + + if (!url) { + logger["b" /* logger */].error('No license server URL configured for key-system "' + keySystem + '"'); + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR, + details: errors["a" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED, + fatal: true + }); + } + + return url; + }; + + /** + * Requests access object and adds it to our list upon success + * @private + * @param {string} keySystem System ID (see `KeySystems`) + * @param {Array<string>} audioCodecs List of required audio codecs to support + * @param {Array<string>} videoCodecs List of required video codecs to support + */ + + + EMEController.prototype._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) { + var _this2 = this; + + // TODO: add other DRM "options" + + var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs); + + if (!mediaKeySystemConfigs) { + logger["b" /* logger */].warn('Can not create config for key-system (maybe because platform is not supported):', keySystem); + return; + } + + logger["b" /* logger */].log('Requesting encrypted media key-system access'); + + // expecting interface like window.navigator.requestMediaKeySystemAccess + this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs).then(function (mediaKeySystemAccess) { + _this2._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess); + }).catch(function (err) { + logger["b" /* logger */].error('Failed to obtain key-system "' + keySystem + '" access:', err); + }); + }; + + /** + * Handles obtaining access to a key-system + * + * @param {string} keySystem + * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess + */ + EMEController.prototype._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) { + var _this3 = this; + + logger["b" /* logger */].log('Access for key-system "' + keySystem + '" obtained'); + + var mediaKeysListItem = { + mediaKeys: null, + mediaKeysSession: null, + mediaKeysSessionInitialized: false, + mediaKeySystemAccess: mediaKeySystemAccess, + mediaKeySystemDomain: keySystem + }; + + this._mediaKeysList.push(mediaKeysListItem); + + mediaKeySystemAccess.createMediaKeys().then(function (mediaKeys) { + mediaKeysListItem.mediaKeys = mediaKeys; + + logger["b" /* logger */].log('Media-keys created for key-system "' + keySystem + '"'); + + _this3._onMediaKeysCreated(); + }).catch(function (err) { + logger["b" /* logger */].error('Failed to create media-keys:', err); + }); + }; + + /** + * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this + * for all existing keys where no session exists yet. + */ + + + EMEController.prototype._onMediaKeysCreated = function _onMediaKeysCreated() { + var _this4 = this; + + // check for all key-list items if a session exists, otherwise, create one + this._mediaKeysList.forEach(function (mediaKeysListItem) { + if (!mediaKeysListItem.mediaKeysSession) { + mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession(); + _this4._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession); + } + }); + }; + + /** + * + * @param {*} keySession + */ + + + EMEController.prototype._onNewMediaKeySession = function _onNewMediaKeySession(keySession) { + var _this5 = this; + + logger["b" /* logger */].log('New key-system session ' + keySession.sessionId); + + keySession.addEventListener('message', function (event) { + _this5._onKeySessionMessage(keySession, event.message); + }, false); + }; + + EMEController.prototype._onKeySessionMessage = function _onKeySessionMessage(keySession, message) { + logger["b" /* logger */].log('Got EME message event, creating license request'); + + this._requestLicense(message, function (data) { + logger["b" /* logger */].log('Received license data, updating key-session'); + keySession.update(data); + }); + }; + + EMEController.prototype._onMediaEncrypted = function _onMediaEncrypted(initDataType, initData) { + logger["b" /* logger */].log('Media is encrypted using "' + initDataType + '" init data type'); + + this._isMediaEncrypted = true; + this._mediaEncryptionInitDataType = initDataType; + this._mediaEncryptionInitData = initData; + + this._attemptSetMediaKeys(); + this._generateRequestWithPreferredKeySession(); + }; + + EMEController.prototype._attemptSetMediaKeys = function _attemptSetMediaKeys() { + if (!this._hasSetMediaKeys) { + // FIXME: see if we can/want/need-to really to deal with several potential key-sessions? + var keysListItem = this._mediaKeysList[0]; + if (!keysListItem || !keysListItem.mediaKeys) { + logger["b" /* logger */].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet'); + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR, + details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_KEYS, + fatal: true + }); + return; + } + + logger["b" /* logger */].log('Setting keys for encrypted media'); + + this._media.setMediaKeys(keysListItem.mediaKeys); + this._hasSetMediaKeys = true; + } + }; + + EMEController.prototype._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession() { + var _this6 = this; + + // FIXME: see if we can/want/need-to really to deal with several potential key-sessions? + var keysListItem = this._mediaKeysList[0]; + if (!keysListItem) { + logger["b" /* logger */].error('Fatal: Media is encrypted but not any key-system access has been obtained yet'); + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR, + details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_ACCESS, + fatal: true + }); + return; + } + + if (keysListItem.mediaKeysSessionInitialized) { + logger["b" /* logger */].warn('Key-Session already initialized but requested again'); + return; + } + + var keySession = keysListItem.mediaKeysSession; + if (!keySession) { + logger["b" /* logger */].error('Fatal: Media is encrypted but no key-session existing'); + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR, + details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_SESSION, + fatal: true + }); + } + + var initDataType = this._mediaEncryptionInitDataType; + var initData = this._mediaEncryptionInitData; + + logger["b" /* logger */].log('Generating key-session request for "' + initDataType + '" init data type'); + + keysListItem.mediaKeysSessionInitialized = true; + + keySession.generateRequest(initDataType, initData).then(function () { + logger["b" /* logger */].debug('Key-session generation succeeded'); + }).catch(function (err) { + logger["b" /* logger */].error('Error generating key-session request:', err); + _this6.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR, + details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_SESSION, + fatal: false + }); + }); + }; + + /** + * @param {string} url License server URL + * @param {ArrayBuffer} keyMessage Message data issued by key-system + * @param {function} callback Called when XHR has succeeded + * @returns {XMLHttpRequest} Unsent (but opened state) XHR object + */ + + + EMEController.prototype._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) { + var xhr = new eme_controller_XMLHttpRequest(); + var licenseXhrSetup = this._licenseXhrSetup; + + try { + if (licenseXhrSetup) { + try { + licenseXhrSetup(xhr, url); + } catch (e) { + // let's try to open before running setup + xhr.open('POST', url, true); + licenseXhrSetup(xhr, url); + } + } + // if licenseXhrSetup did not yet call open, let's do it now + if (!xhr.readyState) { + xhr.open('POST', url, true); + } + } catch (e) { + // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS + logger["b" /* logger */].error('Error setting up key-system license XHR', e); + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR, + details: errors["a" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED, + fatal: true + }); + return; + } + + xhr.responseType = 'arraybuffer'; + xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback); + return xhr; + }; + + /** + * @param {XMLHttpRequest} xhr + * @param {string} url License server URL + * @param {ArrayBuffer} keyMessage Message data issued by key-system + * @param {function} callback Called when XHR has succeeded + * + */ + + + EMEController.prototype._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) { + switch (xhr.readyState) { + case 4: + if (xhr.status === 200) { + this._requestLicenseFailureCount = 0; + logger["b" /* logger */].log('License request succeeded'); + callback(xhr.response); + } else { + logger["b" /* logger */].error('License Request XHR failed (' + url + '). Status: ' + xhr.status + ' (' + xhr.statusText + ')'); + + this._requestLicenseFailureCount++; + if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) { + var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1; + logger["b" /* logger */].warn('Retrying license request, ' + attemptsLeft + ' attempts left'); + this._requestLicense(keyMessage, callback); + return; + } + + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR, + details: errors["a" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED, + fatal: true + }); + } + break; + } + }; + + /** + * @param {object} keysListItem + * @param {ArrayBuffer} keyMessage + * @returns {ArrayBuffer} Challenge data posted to license server + */ + + + EMEController.prototype._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) { + var challenge = void 0; + + if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) { + logger["b" /* logger */].error('PlayReady is not supported (yet)'); + + // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js + /* + if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) { + // For PlayReady CDMs, we need to dig the Challenge out of the XML. + var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml'); + if (keyMessageXml.getElementsByTagName('Challenge')[0]) { + challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue); + } else { + throw 'Cannot find <Challenge> in key message'; + } + var headerNames = keyMessageXml.getElementsByTagName('name'); + var headerValues = keyMessageXml.getElementsByTagName('value'); + if (headerNames.length !== headerValues.length) { + throw 'Mismatched header <name>/<value> pair in key message'; + } + for (var i = 0; i < headerNames.length; i++) { + xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue); + } + } + */ + } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) { + // For Widevine CDMs, the challenge is the keyMessage. + challenge = keyMessage; + } else { + logger["b" /* logger */].error('Unsupported key-system:', keysListItem.mediaKeySystemDomain); + } + + return challenge; + }; + + EMEController.prototype._requestLicense = function _requestLicense(keyMessage, callback) { + logger["b" /* logger */].log('Requesting content license for key-system'); + + var keysListItem = this._mediaKeysList[0]; + if (!keysListItem) { + logger["b" /* logger */].error('Fatal error: Media is encrypted but no key-system access has been obtained yet'); + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR, + details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_ACCESS, + fatal: true + }); + return; + } + + var url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain); + var xhr = this._createLicenseXhr(url, keyMessage, callback); + + logger["b" /* logger */].log('Sending license request to URL: ' + url); + + xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage)); + }; + + EMEController.prototype.onMediaAttached = function onMediaAttached(data) { + var _this7 = this; + + if (!this._emeEnabled) { + return; + } + + var media = data.media; + + // keep reference of media + this._media = media; + + // FIXME: also handle detaching media ! + + media.addEventListener('encrypted', function (e) { + _this7._onMediaEncrypted(e.initDataType, e.initData); + }); + }; + + EMEController.prototype.onManifestParsed = function onManifestParsed(data) { + if (!this._emeEnabled) { + return; + } + + var audioCodecs = data.levels.map(function (level) { + return level.audioCodec; + }); + var videoCodecs = data.levels.map(function (level) { + return level.videoCodec; + }); + + this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs); + }; + + eme_controller__createClass(EMEController, [{ + key: 'requestMediaKeySystemAccess', + get: function get() { + if (!this._requestMediaKeySystemAccess) { + throw new Error('No requestMediaKeySystemAccess function configured'); + } + + return this._requestMediaKeySystemAccess; + } + }]); + + return EMEController; +}(event_handler); + +/* harmony default export */ var eme_controller = (eme_controller_EMEController); +// CONCATENATED MODULE: ./src/utils/mediakeys-helper.js +var requestMediaKeySystemAccess = function () { + if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) { + return window.navigator.requestMediaKeySystemAccess.bind(window.navigator); + } else { + return null; + } +}(); + + +// 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 + + 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 + liveDurationInfinity: false, // used by buffer-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 + 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, // used by fragment-loader + pLoader: undefined, // used by playlist-loader + xhrSetup: undefined, // used by xhr-loader + licenseXhrSetup: undefined, // used by eme-controller + // 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 + emeEnabled: false, // used by eme-controller + widevineLicenseUrl: undefined, // used by eme-controller + requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess // used by eme-controller +}; + +if (true) { + hlsDefaultConfig.subtitleStreamController = subtitle_stream_controller; + hlsDefaultConfig.subtitleTrackController = subtitle_track_controller; + hlsDefaultConfig.timelineController = timeline_controller; + hlsDefaultConfig.cueHandler = cues_namespaceObject; // used by timeline-controller + 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; +} + +if (true) { + hlsDefaultConfig.emeController = eme_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"); } } + + + + + + + + + + + + + + + + + + + + + +// polyfill for IE11 +__webpack_require__(13); + +/** + * @module Hls + * @class + * @constructor + */ + +var hls_Hls = function () { + + /** + * @type {boolean} + */ + Hls.isSupported = function isSupported() { + return is_supported_isSupported(); + }; + + /** + * @type {HlsEvents} + */ + + + hls__createClass(Hls, null, [{ + key: 'version', + + /** + * @type {string} + */ + get: function get() { + return "0.10.0"; + } + }, { + key: 'Events', + get: function get() { + return events["a" /* default */]; + } + + /** + * @type {HlsErrorTypes} + */ + + }, { + key: 'ErrorTypes', + get: function get() { + return errors["b" /* ErrorTypes */]; + } + + /** + * @type {HlsErrorDetails} + */ + + }, { + key: 'ErrorDetails', + get: function get() { + return errors["a" /* ErrorDetails */]; + } + + /** + * @type {HlsConfig} + */ + + }, { + key: 'DefaultConfig', + get: function get() { + if (!Hls.defaultConfig) { + return hlsDefaultConfig; + } + + return Hls.defaultConfig; + } + + /** + * @type {HlsConfig} + */ + , + set: function set(defaultConfig) { + Hls.defaultConfig = defaultConfig; + } + + /** + * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`. + * + * @constructs Hls + * @param {HlsConfig} config + */ + + }]); + + 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.once = observer.once.bind(observer); + this.trigger = observer.trigger.bind(observer); + + // core controllers and network loaders + + /** + * @member {AbrController} abrController + */ + 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 + + /** + * @member {LevelController} levelController + */ + var levelController = this.levelController = new level_controller(this); + + // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important + var fragmentTracker = new fragment_tracker_FragmentTracker(this); + + /** + * @member {StreamController} streamController + */ + var streamController = this.streamController = new stream_controller(this, fragmentTracker); + + var networkControllers = [levelController, streamController]; + + // optional audio stream controller + /** + * @var {ICoreComponent | Controller} + */ + var Controller = config.audioStreamController; + if (Controller) { + networkControllers.push(new Controller(this, fragmentTracker)); + } + + /** + * @member {INetworkController[]} networkControllers + */ + this.networkControllers = networkControllers; + + /** + * @var {ICoreComponent[]} + */ + var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker]; + + // optional audio track and subtitle controller + Controller = config.audioTrackController; + if (Controller) { + var audioTrackController = new Controller(this); + + /** + * @member {AudioTrackController} audioTrackController + */ + this.audioTrackController = audioTrackController; + coreComponents.push(audioTrackController); + } + + Controller = config.subtitleTrackController; + if (Controller) { + var subtitleTrackController = new Controller(this); + + /** + * @member {SubtitleTrackController} subtitleTrackController + */ + this.subtitleTrackController = subtitleTrackController; + coreComponents.push(subtitleTrackController); + } + + Controller = config.emeController; + if (Controller) { + var emeController = new Controller(this); + + /** + * @member {EMEController} emeController + */ + this.emeController = emeController; + coreComponents.push(emeController); + } + + // optional subtitle controller + [config.subtitleStreamController, config.timelineController].forEach(function (Controller) { + if (Controller) { + coreComponents.push(new Controller(_this)); + } + }); + + /** + * @member {ICoreComponent[]} + */ + this.coreComponents = coreComponents; + } + + /** + * Dispose of the instance + */ + + + 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; + }; + + /** + * Attach a media element + * @param {HTMLMediaElement} media + */ + + + Hls.prototype.attachMedia = function attachMedia(media) { + logger["b" /* logger */].log('attachMedia'); + this.media = media; + this.trigger(events["a" /* default */].MEDIA_ATTACHING, { media: media }); + }; + + /** + * Detach from the media + */ + + + Hls.prototype.detachMedia = function detachMedia() { + logger["b" /* logger */].log('detachMedia'); + this.trigger(events["a" /* default */].MEDIA_DETACHING); + this.media = null; + }; + + /** + * Set the source URL. Can be relative or absolute. + * @param {string} url + */ + + + 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 }); + }; + + /** + * Start loading data from the stream source. + * Depending on default config, client starts loading automatically when a source is set. + * + * @param {number} startPosition Set the start position to stream from + * @default -1 None (from earliest point) + */ + + + 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); + }); + }; + + /** + * Stop loading of any stream data. + */ + + + Hls.prototype.stopLoad = function stopLoad() { + logger["b" /* logger */].log('stopLoad'); + this.networkControllers.forEach(function (controller) { + controller.stopLoad(); + }); + }; + + /** + * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1) + */ + + + Hls.prototype.swapAudioCodec = function swapAudioCodec() { + logger["b" /* logger */].log('swapAudioCodec'); + this.streamController.swapAudioCodec(); + }; + + /** + * When the media-element fails, this allows to detach and then re-attach it + * as one call (convenience method). + * + * Automatic recovery of media-errors by this process is configurable. + */ + + + Hls.prototype.recoverMediaError = function recoverMediaError() { + logger["b" /* logger */].log('recoverMediaError'); + var media = this.media; + this.detachMedia(); + this.attachMedia(media); + }; + + /** + * @type {QualityLevel[]} + */ + + + hls__createClass(Hls, [{ + key: 'levels', + get: function get() { + return this.levelController.levels; + } + + /** + * Index of quality level currently played + * @type {number} + */ + + }, { + key: 'currentLevel', + get: function get() { + return this.streamController.currentLevel; + } + + /** + * Set quality level index immediately . + * This will flush the current buffer to replace the quality asap. + * That means playback will interrupt at least shortly to re-buffer and re-sync eventually. + * @type {number} -1 for automatic level selection + */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set currentLevel:' + newLevel); + this.loadLevel = newLevel; + this.streamController.immediateLevelSwitch(); + } + + /** + * Index of next quality level loaded as scheduled by stream controller. + * @type {number} + */ + + }, { + key: 'nextLevel', + get: function get() { + return this.streamController.nextLevel; + } + + /** + * Set quality level index for next loaded data. + * This will switch the video quality asap, without interrupting playback. + * May abort current loading of data, and flush parts of buffer (outside currently played fragment region). + * @type {number} -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 the currently or last (of none is loaded currently) segment + * @type {number} + */ + + }, { + key: 'loadLevel', + get: function get() { + return this.levelController.level; + } + + /** + * Set quality level index for next loaded data in a conservative way. + * This will switch the quality without flushing, but interrupt current loading. + * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer. + * @type {number} newLevel -1 for automatic level selection + */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set loadLevel:' + newLevel); + this.levelController.manualLevel = newLevel; + } + + /** + * get next quality level loaded + * @type {number} + */ + + }, { + key: 'nextLoadLevel', + get: function get() { + return this.levelController.nextLoadLevel; + } + + /** + * Set quality level of next loaded segment in a fully "non-destructive" way. + * Same as `loadLevel` but will wait for next switch (until current loading is done). + * @type {number} level + */ + , + set: function set(level) { + this.levelController.nextLoadLevel = level; + } + + /** + * Return "first level": like a default level, if not set, + * falls back to index of first level referenced in manifest + * @type {number} + */ + + }, { + key: 'firstLevel', + get: function get() { + return Math.max(this.levelController.firstLevel, this.minAutoLevel); + } + + /** + * Sets "first-level", see getter. + * @type {number} + */ + , + 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) + * @type {number} + */ + + }, { + 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) + * @type {number} newLevel + */ + , + 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; + } + + /** + * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) + * @type {number} + */ + + }, { + key: 'autoLevelCapping', + get: function get() { + return this._autoLevelCapping; + } + + /** + * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) + * @type {number} + */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set autoLevelCapping:' + newLevel); + this._autoLevelCapping = newLevel; + } + + /** + * True when automatic level selection enabled + * @type {boolean} + */ + + }, { + key: 'autoLevelEnabled', + get: function get() { + return this.levelController.manualLevel === -1; + } + + /** + * Level set manually (if any) + * @type {number} + */ + + }, { + key: 'manualLevel', + get: function get() { + return this.levelController.manualLevel; + } + + /** + * min level selectable in auto mode according to config.minAutoBitrate + * @type {number} + */ + + }, { + 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; + } + + /** + * max level selectable in auto mode according to autoLevelCapping + * @type {number} + */ + + }, { + 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; + } + + /** + * next automatically selected quality level + * @type {number} + */ + + }, { + 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. + * @type {number} + */ + , + set: function set(nextLevel) { + var hls = this; + hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel); + } + + /** + * @type {AudioTrack[]} + */ + + }, { + key: 'audioTracks', + get: function get() { + var audioTrackController = this.audioTrackController; + return audioTrackController ? audioTrackController.audioTracks : []; + } + + /** + * index of the selected audio track (index in audio track lists) + * @type {number} + */ + + }, { + key: 'audioTrack', + get: function get() { + var audioTrackController = this.audioTrackController; + return audioTrackController ? audioTrackController.audioTrack : -1; + } + + /** + * selects an audio track, based on its index in audio track lists + * @type {number} + */ + , + set: function set(audioTrackId) { + var audioTrackController = this.audioTrackController; + if (audioTrackController) { + audioTrackController.audioTrack = audioTrackId; + } + } + + /** + * @type {Seconds} + */ + + }, { + key: 'liveSyncPosition', + get: function get() { + return this.streamController.liveSyncPosition; + } + + /** + * get alternate subtitle tracks list from playlist + * @type {SubtitleTrack[]} + */ + + }, { + key: 'subtitleTracks', + get: function get() { + var subtitleTrackController = this.subtitleTrackController; + return subtitleTrackController ? subtitleTrackController.subtitleTracks : []; + } + + /** + * index of the selected subtitle track (index in subtitle track lists) + * @type {number} + */ + + }, { + 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 + * @type{number} + */ + , + set: function set(subtitleTrackId) { + var subtitleTrackController = this.subtitleTrackController; + if (subtitleTrackController) { + subtitleTrackController.subtitleTrack = subtitleTrackId; + } + } + + /** + * @type {boolean} + */ + + }, { + key: 'subtitleDisplay', + get: function get() { + var subtitleTrackController = this.subtitleTrackController; + return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false; + } + + /** + * Enable/disable subtitle display rendering + * @type {boolean} + */ + , + 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); + +/***/ }), +/* 11 */ +/***/ (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 +} + +var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+' +var dependencyRegExp = '\\((\/\\*.*?\\*\/)?\s?.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true + +// http://stackoverflow.com/a/2593661/130442 +function quoteRegExp (str) { + return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') +} + +function getModuleDependencies (sources, module, queueName) { + var retval = {} + retval[queueName] = [] + + var fnString = module.toString() + var wrapperSignature = fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/) + if (!wrapperSignature) return retval + var webpackRequireName = wrapperSignature[1] + + // main bundle deps + var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g') + var match + while ((match = re.exec(fnString))) { + if (match[3] === 'dll-reference') continue + retval[queueName].push(match[3]) + } + + // dll deps + re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g') + while ((match = re.exec(fnString))) { + if (!sources[match[2]]) { + retval[queueName].push(match[1]) + sources[match[2]] = __webpack_require__(match[1]).m + } + retval[match[2]] = retval[match[2]] || [] + retval[match[2]].push(match[4]) + } + + return retval +} + +function hasValuesInQueues (queues) { + var keys = Object.keys(queues) + return keys.reduce(function (hasValues, key) { + return hasValues || queues[key].length > 0 + }, false) +} + +function getRequiredModules (sources, moduleId) { + var modulesQueue = { + main: [moduleId] + } + var requiredModules = { + main: [] + } + var seenModules = { + main: {} + } + + while (hasValuesInQueues(modulesQueue)) { + var queues = Object.keys(modulesQueue) + for (var i = 0; i < queues.length; i++) { + var queueName = queues[i] + var queue = modulesQueue[queueName] + var moduleToCheck = queue.pop() + seenModules[queueName] = seenModules[queueName] || {} + if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue + seenModules[queueName][moduleToCheck] = true + requiredModules[queueName] = requiredModules[queueName] || [] + requiredModules[queueName].push(moduleToCheck) + var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName) + var newModulesKeys = Object.keys(newModules) + for (var j = 0; j < newModulesKeys.length; j++) { + modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || [] + modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]]) + } + } + } + + return requiredModules +} + +module.exports = function (moduleId, options) { + options = options || {} + var sources = { + main: __webpack_require__.m + } + + var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId) + + var src = '' + + Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) { + var entryModule = 0 + while (requiredModules[module][entryModule]) { + entryModule++ + } + requiredModules[module].push(entryModule) + sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })' + src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n' + }) + + src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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 +} + + +/***/ }), +/* 12 */ +/***/ (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__(9); +/* 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__(6); +/* 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); + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + +/*! http://mths.be/endswith v0.2.0 by @mathias */ +if (!String.prototype.endsWith) { + (function() { + 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` + var defineProperty = (function() { + // IE 8 only supports `Object.defineProperty` on DOM elements + try { + var object = {}; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch(error) {} + return result; + }()); + var toString = {}.toString; + var endsWith = function(search) { + if (this == null) { + throw TypeError(); + } + var string = String(this); + if (search && toString.call(search) == '[object RegExp]') { + throw TypeError(); + } + var stringLength = string.length; + var searchString = String(search); + var searchLength = searchString.length; + var pos = stringLength; + if (arguments.length > 1) { + var position = arguments[1]; + if (position !== undefined) { + // `ToInteger` + pos = position ? Number(position) : 0; + if (pos != pos) { // better `isNaN` + pos = 0; + } + } + } + var end = Math.min(Math.max(pos, 0), stringLength); + var start = end - searchLength; + if (start < 0) { + return false; + } + var index = -1; + while (++index < searchLength) { + if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) { + return false; + } + } + return true; + }; + if (defineProperty) { + defineProperty(String.prototype, 'endsWith', { + 'value': endsWith, + 'configurable': true, + 'writable': true + }); + } else { + String.prototype.endsWith = endsWith; + } + }()); +} + + +/***/ }) +/******/ ])["default"]; +}); +//# sourceMappingURL=hls.js.map \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls.js.map b/grails-app/assets/bower/hls.js/dist/hls.js.map new file mode 100644 index 000000000..c6ca9d38d --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap eea7ce9536ac0097e9d3","webpack:///./src/utils/logger.js","webpack:///./src/events.js","webpack:///./src/errors.js","webpack:///./src/utils/get-self-scope.js","webpack:///./node_modules/url-toolkit/src/url-toolkit.js","webpack:///./src/demux/id3.js","webpack:///./node_modules/events/events.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:///./src/demux/mp4demuxer.js","webpack:///./src/demux/adts.js","webpack:///./src/demux/aacdemuxer.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/remux/aac-helper.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/loader/level-key.js","webpack:///./src/loader/fragment.js","webpack:///./src/utils/attr-list.js","webpack:///./src/utils/codecs.js","webpack:///./src/loader/m3u8-parser.js","webpack:///./src/loader/playlist-loader.js","webpack:///./src/loader/fragment-loader.js","webpack:///./src/loader/key-loader.js","webpack:///./src/controller/fragment-tracker.js","webpack:///./src/utils/binary-search.js","webpack:///./src/utils/buffer-helper.js","webpack:///./src/utils/mediasource-helper.js","webpack:///./src/demux/demuxer.js","webpack:///./src/controller/level-helper.js","webpack:///./src/utils/time-ranges.js","webpack:///./src/utils/discontinuities.js","webpack:///./src/task-loop.js","webpack:///./src/controller/fragment-finders.js","webpack:///./src/controller/stream-controller.js","webpack:///./src/controller/level-controller.js","webpack:///./src/utils/texttrack-utils.js","webpack:///./src/controller/id3-track-controller.js","webpack:///./src/is-supported.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/controller/eme-controller.js","webpack:///./src/utils/mediakeys-helper.js","webpack:///./src/config.js","webpack:///./src/hls.js","webpack:///./node_modules/webworkify-webpack/index.js","webpack:///./src/demux/demuxer-worker.js","webpack:///./node_modules/string.prototype.endswith/endswith.js"],"names":["noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","formatMsg","type","msg","global","getSelfScope","consolePrintFn","func","console","args","apply","exportLoggerFunctions","debugConfig","functions","forEach","bind","enableLogs","e","logger","HlsEvents","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_SWITCHING","LEVEL_SWITCHED","LEVEL_LOADING","LEVEL_LOADED","LEVEL_UPDATED","LEVEL_PTS_UPDATED","AUDIO_TRACKS_UPDATED","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","KEY_SYSTEM_ERROR","MUX_ERROR","OTHER_ERROR","ErrorDetails","KEY_SYSTEM_NO_KEYS","KEY_SYSTEM_NO_ACCESS","KEY_SYSTEM_NO_SESSION","KEY_SYSTEM_LICENSE_REQUEST_FAILED","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_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","window","self","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","exitOnNull","len","c","char2","char3","out","utf8ArrayToStr","AESCrypto","subtle","iv","aesIV","decrypt","name","FastAESKey","expandKey","importKey","removePadding","outputBytes","paddingBytes","DataView","getUint8","slice","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","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","removePKCS7Padding","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","UINT32_MAX","pow","MP4Demuxer","remuxer","resetTimeStamp","initPTS","resetInitSegment","initSegment","audioCodec","videoCodec","duration","initData","parseInitSegment","tracks","audio","video","audiovideo","container","codec","probe","findBox","start","min","bin2str","readUint16","val","readUint32","writeUint32","path","results","subresults","endbox","concat","parseSegmentIndex","moov","moovEndOffset","sidx","references","version","timescale","earliestPresentationTime","firstOffset","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","referenceType","subsegmentDuration","traks","tkhd","trak","trackId","mdhd","hdlr","hdlrType","codecBox","codecType","id","getStartDTS","fragment","trafs","baseTimes","map","traf","tfhd","scale","baseTime","tfdt","isFinite","offsetStartDTS","timeOffset","baseMediaDecodeTime","max","upper","floor","lower","append","contiguous","accurateTimeOffset","startDTS","remux","getAudioConfig","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","navigator","toLowerCase","manifestCodec","adtsSampleingRates","test","Array","indexOf","samplerate","channelCount","isHeaderPattern","getHeaderLength","getFullFrameLength","headerLength","frameLength","newOffset","initTrackConfig","track","getFrameDuration","parseFrameHeader","pts","frameIndex","frameDuration","stamp","appendFrame","header","aacSample","unit","dts","samples","sample","_audioTrack","sequenceNumber","isAAC","inputTimeScale","id3Samples","ADTS","MpegAudio","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","parseInt","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","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","gapTolerance","deltaToFrameEnd","nextAudioPts","data1","data2","endDTS","hasAudio","hasVideo","nb","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","mp4Sample","fillFrame","filter","maxAudioFramesDrift","nextPts","toFixed","missing","newStamp","audioSample","numMissingFrames","unitLen","lastSampleDuration","sampleDuration","silentFrame","reference","rawData","streamType","performance","demuxer","discontinuity","trackSwitch","defaultInitPTS","startTime","now","Date","endTime","stats","tstart","tdecrypt","pushDecrypted","muxConfig","demux","mux","FORBIDDEN_EVENT_NAMES","Set","hls","onEvent","events","handledEvents","useGenericHandler","registerListeners","onHandlerDestroying","unregisterListeners","onHandlerDestroyed","isEventHandler","event","has","on","off","onEventGeneric","eventToFunction","funcName","replace","constructor","_uri","reluri","URLToolkit","buildAbsoluteURL","baseuri","alwaysNormalize","_url","_byteRange","_decryptdata","tagList","_elementaryStreams","Fragment","ElementaryStreamTypes","AUDIO","VIDEO","addElementaryStream","hasElementaryStream","createInitializationVector","segmentNumber","uint8View","fragmentDecryptdataFromLevelkey","levelkey","uri","relurl","baseurl","_programDateTime","rawProgramDateTime","parse","rawByteRange","byteRange","params","split","lastByteRangeEndOffset","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","parseAttrList","attr","decimalInteger","attrName","intValue","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","MP4_REGEX_SUFFIX","findGroup","groups","mediaGroupId","matchingGroup","group","convertAVC1ToAVCOTI","avcdata","substr","resolve","baseUrl","parseMasterPlaylist","string","levels","setCodecs","codecs","level","filtered","preferred","unknownCodecs","M3U8Parser","resolution","bitrate","NAME","CODECS","parseMasterPlaylistMedia","audioGroups","medias","media","TYPE","groupId","default","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","URI","lang","LANGUAGE","groupCodec","parseLevelPlaylist","levelUrlId","currentSN","totalduration","fragments","live","startSN","cc","prevFrag","title","isNaN","urlId","programDateTime","pdt","endPdt","byteRangeEndOffset","value1","value2","toUpperCase","targetduration","decryptparams","keyAttrs","decryptmethod","decrypturi","decryptiv","startParams","startAttrs","startTimeOffset","mapAttrs","BYTERANGE","pop","averagetargetduration","endSN","startCC","endCC","every","needSidxRanges","ContextType","MANIFEST","LEVEL","AUDIO_TRACK","SUBTITLE_TRACK","LevelType","MAIN","SUBTITLE","loaders","canHaveQualityLevels","mapContextToLevelType","context","getResponseUrl","response","createInternalLoader","PLoader","pLoader","Loader","loader","InternalLoader","getInternalLoader","resetInternalLoader","contextType","destroyInternalLoaders","onManifestLoading","load","onLevelLoading","onAudioTrackLoading","onSubtitleTrackLoading","loaderContext","abort","maxRetry","timeout","retryDelay","maxRetryDelay","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","responseType","loaderConfig","loaderCallbacks","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","networkDetails","isSidxRequest","_handleSidxRequest","_handlePlaylistLoaded","tload","_handleManifestParsingError","_handleTrackOrLevelPlaylist","_handleMasterPlaylist","_handleNetworkError","PlaylistLoader","audioTracks","subtitles","embeddedAudioFound","unshift","levelId","levelType","levelDetails","singleLevel","tparsed","sidxUrl","rangeStart","rangeEnd","sidxInfo","segmentRef","segRefInfo","canHaveLevels","loaderName","onFragLoading","FragmentILoader","fLoader","DefaultILoader","loaded","progressData","byteRangeStartOffset","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","decryptkey","decrypturl","EventHandler","onKeyLoading","fragLoadingMaxRetry","fragLoadingRetryDelay","FragmentState","NOT_LOADED","APPENDING","PARTIAL","OK","bufferPadding","create","timeRanges","getBufferedFrag","bufferedFrags","fragmentEntity","body","buffered","bufferedFragKey","detectEvictedFragments","elementaryStream","timeRange","fragmentTimes","time","esData","range","isTimeBuffered","removeFragment","detectPartialFragments","fragKey","getFragmentKey","getBufferedTimes","fragmentPartial","partial","getPartialFragment","timePadding","bestFragment","bestOverlap","isPartial","getState","onFragLoaded","bitrateTest","onBufferAppended","onFragBuffered","hasFragment","removeAllFragments","BinarySearch","search","list","comparisonFunction","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","BufferHelper","isBuffered","bufferInfo","maxHoleDuration","vbuffered","bufferedInfo","nextStart","buffered2","bufferLen","bufferStart","bufferEnd","bufferStartNext","diff","buf2len","buf2end","getMediaSource","WebKitMediaSource","emit","removeListener","forwardMessage","ev","mp4","enableWorker","Worker","w","work","onwmsg","onWorkerMessage","addEventListener","onerror","filename","lineno","postMessage","cmd","JSON","stringify","URL","revokeObjectURL","objectURL","removeEventListener","terminate","removeAllListeners","lastFrag","nextSN","ArrayBuffer","addGroupId","audioGroupIds","textGroupIds","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","TaskLoop","_tickInterval","_tickTimer","_tickCallCount","_boundTick","tick","clearNextTick","clearInterval","hasInterval","hasNextTick","setInterval","millis","clearTimeout","doTick","setTimeout","calculateNextPDT","parsedDateInt","findFragmentByPDT","PDTValue","isArray","firstSegment","lastSegment","seg","findFragmentBySN","fragPrevious","maxFragLookUpTolerance","foundFrag","fragNext","fragmentWithinToleranceTest","candidateLookupTolerance","State","STOPPED","IDLE","FRAG_LOADING_WAITING_RETRY","WAITING_LEVEL","PARSING","PARSED","ENDED","fragmentTracker","audioCodecSwap","_state","stallReported","stopLoad","startLoad","startPosition","lastCurrentTime","fragLoadError","startFragRequested","startLevel","nextLoadLevel","loadedmetadata","nextLoadPosition","forceStartLoad","fragCurrent","_doTickIdle","retryDate","seeking","_checkBuffer","_checkFragmentChanged","levelLastLoaded","startFragPrefetch","currentTime","levelInfo","levelBitrate","maxBufLen","maxBufferSize","maxBufferLength","maxMaxBufferLength","mediaBuffer","altAudio","_fetchPayloadOrEos","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","encrypted","_loadKey","_loadFragment","maxLatency","liveMaxLatencyDuration","liveMaxLatencyDurationCount","liveSyncPosition","computeLivePosition","readyState","targetSN","fragBySN","curSNIdx","sameLevel","nextFrag","fragState","autoLevel","autoLevelEnabled","_reduceMaxBufferLength","followingBufferedFrag","fragPlayingCurrent","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","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","pending","total","tfirst","mediaBuffered","delay","levelRetry","minLength","stallDebounceInterval","_seekToStartPos","expectedPlaying","tnow","nudgeRetry","stalledDuration","_reportStall","_tryFixBufferStall","onFragLoadEmergencyAborted","onBufferFlushed","swapAudioCodec","targetLatency","liveSyncDuration","liveSyncDurationCount","jumpThreshold","_trySkipBufferHole","highBufferWatchdogPeriod","_tryNudgeBuffer","lastEndTime","nudgeMaxRetry","targetTime","nudgeOffset","nextState","previousState","_liveSyncPosition","canload","currentLevelIndex","manualLevelIndex","timer","clearTimer","_levels","levelRetryCount","loadError","loadLevel","onManifestLoaded","bitrateStart","levelSet","levelFromSet","videoCodecFound","audioCodecFound","chromeOrFirefox","fragmentError","SUBTITLES","_firstLevel","firstLevel","setLevelInternal","newLevel","levelProperties","levelError","levelIndex","recoverLevel","errorEvent","errorDetails","redundantLevels","nextAutoLevel","targetdurationMs","reloadInterval","trequest","audioGroupId","findIndex","levelObject","_startLevel","configStartLevel","sendAddTrackEvent","videoEl","document","createEvent","initEvent","dispatchEvent","clearCurrentCues","cues","removeCue","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","mode","Cue","WebKitDataCue","VTTCue","TextTrackCue","cue","addCue","mediaSource","sourceBuffer","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","appendBuffer","remove","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","isLive","ewmaFast","ewmaSlow","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","minAutoLevel","aborted","playbackRate","requestDelay","loadRate","bw","realBitrate","expectedLen","fragLoadedDelay","bufferStarvationDelay","fragLevelNextLoadedDelay","levelNextBitrate","abrMaxWithRealBitrate","loadedBytes","loadedDuration","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","_live","_objectUrl","onsbue","onSBUpdateEnd","onsbe","onSBUpdateError","pendingTracks","onLevelPtsUpdated","audioBuffer","timestampOffset","updating","audioTimestampOffset","audioExpected","videoExpected","sourceBufferNb","onMediaAttaching","ms","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","liveDurationInfinity","flushBuffer","appendError","code","appendErrorMaxRetry","typeIn","bufStart","bufEnd","flushStart","flushEnd","autoLevelCapping","restrictedLevels","capLevelToPlayerSize","_stopCapping","onFpsDropLevelCapping","CapLevelController","isLevelAllowed","droppedLevel","HTMLVideoElement","_startCapping","onLevelsUpdated","detectPlayerSize","levelsLength","getMaxLevel","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","XMLHttpRequest","xhrSetup","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","trackIdBlacklist","onAudioTrackLoaded","updatePeriodMs","_selectInitialAudioTrack","_handleLoadError","_updateTrack","currentAudioTrack","defaultTracks","trackFound","traverseTracks","_needsTrackLoading","_loadTrackDetailsIfNeeded","newId","previousId","language","newTrack","STARTING","PAUSED","WAITING_TRACK","WAITING_INIT_PTS","waitingFragment","videoTrackCC","onInitPtsFound","demuxerId","trackDetails","mainBufferInfo","maxConfigBuffer","audioSwitch","loadIdx","fragLoadIdx","nextBuffered","isSeeking","waitingFrag","waitingFragCC","onAudioTracksUpdated","appendObj","pendingData","appendOnBufferFlush","autoKeyword","directionSetting","lr","rl","alignSetting","middle","left","right","findDirectionSetting","dir","findAlignSetting","align","extend","obj","cobj","p","isIE8","baseObj","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","k","v","dflt","defaultKey","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","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","padding","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","parsingError","inHeader","parser","cueOffset","onparsingerror","reuseVttTextTrack","inUseTrack","manifestTrack","textTrack1","textTrack2","intersection","x1","y1","y2","enabled","Cues","cueHandler","unparsedVttFrags","cueRanges","captionsTracks","captionsProperties","captionsTextTrack1Label","languageCode","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","enableCEA708Captions","channel1","channel2","cea608Parser","ranges","merged","cueRange","overlap","getExistingTrack","existingTrack","createTextTrack","_cleanTracks","lastSn","enableWebVTT","inUseTracks","subtitleDisplay","onLevelSwitching","closedCaptions","decryptData","_parseVTTs","success","currentTrack","getCueById","textTrackCue","onFragDecrypted","onFragParsingUserdata","ccdatas","extractCea608Data","tmpByte","ccbyte1","ccbyte2","ccValid","ccType","actualCCBytes","filterSubtitleTracks","textTrackList","_onTextTracksChanged","subtitleTrack","queuedDefaultTrack","trackChangeListener","useTextTrackPolling","subtitlePollingInterval","subtitleTracks","onTick","onSubtitleTrackLoaded","_stopTimer","setSubtitleTrackInternal","_toggleTrackModes","oldTrack","nextTrack","subtitleTrackId","vttFragSNsProcessed","vttFragQueues","currentlyProcessing","currentTrackId","clearVttFragQueues","onSubtitleFragProcessed","processedFragSNs","fragQueue","currentFragSN","alreadyProcessed","alreadyInQueue","some","fragInQueue","onSubtitleTracksUpdated","onSubtitleTrackSwitch","MAX_LICENSE_REQUEST_FAILURES","KeySystems","WIDEVINE","PLAYREADY","createWidevineMediaKeySystemConfigurations","audioCodecs","videoCodecs","drmSystemOptions","baseConfig","videoCapabilities","contentType","getSupportedMediaKeySystemConfigurations","keySystem","_widevineLicenseUrl","widevineLicenseUrl","_licenseXhrSetup","licenseXhrSetup","_emeEnabled","emeEnabled","_requestMediaKeySystemAccess","requestMediaKeySystemAccessFunc","_mediaKeysList","_media","_hasSetMediaKeys","_isMediaEncrypted","_requestLicenseFailureCount","getLicenseServerUrl","_attemptKeySystemAccess","mediaKeySystemConfigs","requestMediaKeySystemAccess","mediaKeySystemAccess","_onMediaKeySystemAccessObtained","mediaKeysListItem","mediaKeys","mediaKeysSession","mediaKeysSessionInitialized","mediaKeySystemDomain","createMediaKeys","_onMediaKeysCreated","createSession","_onNewMediaKeySession","keySession","sessionId","_onKeySessionMessage","_requestLicense","update","_onMediaEncrypted","initDataType","_mediaEncryptionInitDataType","_mediaEncryptionInitData","_attemptSetMediaKeys","_generateRequestWithPreferredKeySession","keysListItem","setMediaKeys","generateRequest","_createLicenseXhr","keyMessage","_onLicenseRequestReadyStageChange","attemptsLeft","_generateLicenseRequestChallenge","challenge","hlsDefaultConfig","lowBufferWatchdogPeriod","abrController","bufferController","capLevelController","fpsController","minAutoBitrate","subtitleStreamController","subtitleTrackController","audioStreamController","audioTrackController","emeController","require","isSupported","Hls","defaultConfig","DefaultConfig","prop","_autoLevelCapping","once","playListLoader","fragmentLoader","keyLoader","id3TrackController","levelController","networkControllers","Controller","coreComponents","detachMedia","component","attachMedia","loadSource","location","href","controller","recoverMediaError","manualLevel","audioTrackId","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;AAC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A;AACA;AACA;AACA;AACA;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;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sFAAsF;AACtF;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,2BAA2B,mBAAmB,EAAE;AAChD;AACA;AACA;AACA;AACA,CAAC;AACD;;;;;;;;;;;AClKA;;;IAGME,G;;;;;AACJ;;;;;;MAMOC,Q,qBAAUC,I,EAAMC,M,EAAQ;AAC7B;;;;;;;;;;;;;AAaA,QAAIA,SAAS,EAAT,IAAeD,KAAKE,MAAxB,EAAgC;AAC9B;AACA,UAAIF,KAAKC,MAAL,MAAiB,IAAjB,IAAyBD,KAAKC,SAAS,CAAd,MAAqB,IAA9C,IAAsDD,KAAKC,SAAS,CAAd,MAAqB,IAA/E,EAAqF;AACnF;AACA,YAAID,KAAKC,SAAS,CAAd,IAAmB,IAAnB,IAA2BD,KAAKC,SAAS,CAAd,IAAmB,IAAlD,EAAwD;AACtD;AACA,cAAID,KAAKC,SAAS,CAAd,IAAmB,IAAnB,IAA2BD,KAAKC,SAAS,CAAd,IAAmB,IAA9C,IAAsDD,KAAKC,SAAS,CAAd,IAAmB,IAAzE,IAAiFD,KAAKC,SAAS,CAAd,IAAmB,IAAxG,EAA8G;AAC5G,mBAAO,IAAP;AACD;AACF;AACF;AACF;;AAED,WAAO,KAAP;AACD,G;;AAED;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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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;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,mDAAmD,cAAc;;AAEjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;;AAEA;AACA;AACA;AACA,qCAAqC,0BAA0B,EAAE;AACjE,2CAA2C,eAAe;AAC1D;AACA;AACA;;AAEA;AACA,8DAA8D,+DAA+D;;AAE7H;AACA;;AAEA;AACA,kDAAkD,oBAAoB,WAAW;;AAEjF;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,6CAA6C;AAC7C;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB,mBAAmB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,2BAA2B;AAChD;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,uCAAuC,6BAA6B;;AAEpE;;AAEA,oDAAoD,sBAAsB;AAC1E;AACA;AACA;AACA;AACA;AACA,qFAAqF,sCAAsC,EAAE;AAC7H,sIAAsI,+CAA+C,yEAAyE,gBAAgB,EAAE;AAChR,GAAG;;AAEH,4GAA4G,4CAA4C,sEAAsE,gBAAgB,QAAQ;;AAEtP,qCAAqC,0BAA0B;AAC/D,qBAAqB;;AAErB;;AAEA;AACA;AACA;;AAEA;AACA;;;;;;;;;;;;ACtLA;AAAA;AAAA;;;;;AAKA;AACA;AACA;AACA;;AAEA,IAAIggE,gBAAgB,SAAhBA,aAAgB,CAAU7iE,IAAV,EAAgB;AAClC;AACA,MAAI2I,WAAW,IAAI,8CAAJ,EAAf;AACAA,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AgBxoB,KAAKwoB,KAAL,CAAWjmB,MAA3B;AACAogE,mBAAalhE,IAAb,CAAkBzB,KAAKwoB,KAAL,CAAWjmB,MAA7B;AACA,aAAOvC,KAAKwoB,KAAZ;AACD;AACD3oB,SAAKghC,WAAL,CAAiBn3B,OAAjB,EAA0Bi5D,YAA1B;AACD,GAdD;AAeD,CA/DD;;AAiEA,+DAAeD,aAAf,E;;;;;;AC3EA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA,GAAG;AACH,mBAAmB;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,GAAG;AACH;AACA;AACA,EAAE;AACF","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 = 10);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap eea7ce9536ac0097e9d3","import { getSelfScope } from './get-self-scope';\n\nfunction noop () {}\n\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nlet exportedLogger = fakeLogger;\n\n// 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\nconst global = getSelfScope();\n\nfunction consolePrintFn (type) {\n const func = global.console[type];\n if (func) {\n return function (...args) {\n if (args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n\n func.apply(global.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 } else {\n exportedLogger = fakeLogger;\n }\n};\n\nexport var logger = exportedLogger;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/logger.js","/**\n * @readonly\n * @enum {string}\n */\nconst HlsEvents = {\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 }\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 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\nexport default HlsEvents;\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 // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR: 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nexport const ErrorDetails = {\n KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',\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 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","export function getSelfScope () {\n // see https://stackoverflow.com/a/11237259/589493\n if (typeof window === 'undefined') {\n /* eslint-disable-next-line no-undef */\n return self;\n } else {\n return window;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/get-self-scope.js","// 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 = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\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 (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 = 4\n// module chunks = 0","/**\n * ID3 parser\n */\nclass 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\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;\n } // 2^32 / 90\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, true);\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, exitOnNull = false) {\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 (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\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","// 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 = 6\n// module chunks = 0","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","// PKCS7\nexport function removePadding (buffer) {\n const outputBytes = buffer.byteLength;\n const paddingBytes = outputBytes && (new DataView(buffer)).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return buffer.slice(0, outputBytes - paddingBytes);\n } else {\n return buffer;\n }\n}\n\nclass 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\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, removePKCS7Padding) {\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 let 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 removePKCS7Padding ? removePadding(outputInt32.buffer) : 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\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nclass Decrypter {\n constructor (observer, config, { removePKCS7Padding = true } = {}) {\n this.logEnabled = true;\n this.observer = observer;\n this.config = config;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = global.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {}\n }\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\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));\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 } 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","/**\n * MP4 demuxer\n */\nimport { logger } from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4Demuxer {\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\n if (videoCodec == null) {\n videoCodec = 'avc1.42e01e';\n }\n\n const 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\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 });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\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 static bin2str (buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint16 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 8 |\n buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\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 // Find the data for a box specified by its path\n static findBox (data, path) {\n let 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 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 static parseSegmentIndex (initSegment) {\n const moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n const moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n let index = 0;\n let sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n let references;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n const version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n const timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.end + firstOffset;\n\n const referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7FFFFFFF;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n const subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n moovEndOffset\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 let result = [];\n let 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 * 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 */\n static getStartDTS (initData, fragment) {\n let 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 let 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 let 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 static 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 let id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n let 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 let version = tfdt.data[tfdt.start];\n let 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, false);\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\nexport default MP4Demuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/mp4demuxer.js","/**\n * ADTS parser helper\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\nexport function getAudioConfig (observer, data, offset, audioCodec) {\n let 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\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\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 let 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 let headerLength, frameLength, stamp;\n let 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 let frameDuration = getFrameDuration(track.samplerate);\n let header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n let stamp = header.stamp;\n let headerLength = header.headerLength;\n let frameLength = header.frameLength;\n\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n let 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// 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 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\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 let 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\nexport default AACDemuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/aacdemuxer.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 SamplesCoefficients: [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]\n ],\n\n BytesInSlot: [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\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 let header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n let frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;\n let stamp = pts + frameIndex * frameDuration;\n let 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 let headerB = (data[offset + 1] >> 3) & 3;\n let headerC = (data[offset + 1] >> 1) & 3;\n let headerE = (data[offset + 2] >> 4) & 15;\n let headerF = (data[offset + 2] >> 2) & 3;\n let headerG = (data[offset + 2] >> 1) & 1;\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n let columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n let bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n let columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n let sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n let channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n let sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n let bytesInSlot = MpegAudio.BytesInSlot[headerC];\n let samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n let frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\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\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\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 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 let\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\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 let 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 let\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\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\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 let leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\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 let clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG () {\n let 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 this.readBits(1) === 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 let\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 let\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 let chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // 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 let 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();\n } // offset_for_ref_frame[ i ]\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);\n } // 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\nimport Decrypter from '../crypt/decrypter';\n\nclass SampleAesDecrypter {\n constructor (observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config, { removePKCS7Padding: false });\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\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\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\nexport 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\nimport * as ADTS from './adts';\nimport MpegAudio from './mpegaudio';\nimport Event from '../events';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\n// import Hex from '../utils/hex';\nimport { logger } from '../utils/logger';\nimport { 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: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nclass TSDemuxer {\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\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 let start, len = data.length, stt, pid, atf, offset, pes,\n unknownPIDs = false;\n this.contiguous = contiguous;\n let 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)) && pes.pts !== undefined) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n parseID3PES(pes);\n }\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\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\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\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\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)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\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\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)) && pes.pts !== undefined) {\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 let 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\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\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\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 let 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\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 let 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\n if (debug) {\n avcSample.debug += 'NDR ';\n }\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\n if (debug) {\n avcSample.debug += 'IDR ';\n }\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\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 endOfCaptions = true;\n\n let countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n let providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n let userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n let userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n let firstByte = expGolombDecoder.readUByte();\n let secondByte = expGolombDecoder.readUByte();\n\n let totalCCs = 31 & firstByte;\n let 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 } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\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\n if (!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n let 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 let codecarray = unit.data.subarray(1, 4);\n let codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\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\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\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\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 let len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\n } else {\n for (let 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 } 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 let i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n let 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 let 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 let 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 let 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 let 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 let 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 let 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 let 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\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES (pes) {\n let data = pes.data;\n let length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let 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 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 let 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 timestamp = ID3.getTimeStamp(id3Data);\n let pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n let offset = id3Data.length;\n let length = data.length;\n let frameIndex = 0, stamp = 0;\n let 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 let 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\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/remux/aac-helper.js","/**\n * Generate MP4 Box\n*/\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 let 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 let 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 let 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 let 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 let 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 let majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n let avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n let 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 let\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\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 let\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 let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\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 let\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 let\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 let 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\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\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\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n let 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\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 let 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 let 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 let 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\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 let 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 let 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 let 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 let 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\n let 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\nimport AAC from './aac-helper';\nimport MP4 from './mp4-generator';\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\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\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 // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED);\n }\n\n generateIS (audioTrack, videoTrack, timeOffset) {\n let 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\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 let 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 if (nbSamples === 0) {\n return;\n }\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 || (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\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\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 maxBufferHole.\n // 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 gapTolerance = Math.floor(maxBufferHole * 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 should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\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 // 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 hasAudio: false,\n hasVideo: true,\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 let 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 // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter(function (sample) {\n return sample.pts >= 0;\n });\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = timeOffset * inputTimeScale;\n }\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 if (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 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 } // eslint-disable-line brace-style\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 let 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 (let 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 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\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\n firstPTS = 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 let lastSampleDuration = 0;\n let 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\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 hasAudio: true,\n hasVideo: false,\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 (let i = 0; i < nbSamples; i++) {\n let 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 let 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 (let 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 let length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if (length) {\n for (let 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 let offset;\n if (reference === undefined) {\n return value;\n }\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\n return value;\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 let observer = this.observer;\n let streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\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","/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\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\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst performance = global;\n\nclass DemuxerInline {\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 let 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\n let localthis = this;\n // performance.now() not available on WebWorker, at least on Safari Desktop\n let 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 let 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 let demuxer = this.demuxer;\n if (!demuxer ||\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n // so let's check that current demuxer is still valid\n ((discontinuity || trackSwitch) && !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: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer }\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\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\nconst FORBIDDEN_EVENT_NAMES = new Set([\n 'hlsEventGeneric',\n 'hlsHandlerDestroying',\n 'hlsHandlerDestroyed'\n]);\n\nclass EventHandler {\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.onHandlerDestroying();\n this.unregisterListeners();\n this.onHandlerDestroyed();\n }\n\n onHandlerDestroying () {}\n onHandlerDestroyed () {}\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 (FORBIDDEN_EVENT_NAMES.has(event)) {\n throw new Error('Forbidden event-name: ' + event);\n }\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 let eventToFunction = function (event, data) {\n let 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\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n logger.error(`An internal error happened while handling event ${event}. Error message: \"${err.message}\". Here is a stacktrace:`, err);\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","import URLToolkit from 'url-toolkit';\n\nexport default class LevelKey {\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\n return this._uri;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/level-key.js","\nimport URLToolkit from 'url-toolkit';\n\nimport LevelKey from './level-key';\n\nexport default class Fragment {\n constructor () {\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n this.tagList = [];\n\n // Holds the types of data this fragment supports\n this._elementaryStreams = {\n [Fragment.ElementaryStreamTypes.AUDIO]: false,\n [Fragment.ElementaryStreamTypes.VIDEO]: false\n };\n }\n\n /**\n * `type` property for this._elementaryStreams\n *\n * @enum\n */\n static get ElementaryStreamTypes () {\n return {\n AUDIO: 'audio',\n VIDEO: 'video'\n };\n }\n\n get url () {\n if (!this._url && this.relurl) {\n this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\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\n return this._programDateTime;\n }\n\n get byteRange () {\n if (!this._byteRange && !this.rawByteRange) {\n return [];\n }\n\n if (this._byteRange) {\n return this._byteRange;\n }\n\n let 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 || 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n return byteRange;\n }\n\n /**\n * @type {number}\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\n return this._decryptdata;\n }\n\n get encrypted () {\n return !!((this.decryptdata && this.decryptdata.uri !== null) && (this.decryptdata.key === null));\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n addElementaryStream (type) {\n this._elementaryStreams[type] = true;\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n hasElementaryStream (type) {\n return this._elementaryStreams[type] === true;\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 let uint8View = new Uint8Array(16);\n\n for (let 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 let 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\n\n\n// WEBPACK FOOTER //\n// ./src/loader/fragment.js","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n constructor (attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (let 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\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\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\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\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList (input) {\n let match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let 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\n attrs[match[1]] = value;\n }\n return attrs;\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 window.MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/codecs.js","\nimport URLToolkit from 'url-toolkit';\n\nimport Fragment from './fragment';\nimport LevelKey from './level-key';\n\nimport AttrList from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport { isCodecType } from '../utils/codecs';\n\n/**\n * M3U8 parser\n * @module\n */\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\nconst MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nexport default class M3U8Parser {\n static 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\n static convertAVC1ToAVCOTI (codec) {\n let 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 static resolve (url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static 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 const attrs = level.attrs = new AttrList(result[1]);\n level.url = M3U8Parser.resolve(result[2], baseurl);\n\n const 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 = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n }\n return levels;\n }\n\n static 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 = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n media.lang = attrs.LANGUAGE;\n if (!media.name) {\n media.name = media.lang;\n }\n\n if (audioGroups.length) {\n const groupCodec = M3U8Parser.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 static parseLevelPlaylist (string, baseurl, id, type, levelUrlId) {\n let 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 || 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.urlId = levelUrlId;\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 if (level.programDateTime) {\n if (prevFrag) {\n if (frag.rawProgramDateTime) { // PDT discontinuity found\n frag.pdt = Date.parse(frag.rawProgramDateTime);\n } else { // Contiguous fragment\n frag.pdt = prevFrag.pdt + (prevFrag.duration * 1000);\n }\n } else { // First fragment\n frag.pdt = Date.parse(level.programDateTime);\n }\n frag.endPdt = frag.pdt + (frag.duration * 1000);\n }\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', 'SAMPLE-AES-CENC'].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\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\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every((frag) => MP4_REGEX_SUFFIX.test(frag.relurl))) {\n logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new Fragment();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n return level;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/m3u8-parser.js","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport M3U8Parser from './m3u8-parser';\n\nconst { performance } = window;\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\nconst ContextType = {\n MANIFEST: 'manifest',\n LEVEL: 'level',\n AUDIO_TRACK: 'audioTrack',\n SUBTITLE_TRACK: 'subtitleTrack'\n};\n\n/**\n * @enum {string}\n */\nconst LevelType = {\n MAIN: 'main',\n AUDIO: 'audio',\n SUBTITLE: 'subtitle'\n};\n\n/**\n * @constructor\n */\nclass PlaylistLoader extends EventHandler {\n /**\n * @constructs\n * @param {Hls} hls\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\n this.loaders = {};\n }\n\n static get ContextType () {\n return ContextType;\n }\n\n static get LevelType () {\n return LevelType;\n }\n\n /**\n * @param {ContextType} type\n * @returns {boolean}\n */\n static canHaveQualityLevels (type) {\n return (type !== ContextType.AUDIO_TRACK &&\n type !== ContextType.SUBTITLE_TRACK);\n }\n\n /**\n * Map context.type to LevelType\n * @param {{type: ContextType}} context\n * @returns {LevelType}\n */\n static mapContextToLevelType (context) {\n const { type } = context;\n\n switch (type) {\n case ContextType.AUDIO_TRACK:\n return LevelType.AUDIO;\n case ContextType.SUBTITLE_TRACK:\n return LevelType.SUBTITLE;\n default:\n return LevelType.MAIN;\n }\n }\n\n static getResponseUrl (response, context) {\n let url = response.url;\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 return url;\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {object} context\n * @returns {XHRLoader} or other compatible configured overload\n */\n createInternalLoader (context) {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n\n const loader = new InternalLoader(config);\n\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n getInternalLoader (context) {\n return this.loaders[context.type];\n }\n\n resetInternalLoader (contextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n destroyInternalLoaders () {\n for (let contextType in this.loaders) {\n let loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n }\n\n destroy () {\n this.destroyInternalLoaders();\n\n super.destroy();\n }\n\n onManifestLoading (data) {\n this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });\n }\n\n onLevelLoading (data) {\n this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });\n }\n\n onAudioTrackLoading (data) {\n this.load(data.url, { type: ContextType.AUDIO_TRACK, level: 0, id: data.id });\n }\n\n onSubtitleTrackLoading (data) {\n this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: 0, id: data.id });\n }\n\n load (url, context) {\n const config = this.hls.config;\n\n logger.debug(`Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) { // same URL can't overlap\n logger.trace('playlist request ongoing');\n return false;\n } else {\n logger.warn(`aborting previous loader for type: ${context.type}`);\n loader.abort();\n }\n }\n\n let maxRetry,\n timeout,\n retryDelay,\n maxRetryDelay;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case ContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case ContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n context.url = url;\n context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)\n\n const loaderConfig = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay\n };\n\n const loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n logger.debug(`Calling internal loader delegate for URL: ${url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n }\n\n loadsuccess (response, stats, context, networkDetails = null) {\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n\n const string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n }\n\n loaderror (response, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails);\n }\n\n loadtimeout (stats, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, true);\n }\n\n _handleMasterPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n const string = response.data;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levels = M3U8Parser.parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n\n const audioGroups = levels.map(level => ({\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n }));\n\n let audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n let subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n\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\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // 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({\n type: 'main',\n name: 'main'\n });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n url,\n stats,\n networkDetails\n });\n }\n\n _handleTrackOrLevelPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n\n const { id, level, type } = context;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levelUrlId = isNaN(id) ? 0 : id;\n const levelId = isNaN(level) ? levelUrlId : level; // level -> id -> 0\n const levelType = PlaylistLoader.mapContextToLevelType(context);\n\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n levelDetails.tload = stats.tload;\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === ContextType.MANIFEST) {\n const singleLevel = {\n url,\n details: levelDetails\n };\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n const sidxUrl = levelDetails.initSegment.url;\n this.load(sidxUrl, {\n isSidxRequest: true,\n type,\n level,\n levelDetails,\n id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n }\n\n _handleSidxRequest (response, context) {\n const sidxInfo = MP4Demuxer.parseSegmentIndex(new Uint8Array(response.data));\n sidxInfo.references.forEach((segmentRef, index) => {\n const segRefInfo = segmentRef.info;\n const frag = context.levelDetails.fragments[index];\n\n if (frag.byteRange.length === 0) {\n frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);\n }\n });\n\n context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';\n }\n\n _handleManifestParsingError (response, context, reason, networkDetails) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason,\n networkDetails\n });\n }\n\n _handleNetworkError (context, networkDetails, timeout = false) {\n logger.info(`A network error occured while loading a ${context.type}-type playlist`);\n\n let details;\n let fatal;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case ContextType.MANIFEST:\n details = (timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR);\n fatal = true;\n break;\n case ContextType.LEVEL:\n details = (timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR);\n fatal = false;\n break;\n case ContextType.AUDIO_TRACK:\n details = (timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR);\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: loader.url,\n loader,\n context,\n networkDetails\n });\n }\n\n _handlePlaylistLoaded (response, stats, context, networkDetails) {\n const { type, level, id, levelDetails } = context;\n\n if (!levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n const canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(Event.LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats,\n networkDetails\n });\n } else {\n switch (type) {\n case ContextType.AUDIO_TRACK:\n this.hls.trigger(Event.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n case ContextType.SUBTITLE_TRACK:\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n }\n }\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 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\n super.destroy();\n }\n\n onFragLoading (data) {\n const frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n let loader = loaders[type];\n if (loader) {\n logger.warn(`abort previous fragment loader for type: ${type}`);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader =\n config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n let start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (!isNaN(start) && !isNaN(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\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\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\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 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\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\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","import EventHandler from '../event-handler';\nimport Event from '../events';\n\nexport const FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nexport class FragmentTracker extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.BUFFER_APPENDED,\n Event.FRAG_BUFFERED,\n Event.FRAG_LOADED\n );\n\n this.bufferPadding = 0.2;\n\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n\n this.config = hls.config;\n }\n\n destroy () {\n this.fragments = null;\n this.timeRanges = null;\n this.config = null;\n EventHandler.prototype.destroy.call(this);\n super.destroy();\n }\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n getBufferedFrag (position, levelType) {\n const fragments = this.fragments;\n const bufferedFrags = Object.keys(fragments).filter(key => {\n const fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n const frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n const bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n detectEvictedFragments (elementaryStream, timeRange) {\n let fragmentTimes, time;\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (fragmentEntity.buffered === true) {\n const esData = fragmentEntity.range[elementaryStream];\n if (esData) {\n fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n time = fragmentTimes[i];\n\n if (this.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n break;\n }\n }\n }\n }\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n detectPartialFragments (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n if (fragment.hasElementaryStream(elementaryStream) === true) {\n let timeRange = this.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n }\n\n getBufferedTimes (startPTS, endPTS, timeRange) {\n let fragmentTimes = [];\n let startTime, endTime;\n let fragmentPartial = false;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n }\n\n getFragmentKey (fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n }\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n getPartialFragment (time) {\n let timePadding, startTime, endTime;\n let bestFragment = null;\n let bestOverlap = 0;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (this.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - this.bufferPadding;\n endTime = fragmentEntity.body.endPTS + this.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n getState (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n let state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n }\n\n isPartial (fragmentEntity) {\n return fragmentEntity.buffered === true &&\n ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||\n (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));\n }\n\n isTimeBuffered (startPTS, endPTS, timeRange) {\n let startTime, endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n /**\n * Fires when a fragment loading is completed\n */\n onFragLoaded (e) {\n let fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!isNaN(fragment.sn) && !fragment.bitrateTest) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n this.fragments[fragKey] = fragmentEntity;\n }\n }\n\n /**\n * Fires when the buffer is updated\n */\n onBufferAppended (e) {\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n let timeRange = this.timeRanges[elementaryStream];\n this.detectEvictedFragments(elementaryStream, timeRange);\n });\n }\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n onFragBuffered (e) {\n this.detectPartialFragments(e.frag);\n }\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n hasFragment (fragment) {\n const fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n }\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n removeFragment (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n }\n\n /**\n * Remove all fragments from fragment tracker.\n */\n removeAllFragments () {\n this.fragments = Object.create(null);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fragment-tracker.js","let 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 let minIndex = 0;\n let maxIndex = list.length - 1;\n let currentIndex = null;\n let currentElement = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n\n let comparisonResult = comparisonFunction(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\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 * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n * @param {HTMLMediaElement|SourceBuffer} media\n * @param {number} position\n * @returns {boolean}\n */\n static isBuffered (media, position) {\n try {\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 } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo (media, pos, maxHoleDuration) {\n try {\n if (media) {\n let 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\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo (buffered, pos, maxHoleDuration) {\n let 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 let 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 let buf2len = buffered2.length;\n if (buf2len) {\n let 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 let start = buffered2[i].start,\n end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/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/utils/mediasource-helper.js","import EventEmitter from 'events';\nimport work from 'webworkify-webpack';\n\nimport Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst MediaSource = getMediaSource();\n\nclass Demuxer {\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 let 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) {\n 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 };\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 global.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\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\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 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 global.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\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// WEBPACK FOOTER //\n// ./src/demux/demuxer.js","/**\n * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\nimport { logger } from '../utils/logger';\n\nexport function addGroupId (level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nexport function updatePTS (fragments, fromIdx, toIdx) {\n let 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\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\n let 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\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 let 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 // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\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 let 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 let 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/controller/level-helper.js","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r) {\n let log = '', len = r.length;\n for (let i = 0; i < len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n\n return log;\n }\n};\n\nexport default TimeRanges;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/time-ranges.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 && lastLevel.details.fragments && lastLevel.details.fragments.length) {\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","import EventHandler from './event-handler';\n\n/**\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\n\nexport default class TaskLoop extends EventHandler {\n constructor (hls, ...events) {\n super(hls, ...events);\n\n this._tickInterval = null;\n this._tickTimer = null;\n this._tickCallCount = 0;\n this._boundTick = this.tick.bind(this);\n }\n\n /**\n * @override\n */\n onHandlerDestroying () {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n /**\n * @returns {boolean}\n */\n hasInterval () {\n return !!this._tickInterval;\n }\n\n /**\n * @returns {boolean}\n */\n hasNextTick () {\n return !!this._tickTimer;\n }\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n */\n setInterval (millis) {\n if (!this._tickInterval) {\n this._tickInterval = setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n */\n clearInterval () {\n if (this._tickInterval) {\n clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n clearNextTick () {\n if (this._tickTimer) {\n clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n tick () {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.clearNextTick();\n this._tickTimer = setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n doTick () {}\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/task-loop.js","import BinarySearch from '../utils/binary-search';\n\n/**\n * Calculates the PDT of the next load position.\n * bufferEnd in this function is usually the position of the playhead.\n * @param {number} [start = 0] - The PTS of the first fragment within the level\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level\n * @returns {number} nextPdt - The computed PDT\n */\nexport function calculateNextPDT (start = 0, bufferEnd = 0, levelDetails) {\n let pdt = 0;\n if (levelDetails.programDateTime) {\n const parsedDateInt = Date.parse(levelDetails.programDateTime);\n if (!isNaN(parsedDateInt)) {\n pdt = (bufferEnd * 1000) + parsedDateInt - (1000 * start);\n }\n }\n return pdt;\n}\n\n/**\n * Finds the first fragment whose endPDT value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @returns {*|null} fragment - The best matching fragment\n */\nexport function findFragmentByPDT (fragments, PDTValue = null) {\n if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) {\n return null;\n }\n\n // if less than start\n let firstSegment = fragments[0];\n\n if (PDTValue < firstSegment.pdt) {\n return null;\n }\n\n let lastSegment = fragments[fragments.length - 1];\n\n if (PDTValue >= lastSegment.endPdt) {\n return null;\n }\n\n for (let seg = 0; seg < fragments.length; ++seg) {\n let frag = fragments[seg];\n if (PDTValue < frag.endPdt) {\n return frag;\n }\n }\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} [end = 0] - The computed end time of the stream\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nexport function findFragmentBySN (fragPrevious, fragments, bufferEnd = 0, end = 0, maxFragLookUpTolerance = 0) {\n let foundFrag;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n }\n }\n return foundFrag;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest (bufferEnd = 0, maxFragLookUpTolerance = 0, 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 } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fragment-finders.js","/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment from '../loader/fragment';\nimport PlaylistLoader from '../loader/playlist-loader';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { alignDiscontinuities } from '../utils/discontinuities';\nimport TaskLoop from '../task-loop';\nimport { calculateNextPDT, findFragmentByPDT, findFragmentBySN, fragmentWithinToleranceTest } from './fragment-finders';\n\nexport const 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 TaskLoop {\n constructor (hls, fragmentTracker) {\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.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.stallReported = false;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n super.onHandlerDestroyed();\n }\n\n startLoad (startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n this.setInterval(100);\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 let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.clearInterval();\n this.state = State.STOPPED;\n this.forceStartLoad = false;\n }\n\n doTick () {\n switch (this.state) {\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\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log('mediaController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle () {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n // if 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\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\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 (!levelDetails || (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\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 } 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\n if (frag) {\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);\n this._loadKey(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 this._loadFragment(frag);\n }\n }\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\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 if (!levelDetails.programDateTime) { // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\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 } else { // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPDT(fragments, fragPrevious.endPdt + 1);\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 const fragBySN = () => findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n let frag;\n let foundFrag;\n\n if (bufferEnd < end) {\n if (!levelDetails.programDateTime) { // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n } else {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = findFragmentByPDT(fragments, calculateNextPDT(start, bufferEnd, levelDetails));\n if (!foundFrag || fragmentWithinToleranceTest(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) {\n // Fall back to SN order if finding by PDT returns a frag which won't fit within the stream\n // fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise\n logger.warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN');\n foundFrag = fragBySN();\n }\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 } 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 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 _loadKey (frag) {\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\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\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n this.hls.trigger(Event.FRAG_LOADING, { 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(this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\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 this.fragmentTracker.getBufferedFrag(position, PlaylistLoader.LevelType.MAIN);\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 let 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 > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\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 let 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\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 let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\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 const 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 /**\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 nextLevelSwitch () {\n const 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 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 let 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 let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\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\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached (data) {\n let 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 let 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 backtracked flag\n let levels = this.levels;\n if (levels) {\n levels.forEach(level => {\n if (level.details) {\n level.details.fragments.forEach(fragment => {\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\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\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\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\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\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 onManifestLoading () {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed (data) {\n let 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\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\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 let 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\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 let 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 const stats = data.stats;\n const currentLevel = this.levels[fragCurrent.level];\n const 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 = window.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 = window.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\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\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\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let 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\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n let 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 let 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 let 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 if (data.hasAudio === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.VIDEO);\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', frag.sn);\n } else {\n logger.warn('missing video frame(s), backtracking fragment', frag.sn);\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 this.fragmentTracker.removeFragment(frag);\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', frag.sn);\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 let 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 // 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 = window.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 let 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 let 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 onBufferCreated (data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for (let 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 this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = window.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\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 logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = window.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.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 return true;\n }\n return false;\n }\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n _checkBuffer () {\n const { config, media } = this;\n const stallDebounceInterval = 1000;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n const currentTime = media.currentTime;\n const mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n const buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n const expectedPlaying = !((media.paused && media.readyState > 1) || // not playing when media is paused and sufficiently buffered\n media.ended || // not playing when media is ended\n media.buffered.length === 0); // not playing if nothing buffered\n const tnow = window.performance.now();\n\n if (currentTime !== this.lastCurrentTime) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(tnow - this.stalled)}ms`);\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n } else if (expectedPlaying) {\n // The playhead isn't moving but it should be\n // Allow some slack time to for small stalls to resolve themselves\n const stalledDuration = tnow - this.stalled;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);\n if (!this.stalled) {\n this.stalled = tnow;\n return;\n } else if (stalledDuration >= stallDebounceInterval) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n this._tryFixBufferStall(bufferInfo, stalledDuration);\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 if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n this.fragmentTracker.detectEvictedFragments(Fragment.ElementaryStreamTypes.VIDEO, media.buffered);\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 /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDuration - The amount of time Hls.js has been stalling for.\n * @private\n */\n _tryFixBufferStall (bufferInfo, stalledDuration) {\n const { config, media } = this;\n const currentTime = media.currentTime;\n const jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end\n\n const partial = this.fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n this._trySkipBufferHole(partial);\n }\n\n if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n _reportStall (bufferLen) {\n const { hls, media, stallReported } = this;\n if (!stallReported) {\n // Report stalled error once\n this.stallReported = true;\n logger.warn(`Playback stalling at @${media.currentTime} due to low buffer`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n _trySkipBufferHole (partial) {\n const { hls, media } = this;\n const currentTime = media.currentTime;\n let lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (let i = 0; i < media.buffered.length; i++) {\n let startTime = media.buffered.start(i);\n if (currentTime >= lastEndTime && currentTime < startTime) {\n media.currentTime = Math.max(startTime, media.currentTime + 0.1);\n logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${media.currentTime}`);\n this.stalled = null;\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${media.currentTime}`,\n frag: partial\n });\n return;\n }\n lastEndTime = media.buffered.end(i);\n }\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n _tryNudgeBuffer () {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n const nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\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, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, raise fatal error`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n _seekToStartPos () {\n const { media } = this;\n const currentTime = media.currentTime;\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 const startPosition = media.seeking ? currentTime : this.startPosition;\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition) {\n // if startPosition not buffered, let's seek to buffered.start(0)\n logger.log(`target start position not buffered, seek to buffered.start(0) ${startPosition} from current time ${currentTime} `);\n media.currentTime = startPosition;\n }\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// 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';\nimport { addGroupId } from './level-helper';\n\nconst { performance } = window;\n\nexport default class LevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.FRAG_LOADED,\n Event.ERROR);\n\n this.canload = false;\n this.currentLevelIndex = null;\n this.manualLevelIndex = -1;\n this.timer = null;\n }\n\n onHandlerDestroying () {\n this.clearTimer();\n this.manualLevelIndex = -1;\n }\n\n clearTimer () {\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 !== null) {\n this.loadLevel();\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 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (level.attrs && level.attrs.AUDIO) {\n addGroupId(levelFromSet || level, 'audio', level.attrs.AUDIO);\n }\n\n if (level.attrs && level.attrs.SUBTITLES) {\n addGroupId(levelFromSet || level, 'text', level.attrs.SUBTITLES);\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\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 > 0) {\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, {\n levels,\n audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: audioTracks.length > 0 && videoCodecFound\n });\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.currentLevelIndex;\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.currentLevelIndex !== newLevel || !levels[newLevel].details) {\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.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this.currentLevelIndex = newLevel;\n const levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n const level = levels[newLevel];\n const levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n let 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, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n }\n\n get manualLevel () {\n return this.manualLevelIndex;\n }\n\n set manualLevel (newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel () {\n return this._firstLevel;\n }\n\n set firstLevel (newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel () {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel (newLevel) {\n this._startLevel = newLevel;\n }\n\n onError (data) {\n if (data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n let levelError = false, fragmentError = false;\n let levelIndex;\n\n // try to recover not fatal errors\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 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 levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {\n let { config } = this.hls;\n let { details: errorDetails } = errorEvent;\n let level = this._levels[levelIndex];\n let redundantLevels, delay, nextLevel;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(() => this.loadLevel(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`level controller, cannot recover from ${errorDetails} error`);\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;\n logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n logger.warn(`level controller, ${errorDetails}: reload a fragment`);\n this.currentLevelIndex = null;\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.currentLevelIndex) {\n return;\n }\n\n const 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) {\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 const targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration);\n let reloadInterval = targetdurationMs,\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 half of target duration\n reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval));\n logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);\n this.timer = setTimeout(() => this.loadLevel(), reloadInterval);\n } else {\n this.clearTimer();\n }\n }\n\n onAudioTrackSwitched (data) {\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n const urlId = currentLevel.audioGroupIds.findIndex((groupId) => groupId === audioGroupId);\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n loadLevel () {\n logger.debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n const levelObject = this._levels[this.currentLevelIndex];\n\n if (typeof levelObject === 'object' &&\n levelObject.url.length > 0) {\n const level = this.currentLevelIndex;\n const id = levelObject.urlId;\n const url = levelObject.url[id];\n\n logger.log(`Attempt loading level index ${level} with URL-id ${id}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });\n }\n }\n }\n\n get nextLoadLevel () {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel (nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/level-controller.js","\nexport function sendAddTrackEvent (track, videoEl) {\n let event = null;\n try {\n event = new window.Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n event.track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function clearCurrentCues (track) {\n if (track && track.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/texttrack-utils.js","/*\n * id3 metadata track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport ID3 from '../demux/id3';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\n\nclass ID3TrackController extends EventHandler {\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\n }\n }\n\n onMediaDetaching () {\n clearCurrentCues(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n getID3Track (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n let textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\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.getID3Track(this.media.textTracks);\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","import { getMediaSource } from './utils/mediasource-helper';\n\nexport function 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\n\n// WEBPACK FOOTER //\n// ./src/is-supported.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 // 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 let 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 let 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\nclass EwmaBandWidthEstimator {\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 let 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 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// 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 '../utils/buffer-helper';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\n\nconst { performance } = window;\n\nclass AbrController extends EventHandler {\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 const frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, 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 const hls = this.hls;\n const config = hls.config;\n const level = frag.level;\n const isLive = hls.levels[level].details.live;\n\n let ewmaFast, ewmaSlow;\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 }\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 const hls = this.hls;\n const video = hls.media;\n const frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n const loader = frag.loader;\n const 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 // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\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 (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {\n let requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(video.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 = video.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (BufferHelper.bufferInfo(video, 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 const 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 const stats = data.stats;\n const 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.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\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\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel () {\n let hls = this.hls, maxAutoLevel = hls.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = hls.minAutoLevel;\n const video = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = (video ? video.currentTime : 0),\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.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(video, 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\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// 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 '../utils/mediasource-helper';\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\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 // current stream state: true - for live broadcast, false - for VoD content\n this._live = null;\n // cache the self generated object url to detect hijack of video tag\n this._objectUrl = 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.altAudio),\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 let 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 = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n }\n\n onMediaDetaching () {\n logger.log('media source detaching');\n let 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 window.URL.revokeObjectURL(this._objectUrl);\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n logger.warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = 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 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\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\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n let timeRanges = {};\n const sourceBuffer = this.sourceBuffer;\n for (let streamType in sourceBuffer) {\n timeRanges[streamType] = sourceBuffer[streamType].buffered;\n }\n\n this.hls.trigger(Event.BUFFER_APPENDED, { parent, pending, timeRanges });\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 let sourceBuffer = this.sourceBuffer;\n for (let type in sourceBuffer) {\n let 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 (let 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 createSourceBuffers (tracks) {\n let 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\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 let 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 let 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\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 onBufferFlushing (data) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n onLevelUpdated ({ details }) {\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n updateMediaElementDuration () {\n let { config } = this.hls;\n let duration;\n\n if (this._levelDuration === null ||\n !this.media ||\n !this.mediaSource ||\n !this.sourceBuffer ||\n this.media.readyState === 0 ||\n this.mediaSource.readyState !== 'open') {\n return;\n }\n\n for (let type in this.sourceBuffer) {\n if (this.sourceBuffer[type].updating === true) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n\n duration = this.media.duration;\n // initialise to the value that the media source is reporting\n if (this._msDuration === null) {\n this._msDuration = this.mediaSource.duration;\n }\n\n if (this._live === true && config.liveDurationInfinity === true) {\n // Override duration to Infinity\n logger.log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if ((this._levelDuration > this._msDuration && this._levelDuration > duration) ||\n (duration === Infinity || isNaN(duration))) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(`Updating Media Source duration to ${this._levelDuration.toFixed(3)}`);\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n }\n\n doFlush () {\n // loop through all buffer ranges to flush\n while (this.flushRange.length) {\n let 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 let appended = 0;\n let sourceBuffer = this.sourceBuffer;\n try {\n for (let 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 let 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 let 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\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 } 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 }\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 let 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 (let 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\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 constructor (hls) {\n super(hls,\n Event.FPS_DROP_LEVEL_CAPPING,\n Event.MEDIA_ATTACHING,\n Event.MANIFEST_PARSED,\n Event.BUFFER_CODECS);\n\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = null;\n this.levels = [];\n this.media = null;\n this.restrictedLevels = [];\n this.timer = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this._stopCapping();\n }\n }\n\n onFpsDropLevelCapping (data) {\n // 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 onMediaAttaching (data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed (data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && (data.video || (data.levels.length && data.altAudio))) {\n // Start capping immediately if the manifest has signaled video codecs\n this._startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs (data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this._startCapping();\n }\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\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 _startCapping () {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n _stopCapping () {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\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\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\nconst { performance } = window;\n\nclass FPSController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy () {\n if (this.timer) {\n clearInterval(this.timer);\n }\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 window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\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// WEBPACK FOOTER //\n// ./src/controller/fps-controller.js","/**\n * XHR based logger\n*/\n\nimport { logger } from '../utils/logger';\n\nconst { performance, XMLHttpRequest } = window;\n\nclass XhrLoader {\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 let 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 let 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\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 let 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\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 let xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\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","import Event from '../events';\nimport TaskLoop from '../task-loop';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\n/**\n * @class AudioTrackController\n * @implements {EventHandler}\n *\n * Handles main manifest and audio-track metadata loaded,\n * owns and exposes the selectable audio-tracks data-models.\n *\n * Exposes internal interface to select available audio-tracks.\n *\n * Handles errors on loading audio-track playlists. Manages fallback mechanism\n * with redundants tracks (group-IDs).\n *\n * Handles level-loading and group-ID switches for video (fallback on video levels),\n * and eventually adapts the audio-track group-ID to match.\n *\n * @fires AUDIO_TRACK_LOADING\n * @fires AUDIO_TRACK_SWITCHING\n * @fires AUDIO_TRACKS_UPDATED\n * @fires ERROR\n *\n */\nclass AudioTrackController extends TaskLoop {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.AUDIO_TRACK_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.LEVEL_LOADED,\n Event.ERROR\n );\n\n /**\n * @private\n * Currently selected index in `tracks`\n * @member {number} trackId\n */\n this.trackId = -1;\n\n /**\n * @public\n * All tracks available\n * @member {AudioTrack[]}\n */\n this.tracks = [];\n\n /**\n * @public\n * List of blacklisted audio track IDs (that have caused failure)\n * @member {number[]}\n */\n this.trackIdBlacklist = Object.create(null);\n\n /**\n * @public\n * The currently running group ID for audio\n * (we grab this on manifest-parsed and new level-loaded)\n * @member {string}\n */\n this.audioGroupId = null;\n }\n\n /**\n * Reset audio tracks on new manifest loading.\n */\n onManifestLoading () {\n this.tracks = [];\n this.trackId = -1;\n }\n\n /**\n * Store tracks data from manifest parsed data.\n *\n * Trigger AUDIO_TRACKS_UPDATED event.\n *\n * @param {*} data\n */\n onManifestParsed (data) {\n const tracks = this.tracks = data.audioTracks || [];\n this.hls.trigger(Event.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });\n }\n\n /**\n * Store track details of loaded track in our data-model.\n *\n * Set-up metadata update interval task for live-mode streams.\n *\n * @param {} data\n */\n onAudioTrackLoaded (data) {\n if (data.id >= this.tracks.length) {\n logger.warn('Invalid audio track id:', data.id);\n return;\n }\n\n logger.log(`audioTrack ${data.id} loaded`);\n\n this.tracks[data.id].details = data.details;\n\n // check if current playlist is a live playlist\n // and if we have already our reload interval setup\n if (data.details.live && !this.hasInterval()) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n const updatePeriodMs = data.details.targetduration * 1000;\n this.setInterval(updatePeriodMs);\n }\n\n if (!data.details.live && this.hasInterval()) {\n // playlist is not live and timer is scheduled: cancel it\n this.clearInterval();\n }\n }\n\n /**\n * Update the internal group ID to any audio-track we may have set manually\n * or because of a failure-handling fallback.\n *\n * Quality-levels should update to that group ID in this case.\n *\n * @param {*} data\n */\n onAudioTrackSwitched (data) {\n const audioGroupId = this.tracks[data.id].groupId;\n if (audioGroupId && (this.audioGroupId !== audioGroupId)) {\n this.audioGroupId = audioGroupId;\n }\n }\n\n /**\n * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)\n * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.\n *\n * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently\n * selected one (based on NAME property).\n *\n * @param {*} data\n */\n onLevelLoaded (data) {\n // FIXME: crashes because currentLevel is undefined\n // const levelInfo = this.hls.levels[this.hls.currentLevel];\n\n const levelInfo = this.hls.levels[data.level];\n\n if (!levelInfo.audioGroupIds) {\n return;\n }\n\n const audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.audioGroupId !== audioGroupId) {\n this.audioGroupId = audioGroupId;\n this._selectInitialAudioTrack();\n }\n }\n\n /**\n * Handle network errors loading audio track manifests\n * and also pausing on any netwok errors.\n *\n * @param {ErrorEventData} data\n */\n onError (data) {\n // Only handle network errors\n if (data.type !== ErrorTypes.NETWORK_ERROR) {\n return;\n }\n\n // If fatal network error, cancel update task\n if (data.fatal) {\n this.clearInterval();\n }\n\n // If not an audio-track loading error don't handle further\n if (data.details !== ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {\n return;\n }\n\n logger.warn('Network failure on audio-track id:', data.context.id);\n this._handleLoadError();\n }\n\n /**\n * @type {AudioTrack[]} Audio-track list we own\n */\n get audioTracks () {\n return this.tracks;\n }\n\n /**\n * @type {number} Index into audio-tracks list of currently selected track.\n */\n get audioTrack () {\n return this.trackId;\n }\n\n /**\n * Select current track by index\n */\n set audioTrack (newId) {\n // noop on same audio track id as already set\n if (this.trackId === newId && this.tracks[this.trackId].details) {\n logger.debug('Same id as current audio-track passed, and track details available -> no-op');\n return;\n }\n\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n logger.warn('Invalid id passed to audio-track controller');\n return;\n }\n\n const audioTrack = this.tracks[newId];\n\n logger.log(`Now switching to audio-track index ${newId}`);\n\n // stopping live reloading timer if any\n this.clearInterval();\n this.trackId = newId;\n\n const { url, type, id } = audioTrack;\n this.hls.trigger(Event.AUDIO_TRACK_SWITCHING, { id, type, url });\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @override\n */\n doTick () {\n this._updateTrack(this.trackId);\n }\n\n /**\n * Select initial track\n * @private\n */\n _selectInitialAudioTrack () {\n let tracks = this.tracks;\n if (!tracks.length) {\n return;\n }\n\n const currentAudioTrack = this.tracks[this.trackId];\n\n let name = null;\n if (currentAudioTrack) {\n name = currentAudioTrack.name;\n }\n\n // Pre-select default tracks if there are any\n const defaultTracks = tracks.filter((track) => track.default);\n if (defaultTracks.length) {\n tracks = defaultTracks;\n } else {\n logger.warn('No default audio tracks defined');\n }\n\n let trackFound = false;\n\n const traverseTracks = () => {\n // Select track with right group ID\n tracks.forEach((track) => {\n if (trackFound) {\n return;\n }\n // We need to match the (pre-)selected group ID\n // and the NAME of the current track.\n if ((!this.audioGroupId || track.groupId === this.audioGroupId) &&\n (!name || name === track.name)) {\n // If there was a previous track try to stay with the same `NAME`.\n // It should be unique across tracks of same group, and consistent through redundant track groups.\n this.audioTrack = track.id;\n trackFound = true;\n }\n });\n };\n\n traverseTracks();\n\n if (!trackFound) {\n name = null;\n traverseTracks();\n }\n\n if (!trackFound) {\n logger.error(`No track found for running audio group-ID: ${this.audioGroupId}`);\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n * @returns {boolean}\n */\n _needsTrackLoading (audioTrack) {\n const { details } = audioTrack;\n\n if (!details) {\n return true;\n } else if (details.live) {\n return true;\n }\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n */\n _loadTrackDetailsIfNeeded (audioTrack) {\n if (this._needsTrackLoading(audioTrack)) {\n const { url, id } = audioTrack;\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`loading audio-track playlist for id: ${id}`);\n this.hls.trigger(Event.AUDIO_TRACK_LOADING, { url, id });\n }\n }\n\n /**\n * @private\n * @param {number} newId\n */\n _updateTrack (newId) {\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearInterval();\n this.trackId = newId;\n logger.log(`trying to update audio-track ${newId}`);\n const audioTrack = this.tracks[newId];\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @private\n */\n _handleLoadError () {\n // First, let's black list current track id\n this.trackIdBlacklist[this.trackId] = true;\n\n // Let's try to fall back on a functional audio-track with the same group ID\n const previousId = this.trackId;\n const { name, language, groupId } = this.tracks[previousId];\n\n logger.warn(`Loading failed on audio track id: ${previousId}, group-id: ${groupId}, name/language: \"${name}\" / \"${language}\"`);\n\n // Find a non-blacklisted track ID with the same NAME\n // At least a track that is not blacklisted, thus on another group-ID.\n let newId = previousId;\n for (let i = 0; i < this.tracks.length; i++) {\n if (this.trackIdBlacklist[i]) {\n continue;\n }\n const newTrack = this.tracks[i];\n if (newTrack.name === name) {\n newId = i;\n break;\n }\n }\n\n if (newId === previousId) {\n logger.warn(`No fallback audio-track found for name/language: \"${name}\" / \"${language}\"`);\n return;\n }\n\n logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);\n\n this.audioTrack = newId;\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 '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { findFragWithCC } from '../utils/discontinuities';\nimport TaskLoop from '../task-loop';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment from '../loader/fragment';\n\nconst { performance } = window;\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 TaskLoop {\n constructor (hls, fragmentTracker) {\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_RESET,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED,\n Event.INIT_PTS_FOUND);\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.initPTS = [];\n this.waitingFragment = null;\n this.videoTrackCC = null;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n super.onHandlerDestroyed();\n }\n\n // Signal that video PTS was found\n onInitPtsFound (data) {\n let 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 let lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(100);\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 let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\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 doTick () {\n let 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\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\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) or config.maxMaxBufferLength (default: 600s)\n // whichever is smaller.\n // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)\n maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),\n maxBufLen = Math.max(maxConfigBuffer, 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 // check if we need to finalize media stream\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 if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN && !bufferInfo.nextStart) {\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 } // eslint-disable-line brace-style\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 } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\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.encrypted) {\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 // only load if fragment is not loaded or if in audio switch\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) {\n this.fragCurrent = frag;\n this.startFragRequested = true;\n if (!isNaN(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n hls.trigger(Event.FRAG_LOADING, { frag });\n this.state = State.FRAG_LOADING;\n }\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\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 let 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 let 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 // 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\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 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 let 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 this.setInterval(100);\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 }\n this.tick();\n }\n\n onAudioTrackLoaded (data) {\n let 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 let 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\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 let 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 let 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\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 fragCurrent.addElementaryStream(Fragment.ElementaryStreamTypes.AUDIO);\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 let pendingData = this.pendingData;\n\n if (!pendingData) {\n logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');\n hls.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: null, fatal: true });\n return;\n }\n\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 onBufferReset () {\n // reset reference to sourcebuffers\n this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\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\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n const frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n break;\n }\n\n if (!data.fatal) {\n let loadError = this.fragLoadError;\n if (loadError) {\n loadError++;\n } else {\n loadError = 1;\n }\n\n const config = this.config;\n if (loadError <= config.fragLoadingMaxRetry) {\n this.fragLoadError = loadError;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n const 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.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, now switching 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(`AudioStreamController: reduce max buffer length to ${config.maxMaxBufferLength}s`);\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('AudioStreamController: 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('AudioStreamController: appending pending audio data after 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// 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 let autoKeyword = 'auto';\n let directionSetting = {\n '': true,\n lr: true,\n rl: true\n };\n let 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\n let 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\n let align = alignSetting[value.toLowerCase()];\n return align ? value.toLowerCase() : false;\n }\n\n function extend (obj) {\n let i = 1;\n for (; i < arguments.length; i++) {\n let cobj = arguments[i];\n for (let p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue (startTime, endTime, text) {\n let cue = this;\n let isIE8 = (function () {\n if (typeof navigator === 'undefined') {\n return;\n }\n\n return (/MSIE\\s8\\.0/).test(navigator.userAgent);\n })();\n let 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 let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical = '';\n let _snapToLines = true;\n let _line = 'auto';\n let _lineAlign = 'start';\n let _position = 50;\n let _positionAlign = 'middle';\n let _size = 50;\n let _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\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\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 let 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\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\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 let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\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\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 let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\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\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 let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\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 let 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\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\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// Try to parse input as a time stamp.\nfunction parseTimeStamp (input) {\n function computeSeconds (h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;\n }\n\n let 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\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 (let 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 let 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 let groups = groupDelim ? input.split(groupDelim) : [input];\n for (let i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n\n let kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n let k = kv[0];\n let v = kv[1];\n callback(k, v);\n }\n}\n\nlet 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.\nlet 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 let oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp () {\n let ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\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 let 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 (let 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\n settings.alt(k, vals0, ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\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\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 let 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 let 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 let 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 let buffer = self.buffer;\n let pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n ++pos;\n }\n\n let line = buffer.substr(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n\n if (buffer[pos] === '\\n') {\n ++pos;\n }\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 let 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 let 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 let 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\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\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\n self.cue = null;\n self.state = 'ID';\n continue;\n }\n if (self.cue.text) {\n self.cue.text += '\\n';\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\n continue;\n }\n }\n } catch (e) {\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\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 let 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\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 let row;\n let cue;\n let indenting;\n let indent;\n let text;\n let VTTCue = window.VTTCue || window.TextTrackCue;\n\n for (let r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty()) {\n for (let c = 0; c < row.chars.length; c++) {\n if (row.chars[c].uchar.match(/\\s/) && indenting) {\n indent++;\n } else {\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 endTime += 0.0001;\n }\n\n cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));\n\n if (indent >= 16) {\n indent--;\n } else {\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 cue.line = r + 1;\n } else {\n cue.line = (r > 7 ? r - 2 : r + 1);\n }\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// 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\nlet 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 */\nlet getCharForByte = function (byte) {\n let charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n\n return String.fromCharCode(charCode);\n};\n\nlet NR_ROWS = 15,\n NR_COLS = 100;\n// Tables to look up row from PAC data\nlet rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };\nlet rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };\nlet rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };\nlet rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };\n\nlet 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 */\nlet 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 let minLevel = this.verboseFilter[severity];\n if (this.verboseLevel >= minLevel) {\n // console.log(this.time + ' [' + severity + '] ' + msg);\n }\n }\n};\n\nlet numArrayToHexArray = function (numArray) {\n let hexArray = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\nclass PenState {\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 let attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (let i = 0; i < attribs.length; i++) {\n let 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 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 (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals (other) {\n let equal = true;\n for (let 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 (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty () {\n let empty = true;\n for (let 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\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 let newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let 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 let 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 let 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 let chars = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n let char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\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 let 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 constructor () {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row());\n } // 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 (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n }\n\n equals (other) {\n let equal = true;\n for (let 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 (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty () {\n let empty = true;\n for (let 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 let row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow () {\n let 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 let row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen (styles) {\n let row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor (relPos) {\n let row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor (absPos) {\n logger.log('INFO', 'setCursor: ' + absPos);\n let row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC (pacData) {\n logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));\n let 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 let 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 let 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 let row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n let indent = pacData.indent;\n let prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n let 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 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 let topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n let 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 let displayText = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n let 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 constructor (channelNumber, outputFilter) {\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\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 (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n\n let 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\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF () { // Reserved (formerly Alarm Off)\n\n }\n\n ccAON () { // Reserved (formerly Alarm On)\n\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 let 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 let styles = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n let colorIndex = Math.floor(secondByte / 2) - 0x10;\n let 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\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\n this.cueStartTime = t;\n }\n }\n }\n}\n\nclass Cea608Parser {\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 let cmdFound, a, b,\n charsFound = false;\n\n this.lastTime = t;\n logger.setTime(t);\n\n for (let 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\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n if (this.currChNr && this.currChNr >= 0) {\n let 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 let chNr = null;\n\n let cond1 = (a === 0x14 || a === 0x1C) && (b >= 0x20 && b <= 0x2F);\n let cond2 = (a === 0x17 || a === 0x1F) && (b >= 0x21 && 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;\n } // (a === 0x1C || a=== 0x1f)\n\n let 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 let chNr = null;\n\n if (((a === 0x11) || (a === 0x19)) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n\n if (chNr !== this.currChNr) {\n logger.log('ERROR', 'Mismatch channel in midrow parsing');\n return false;\n }\n let 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 let chNr = null;\n let row = null;\n\n let case1 = ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1F)) && (b >= 0x40 && b <= 0x7F);\n let case2 = (a === 0x10 || a === 0x18) && (b >= 0x40 && 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 (b >= 0x40 && 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 let pacData = this.interpretPAC(row, b);\n let 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 let pacIndex = byte;\n let 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\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 let 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 (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let 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\n logger.log('INFO', 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = (b === 0) ? [a] : [a, b];\n }\n if (charCodes) {\n let 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 let bkgData,\n index,\n chNr,\n channel;\n\n let case1 = (a === 0x10 || a === 0x18) && (b >= 0x20 && b <= 0x2f);\n let case2 = (a === 0x17 || a === 0x1f) && (b >= 0x2d && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\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 (let 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 (let 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 constructor (timelineController, trackName) {\n this.timelineController = timelineController;\n this.trackName = trackName;\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\n this.timelineController.addCues(this.trackName, 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\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\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\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 } 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';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\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 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 this.captionsTracks = {};\n\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode\n }\n };\n\n if (this.config.enableCEA708Captions) {\n let channel1 = new OutputFilter(this, 'textTrack1');\n let channel2 = new OutputFilter(this, 'textTrack2');\n\n this.cea608Parser = new Cea608Parser(0, channel1, channel2);\n }\n }\n\n addCues (trackName, 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\n this.Cues.newCue(this.captionsTracks[trackName], 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 (trackName) {\n const { media } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n let textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n createCaptionsTrack (trackName) {\n const { label, languageCode } = this.captionsProperties[trackName];\n const captionsTracks = this.captionsTracks;\n if (!captionsTracks[trackName]) {\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], this.media);\n }\n }\n }\n\n createTextTrack (kind, label, lang) {\n const media = this.media;\n if (media) {\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 const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach(trackName => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n }\n\n onManifestLoading () {\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 _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\n if (track.default) {\n textTrack.mode = this.hls.subtitleDisplay ? 'showing' : 'hidden';\n } else {\n textTrack.mode = 'disabled';\n }\n\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 let 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 } // eslint-disable-line brace-style\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 let 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 } 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 // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n if (currentTrack.mode === 'disabled') {\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n return;\n }\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 );\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 let 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 (let i = 0; i < data.samples.length; i++) {\n let ccdatas = this.extractCea608Data(data.samples[i].bytes);\n this.cea608Parser.addData(data.samples[i].pts, ccdatas);\n }\n }\n }\n\n extractCea608Data (byteArray) {\n let count = byteArray[0] & 31;\n let position = 2;\n let tmpByte, ccbyte1, ccbyte2, ccValid, ccType;\n let actualCCBytes = [];\n\n for (let 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 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 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 = null;\n\n /**\n * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering\n */\n this.subtitleDisplay = true;\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 === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\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) {\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\n if (this.useTextTrackPolling) {\n clearInterval(this.subtitlePollingInterval);\n } else {\n this.media.textTracks.removeEventListener('change', this.trackChangeListener);\n }\n\n this.media = null;\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 || details.live) {\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 this._stopTimer();\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) {\n this._toggleTrackModes(subtitleTrackId);\n this.setSubtitleTrackInternal(subtitleTrackId);\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n * @param newId - The id of the subtitle track to activate.\n */\n setSubtitleTrackInternal (newId) {\n const { hls, tracks } = this;\n if (typeof newId !== 'number' || newId < -1 || newId >= tracks.length) {\n return;\n }\n\n this._stopTimer();\n this.trackId = newId;\n logger.log(`switching to subtitle track ${newId}`);\n hls.trigger(Event.SUBTITLE_TRACK_SWITCH, { id: newId });\n if (newId === -1) {\n return;\n }\n\n // check if we need to load playlist for this subtitle Track\n const subtitleTrack = tracks[newId];\n const details = subtitleTrack.details;\n if (!details || details.live) {\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 hls.trigger(Event.SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId });\n }\n }\n\n _stopTimer () {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n * @param newId - The id of the next track to enable\n * @private\n */\n _toggleTrackModes (newId) {\n const { media, subtitleDisplay, trackId } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n if (newId === -1) {\n [].slice.call(textTracks).forEach(track => {\n track.mode = 'disabled';\n });\n } else {\n const oldTrack = textTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n const nextTrack = textTracks[newId];\n if (nextTrack) {\n nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';\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 { logger } from '../utils/logger';\nimport Decrypter from '../crypt/decrypter';\nimport TaskLoop from '../task-loop';\n\nconst { performance } = window;\n\nconst State = {\n STOPPED: 'STOPPED',\n IDLE: 'IDLE',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING'\n};\n\nclass SubtitleStreamController extends TaskLoop {\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\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.decrypter = new Decrypter(hls.observer, hls.config);\n }\n\n onHandlerDestroyed () {\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\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\n if (this.currentlyProcessing) {\n this.currentlyProcessing = null;\n this.nextFrag();\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 => {\n return fragInQueue.sn === frag.sn;\n });\n };\n\n // exit if tracks don't exist\n if (!tracks) {\n break;\n }\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.encrypted) {\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 if (!this.tracks || this.currentTrackId === -1) {\n return;\n }\n\n // Check if track was already loaded and if so make sure we finish\n // downloading its frags, if not all have been downloaded yet\n const currentTrack = this.tracks[this.currentTrackId];\n if (currentTrack && currentTrack.details) {\n this.tick();\n }\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 let 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 let 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 let 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 * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n *\n * DRM support for Hls.js\n */\n\nimport EventHandler from '../event-handler';\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\nconst { XMLHttpRequest } = window;\n\nconst MAX_LICENSE_REQUEST_FAILURES = 3;\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nconst KeySystems = {\n WIDEVINE: 'com.widevine.alpha',\n PLAYREADY: 'com.microsoft.playready'\n};\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @param {object} drmSystemOptions Optional parameters/requirements for the key-system\n * @returns {Array<MediaSystemConfiguration>} An array of supported configurations\n */\n\nconst createWidevineMediaKeySystemConfigurations = function (audioCodecs, videoCodecs, drmSystemOptions) { /* jshint ignore:line */\n const baseConfig = {\n // initDataTypes: ['keyids', 'mp4'],\n // label: \"\",\n // persistentState: \"not-allowed\", // or \"required\" ?\n // distinctiveIdentifier: \"not-allowed\", // or \"required\" ?\n // sessionTypes: ['temporary'],\n videoCapabilities: [\n // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n ]\n };\n\n videoCodecs.forEach((codec) => {\n baseConfig.videoCapabilities.push({\n contentType: `video/mp4; codecs=\"${codec}\"`\n });\n });\n\n return [\n baseConfig\n ];\n};\n\n/**\n * The idea here is to handle key-system (and their respective platforms) specific configuration differences\n * in order to work with the local requestMediaKeySystemAccess method.\n *\n * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`\n */\nconst getSupportedMediaKeySystemConfigurations = function (keySystem, audioCodecs, videoCodecs) {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);\n default:\n throw Error('Unknown key-system: ' + keySystem);\n }\n};\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\nclass EMEController extends EventHandler {\n /**\n * @constructs\n * @param {Hls} hls Our Hls.js instance\n */\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MANIFEST_PARSED\n );\n\n this._widevineLicenseUrl = hls.config.widevineLicenseUrl;\n this._licenseXhrSetup = hls.config.licenseXhrSetup;\n this._emeEnabled = hls.config.emeEnabled;\n\n this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;\n\n this._mediaKeysList = [];\n this._media = null;\n\n this._hasSetMediaKeys = false;\n this._isMediaEncrypted = false;\n\n this._requestLicenseFailureCount = 0;\n }\n\n /**\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @returns {string} License server URL for key-system (if any configured, otherwise causes error)\n */\n getLicenseServerUrl (keySystem) {\n let url;\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n url = this._widevineLicenseUrl;\n break;\n default:\n url = null;\n break;\n }\n\n if (!url) {\n logger.error(`No license server URL configured for key-system \"${keySystem}\"`);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n\n return url;\n }\n\n /**\n * Requests access object and adds it to our list upon success\n * @private\n * @param {string} keySystem System ID (see `KeySystems`)\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n */\n _attemptKeySystemAccess (keySystem, audioCodecs, videoCodecs) {\n // TODO: add other DRM \"options\"\n\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);\n\n if (!mediaKeySystemConfigs) {\n logger.warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);\n return;\n }\n\n logger.log('Requesting encrypted media key-system access');\n\n // expecting interface like window.navigator.requestMediaKeySystemAccess\n this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs)\n .then((mediaKeySystemAccess) => {\n this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);\n })\n .catch((err) => {\n logger.error(`Failed to obtain key-system \"${keySystem}\" access:`, err);\n });\n }\n\n get requestMediaKeySystemAccess () {\n if (!this._requestMediaKeySystemAccess) {\n throw new Error('No requestMediaKeySystemAccess function configured');\n }\n\n return this._requestMediaKeySystemAccess;\n }\n\n /**\n * Handles obtaining access to a key-system\n *\n * @param {string} keySystem\n * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess\n */\n _onMediaKeySystemAccessObtained (keySystem, mediaKeySystemAccess) {\n logger.log(`Access for key-system \"${keySystem}\" obtained`);\n\n const mediaKeysListItem = {\n mediaKeys: null,\n mediaKeysSession: null,\n mediaKeysSessionInitialized: false,\n mediaKeySystemAccess: mediaKeySystemAccess,\n mediaKeySystemDomain: keySystem\n };\n\n this._mediaKeysList.push(mediaKeysListItem);\n\n mediaKeySystemAccess.createMediaKeys()\n .then((mediaKeys) => {\n mediaKeysListItem.mediaKeys = mediaKeys;\n\n logger.log(`Media-keys created for key-system \"${keySystem}\"`);\n\n this._onMediaKeysCreated();\n })\n .catch((err) => {\n logger.error('Failed to create media-keys:', err);\n });\n }\n\n /**\n * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this\n * for all existing keys where no session exists yet.\n */\n _onMediaKeysCreated () {\n // check for all key-list items if a session exists, otherwise, create one\n this._mediaKeysList.forEach((mediaKeysListItem) => {\n if (!mediaKeysListItem.mediaKeysSession) {\n mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();\n this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);\n }\n });\n }\n\n /**\n *\n * @param {*} keySession\n */\n _onNewMediaKeySession (keySession) {\n logger.log(`New key-system session ${keySession.sessionId}`);\n\n keySession.addEventListener('message', (event) => {\n this._onKeySessionMessage(keySession, event.message);\n }, false);\n }\n\n _onKeySessionMessage (keySession, message) {\n logger.log('Got EME message event, creating license request');\n\n this._requestLicense(message, (data) => {\n logger.log('Received license data, updating key-session');\n keySession.update(data);\n });\n }\n\n _onMediaEncrypted (initDataType, initData) {\n logger.log(`Media is encrypted using \"${initDataType}\" init data type`);\n\n this._isMediaEncrypted = true;\n this._mediaEncryptionInitDataType = initDataType;\n this._mediaEncryptionInitData = initData;\n\n this._attemptSetMediaKeys();\n this._generateRequestWithPreferredKeySession();\n }\n\n _attemptSetMediaKeys () {\n if (!this._hasSetMediaKeys) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem || !keysListItem.mediaKeys) {\n logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n fatal: true\n });\n return;\n }\n\n logger.log('Setting keys for encrypted media');\n\n this._media.setMediaKeys(keysListItem.mediaKeys);\n this._hasSetMediaKeys = true;\n }\n }\n\n _generateRequestWithPreferredKeySession () {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n if (keysListItem.mediaKeysSessionInitialized) {\n logger.warn('Key-Session already initialized but requested again');\n return;\n }\n\n const keySession = keysListItem.mediaKeysSession;\n if (!keySession) {\n logger.error('Fatal: Media is encrypted but no key-session existing');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: true\n });\n }\n\n const initDataType = this._mediaEncryptionInitDataType;\n const initData = this._mediaEncryptionInitData;\n\n logger.log(`Generating key-session request for \"${initDataType}\" init data type`);\n\n keysListItem.mediaKeysSessionInitialized = true;\n\n keySession.generateRequest(initDataType, initData)\n .then(() => {\n logger.debug('Key-session generation succeeded');\n })\n .catch((err) => {\n logger.error('Error generating key-session request:', err);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: false\n });\n });\n }\n\n /**\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n * @returns {XMLHttpRequest} Unsent (but opened state) XHR object\n */\n _createLicenseXhr (url, keyMessage, callback) {\n const xhr = new XMLHttpRequest();\n const licenseXhrSetup = this._licenseXhrSetup;\n\n try {\n if (licenseXhrSetup) {\n try {\n licenseXhrSetup(xhr, url);\n } catch (e) {\n // let's try to open before running setup\n xhr.open('POST', url, true);\n licenseXhrSetup(xhr, url);\n }\n }\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n logger.error('Error setting up key-system license XHR', e);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n return;\n }\n\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange =\n this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);\n return xhr;\n }\n\n /**\n * @param {XMLHttpRequest} xhr\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n *\n */\n _onLicenseRequestReadyStageChange (xhr, url, keyMessage, callback) {\n switch (xhr.readyState) {\n case 4:\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n logger.log('License request succeeded');\n callback(xhr.response);\n } else {\n logger.error(`License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`);\n\n this._requestLicenseFailureCount++;\n if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {\n const attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;\n logger.warn(`Retrying license request, ${attemptsLeft} attempts left`);\n this._requestLicense(keyMessage, callback);\n return;\n }\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n break;\n }\n }\n\n /**\n * @param {object} keysListItem\n * @param {ArrayBuffer} keyMessage\n * @returns {ArrayBuffer} Challenge data posted to license server\n */\n _generateLicenseRequestChallenge (keysListItem, keyMessage) {\n let challenge;\n\n if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {\n logger.error('PlayReady is not supported (yet)');\n\n // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js\n /*\n if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');\n if (keyMessageXml.getElementsByTagName('Challenge')[0]) {\n challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);\n } else {\n throw 'Cannot find <Challenge> in key message';\n }\n var headerNames = keyMessageXml.getElementsByTagName('name');\n var headerValues = keyMessageXml.getElementsByTagName('value');\n if (headerNames.length !== headerValues.length) {\n throw 'Mismatched header <name>/<value> pair in key message';\n }\n for (var i = 0; i < headerNames.length; i++) {\n xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);\n }\n }\n */\n } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {\n // For Widevine CDMs, the challenge is the keyMessage.\n challenge = keyMessage;\n } else {\n logger.error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);\n }\n\n return challenge;\n }\n\n _requestLicense (keyMessage, callback) {\n logger.log('Requesting content license for key-system');\n\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n const url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);\n const xhr = this._createLicenseXhr(url, keyMessage, callback);\n\n logger.log(`Sending license request to URL: ${url}`);\n\n xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));\n }\n\n onMediaAttached (data) {\n if (!this._emeEnabled) {\n return;\n }\n\n const media = data.media;\n\n // keep reference of media\n this._media = media;\n\n // FIXME: also handle detaching media !\n\n media.addEventListener('encrypted', (e) => {\n this._onMediaEncrypted(e.initDataType, e.initData);\n });\n }\n\n onManifestParsed (data) {\n if (!this._emeEnabled) {\n return;\n }\n\n const audioCodecs = data.levels.map((level) => level.audioCodec);\n const videoCodecs = data.levels.map((level) => level.videoCodec);\n\n this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);\n }\n}\n\nexport default EMEController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/eme-controller.js","const requestMediaKeySystemAccess = (function () {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {\n return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);\n } else {\n return null;\n }\n})();\n\nexport {\n requestMediaKeySystemAccess\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/mediakeys-helper.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';\nimport EMEController from './controller/eme-controller';\n\nimport { requestMediaKeySystemAccess } from './utils/mediakeys-helper';\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\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 liveDurationInfinity: false, // used by buffer-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 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, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\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 emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n requestMediaKeySystemAccessFunc:\n requestMediaKeySystemAccess // used by eme-controller\n};\n\nif (__USE_SUBTITLES__) {\n hlsDefaultConfig.subtitleStreamController = SubtitleStreamController;\n hlsDefaultConfig.subtitleTrackController = SubtitleTrackController;\n hlsDefaultConfig.timelineController = TimelineController;\n hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller\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 (__USE_ALT_AUDIO__) {\n hlsDefaultConfig.audioStreamController = AudioStreamController;\n hlsDefaultConfig.audioTrackController = AudioTrackController;\n}\n\nif (__USE_EME_DRM__) {\n hlsDefaultConfig.emeController = EMEController;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/config.js","import URLToolkit from 'url-toolkit';\n\nimport {\n ErrorTypes,\n ErrorDetails\n} from './errors';\n\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { hlsDefaultConfig } from './config';\n\nimport HlsEvents from './events';\nimport EventEmitter from 'events';\n\n// polyfill for IE11\nrequire('string.prototype.endswith');\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\nexport default class Hls {\n /**\n * @type {string}\n */\n static get version () {\n return __VERSION__;\n }\n\n /**\n * @type {boolean}\n */\n static isSupported () {\n return isSupported();\n }\n\n /**\n * @type {HlsEvents}\n */\n static get Events () {\n return HlsEvents;\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n static get ErrorTypes () {\n return ErrorTypes;\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n static get ErrorDetails () {\n return ErrorDetails;\n }\n\n /**\n * @type {HlsConfig}\n */\n static get DefaultConfig () {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n static set DefaultConfig (defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n constructor (config = {}) {\n let 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 (let 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 let 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.once = observer.once.bind(observer);\n this.trigger = observer.trigger.bind(observer);\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n const abrController = this.abrController = new config.abrController(this);\n\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\n /**\n * @member {LevelController} levelController\n */\n const levelController = this.levelController = new LevelController(this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n\n /**\n * @member {StreamController} streamController\n */\n const streamController = this.streamController = new StreamController(this, fragmentTracker);\n\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n const coreComponents = [\n playListLoader,\n fragmentLoader,\n keyLoader,\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker\n ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n const audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n const subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n coreComponents.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n const emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\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\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n destroy () {\n logger.log('destroy');\n this.trigger(HlsEvents.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {\n component.destroy();\n });\n this.url = null;\n this.observer.removeAllListeners();\n this._autoLevelCapping = -1;\n }\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n attachMedia (media) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(HlsEvents.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach from the media\n */\n detachMedia () {\n logger.log('detachMedia');\n this.trigger(HlsEvents.MEDIA_DETACHING);\n this.media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\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(HlsEvents.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n startLoad (startPosition = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach(controller => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad () {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec () {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError () {\n logger.log('recoverMediaError');\n let media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n }\n\n /**\n * @type {QualityLevel[]}\n */\n get levels () {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel () {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @type {number} -1 for automatic level selection\n */\n set currentLevel (newLevel) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n get nextLevel () {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n set nextLevel (newLevel) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n get loadLevel () {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n set loadLevel (newLevel) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n get nextLoadLevel () {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n set nextLoadLevel (level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n get firstLevel () {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n set firstLevel (newLevel) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\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\n * (determined from download of first segment)\n * @type {number}\n */\n get startLevel () {\n return this.levelController.startLevel;\n }\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\n * (determined from download of first segment)\n * @type {number} newLevel\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\n hls.levelController.startLevel = newLevel;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n get autoLevelCapping () {\n return this._autoLevelCapping;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n set autoLevelCapping (newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n get autoLevelEnabled () {\n return (this.levelController.manualLevel === -1);\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n get manualLevel () {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\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 /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\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\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\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 /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * 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,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n set nextAutoLevel (nextLevel) {\n const hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n get audioTracks () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n get audioTrack () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n set audioTrack (audioTrackId) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n get liveSyncPosition () {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n get subtitleTracks () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n get subtitleTrack () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type{number}\n */\n set subtitleTrack (subtitleTrackId) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n get subtitleDisplay () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\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\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\((\\/\\\\*.*?\\\\*\\/)?\\s?.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_modules__\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\\n'\n })\n\n src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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 = 11\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\nimport DemuxerInline from '../demux/demuxer-inline';\nimport Event from '../events';\nimport { enableLogs } from '../utils/logger';\nimport EventEmitter from 'events';\n\nlet DemuxerWorker = function (self) {\n // observer setup\n let 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 let forwardMessage = function (ev, data) {\n self.postMessage({ event: ev, data: data });\n };\n\n self.addEventListener('message', function (ev) {\n let 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// WEBPACK FOOTER //\n// ./src/demux/demuxer-worker.js","/*! http://mths.be/endswith v0.2.0 by @mathias */\nif (!String.prototype.endsWith) {\n\t(function() {\n\t\t'use strict'; // needed to support `apply`/`call` with `undefined`/`null`\n\t\tvar defineProperty = (function() {\n\t\t\t// IE 8 only supports `Object.defineProperty` on DOM elements\n\t\t\ttry {\n\t\t\t\tvar object = {};\n\t\t\t\tvar $defineProperty = Object.defineProperty;\n\t\t\t\tvar result = $defineProperty(object, object, object) && $defineProperty;\n\t\t\t} catch(error) {}\n\t\t\treturn result;\n\t\t}());\n\t\tvar toString = {}.toString;\n\t\tvar endsWith = function(search) {\n\t\t\tif (this == null) {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar string = String(this);\n\t\t\tif (search && toString.call(search) == '[object RegExp]') {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar stringLength = string.length;\n\t\t\tvar searchString = String(search);\n\t\t\tvar searchLength = searchString.length;\n\t\t\tvar pos = stringLength;\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tvar position = arguments[1];\n\t\t\t\tif (position !== undefined) {\n\t\t\t\t\t// `ToInteger`\n\t\t\t\t\tpos = position ? Number(position) : 0;\n\t\t\t\t\tif (pos != pos) { // better `isNaN`\n\t\t\t\t\t\tpos = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar end = Math.min(Math.max(pos, 0), stringLength);\n\t\t\tvar start = end - searchLength;\n\t\t\tif (start < 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar index = -1;\n\t\t\twhile (++index < searchLength) {\n\t\t\t\tif (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\tif (defineProperty) {\n\t\t\tdefineProperty(String.prototype, 'endsWith', {\n\t\t\t\t'value': endsWith,\n\t\t\t\t'configurable': true,\n\t\t\t\t'writable': true\n\t\t\t});\n\t\t} else {\n\t\t\tString.prototype.endsWith = endsWith;\n\t\t}\n\t}());\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/string.prototype.endswith/endswith.js\n// module id = 13\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls.light.js b/grails-app/assets/bower/hls.js/dist/hls.light.js new file mode 100644 index 000000000..fd79a2b50 --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls.light.js @@ -0,0 +1,13855 @@ +(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 = 10); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 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; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__get_self_scope__ = __webpack_require__(4); +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; + +// 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; +} + +var global = Object(__WEBPACK_IMPORTED_MODULE_0__get_self_scope__["a" /* getSelfScope */])(); + +function consolePrintFn(type) { + var func = global.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(global.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"; +/** + * @readonly + * @enum {string} + */ +var HlsEvents = { + // 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 } + 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 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' +}; + +/* harmony default export */ __webpack_exports__["a"] = (HlsEvents); + +/***/ }), +/* 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', + // EME (encrypted media extensions) errors + KEY_SYSTEM_ERROR: 'keySystemError', + // Identifier for a mux Error (demuxing/remuxing) + MUX_ERROR: 'muxError', + // Identifier for all other errors + OTHER_ERROR: 'otherError' +}; + +/** + * @enum {ErrorDetails} + * @typedef {string} ErrorDetail + */ +var ErrorDetails = { + KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys', + KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess', + KEY_SYSTEM_NO_SESSION: 'keySystemNoSession', + KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed', + // 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 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, exports) { + +// This file is inserted as a shim for modules which we do not want to include into the distro. +// This replacement is done in the "resolve" section of the webpack config. +module.exports = void 0; + +/***/ }), +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = getSelfScope; +function getSelfScope() { + // see https://stackoverflow.com/a/11237259/589493 + if (typeof window === 'undefined') { + /* eslint-disable-next-line no-undef */ + return self; + } else { + return window; + } +} + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +// see https://tools.ietf.org/html/rfc1808 + +/* jshint ignore:start */ +(function(root) { +/* jshint ignore:end */ + + var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/; + 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 (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 <net_loc> is non-empty, we skip to + // Step 7. Otherwise, the embedded URL inherits the <net_loc> + // (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 <params> is non-empty, we skip to + // step 7; otherwise, it inherits the <params> of the base + // URL (if any) and + if (!relativeParts.params) { + builtParts.params = baseParts.params; + // 5b) if the embedded URL's <query> is non-empty, we skip to + // step 7; otherwise, it inherits the <query> 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 "<segment>/../", where <segment> 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 "<segment>/..", where <segment> is a + // complete path segment not equal to "..", that + // "<segment>/.." 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 */ + + +/***/ }), +/* 6 */ +/***/ (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; +} + + +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* unused harmony export 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: <text string>\0<binary data> + */ + if (frame.size < 2) { + return undefined; + } + + var owner = ID3._utf8ArrayToStr(frame.data, true); + 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 <iz@onicos.co.jp> + * 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 exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + 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 (c === 0x00 && exitOnNull) { + return out; + } else if (c === 0x00 || c === 0x03) { + // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it + 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); + + + +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1); +function _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 = function () { + function MP4Demuxer(observer, remuxer) { + _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(__WEBPACK_IMPORTED_MODULE_1__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.readUint16 = function readUint16(buffer, offset) { + if (buffer.data) { + offset += buffer.start; + buffer = buffer.data; + } + + var val = buffer[offset] << 8 | buffer[offset + 1]; + + return val < 0 ? 65536 + val : val; + }; + + 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 = void 0, + size = void 0, + type = void 0, + end = void 0, + subresults = void 0, + start = void 0, + endbox = void 0; + + 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; + }; + + MP4Demuxer.parseSegmentIndex = function parseSegmentIndex(initSegment) { + var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0]; + var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data + + var index = 0; + var sidx = MP4Demuxer.findBox(initSegment, ['sidx']); + var references = void 0; + + if (!sidx || !sidx[0]) { + return null; + } + + references = []; + sidx = sidx[0]; + + var version = sidx.data[0]; + + // set initial offset, we skip the reference ID (not needed) + index = version === 0 ? 8 : 16; + + var timescale = MP4Demuxer.readUint32(sidx, index); + index += 4; + + // TODO: parse earliestPresentationTime and firstOffset + // usually zero in our case + var earliestPresentationTime = 0; + var firstOffset = 0; + + if (version === 0) { + index += 8; + } else { + index += 16; + } + + // skip reserved + index += 2; + + var startByte = sidx.end + firstOffset; + + var referencesCount = MP4Demuxer.readUint16(sidx, index); + index += 2; + + for (var i = 0; i < referencesCount; i++) { + var referenceIndex = index; + + var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex); + referenceIndex += 4; + + var referenceSize = referenceInfo & 0x7FFFFFFF; + var referenceType = (referenceInfo & 0x80000000) >>> 31; + + if (referenceType === 1) { + console.warn('SIDX has hierarchical references (not supported)'); + return; + } + + var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex); + referenceIndex += 4; + + references.push({ + referenceSize: referenceSize, + subsegmentDuration: subsegmentDuration, // unscaled + info: { + duration: subsegmentDuration / timescale, + start: startByte, + end: startByte + referenceSize - 1 + } + }); + + startByte += referenceSize; + + // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits + // for |sapDelta|. + referenceIndex += 4; + + // skip to next ref + index = referenceIndex; + } + + return { + earliestPresentationTime: earliestPresentationTime, + timescale: timescale, + version: version, + referencesCount: referencesCount, + references: references, + moovEndOffset: moovEndOffset + }; + }; + + /** + * 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)); + __WEBPACK_IMPORTED_MODULE_0__utils_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 = void 0, + baseTimes = void 0, + result = void 0; + + // 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 = void 0, + scale = void 0, + baseTime = void 0; + + // 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 = void 0, + result = void 0; + + 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, false); + 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(__WEBPACK_IMPORTED_MODULE_1__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 */ __webpack_exports__["a"] = (MP4Demuxer); + +/***/ }), +/* 9 */ +/***/ (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); + +// 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"); } } + +// PKCS7 +function removePadding(buffer) { + var outputBytes = buffer.byteLength; + var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1); + if (paddingBytes) { + return buffer.slice(0, outputBytes - paddingBytes); + } else { + return buffer; + } +} + +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, removePKCS7Padding) { + 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 = void 0, + i = void 0; + 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 removePKCS7Padding ? removePadding(outputInt32.buffer) : 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/utils/logger.js +var logger = __webpack_require__(0); + +// EXTERNAL MODULE: ./src/utils/get-self-scope.js +var get_self_scope = __webpack_require__(4); + +// 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"); } } + + + + + + + + + + + + +// see https://stackoverflow.com/a/11237259/589493 +var global = Object(get_self_scope["a" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread + +var decrypter_Decrypter = function () { + function Decrypter(observer, config) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$removePKCS7Paddi = _ref.removePKCS7Padding, + removePKCS7Padding = _ref$removePKCS7Paddi === undefined ? true : _ref$removePKCS7Paddi; + + decrypter__classCallCheck(this, Decrypter); + + this.logEnabled = true; + this.observer = observer; + this.config = config; + this.removePKCS7Padding = removePKCS7Padding; + // built in decryptor expects PKCS7 padding + if (removePKCS7Padding) { + try { + var browserCrypto = global.crypto; + if (browserCrypto) { + 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, this.removePKCS7Padding)); + } 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(events["a" /* default */].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 crypt_decrypter = (decrypter_Decrypter); +// CONCATENATED MODULE: ./src/demux/adts.js +/** + * ADTS parser helper + */ + + + + + + + +function getAudioConfig(observer, data, offset, audioCodec) { + var adtsObjectType = void 0, + // :int + adtsSampleingIndex = void 0, + // :int + adtsExtensionSampleingIndex = void 0, + // :int + adtsChanelConfig = void 0, + // :int + config = void 0, + 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(events["a" /* default */].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 = void 0, + frameLength = void 0, + stamp = void 0; + 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__(7); + +// CONCATENATED MODULE: ./src/demux/aacdemuxer.js +function aacdemuxer__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) { + aacdemuxer__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); +// EXTERNAL MODULE: ./src/demux/mp4demuxer.js +var mp4demuxer = __webpack_require__(8); + +// 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], + + SamplesCoefficients: [ + // MPEG 2.5 + [0, // Reserved + 72, // Layer3 + 144, // Layer2 + 12 // Layer1 + ], + // Reserved + [0, // Reserved + 0, // Layer3 + 0, // Layer2 + 0 // Layer1 + ], + // MPEG 2 + [0, // Reserved + 72, // Layer3 + 144, // Layer2 + 12 // Layer1 + ], + // MPEG 1 + [0, // Reserved + 144, // Layer3 + 144, // Layer2 + 12 // Layer1 + ]], + + BytesInSlot: [0, // Reserved + 1, // Layer3 + 1, // Layer2 + 4 // Layer1 + ], + + 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 = header.samplesPerFrame * 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] >> 1 & 1; + 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 channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono) + var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC]; + var bytesInSlot = MpegAudio.BytesInSlot[headerC]; + var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot; + var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot; + + return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame }; + } + + 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 = void 0; // :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 = void 0; // :uint + for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) { + if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) { + // 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 this.readBits(1) === 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 = void 0, + deltaScale = void 0; + 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 = void 0, + profileCompat = void 0, + levelIdc = void 0, + numRefFramesInPicOrderCntCycle = void 0, + picWidthInMbsMinus1 = void 0, + picHeightInMapUnitsMinus1 = void 0, + frameMbsOnlyFlag = void 0, + scalingListCount = void 0, + i = void 0, + 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(observer, config, { removePKCS7Padding: false }); + } + + 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: 1, + audio: 2, + id3: 3, + text: 4 +}; + +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 = void 0, + len = data.length, + stt = void 0, + pid = void 0, + atf = void 0, + offset = void 0, + pes = void 0, + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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)) && pes.pts !== undefined) { + 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 = void 0, + tableEnd = void 0, + programInfoLength = void 0, + pid = void 0, + 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 = void 0, + pesFlags = void 0, + pesPrefix = void 0, + pesLen = void 0, + pesHdrLen = void 0, + pesData = void 0, + pesPts = void 0, + pesDts = void 0, + payloadStartOffset = void 0, + 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 = void 0, + avcSample = this.avcSample, + push = void 0, + spsfound = false, + i = void 0, + 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 = void 0, + overflow = void 0, + track = this._avcTrack, + state = track.naluState || 0, + lastState = state; + var units = [], + unit = void 0, + unitType = void 0, + lastUnitStart = -1, + lastUnitType = void 0; + // 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 = void 0, + newData = void 0; + + // 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 = void 0, + frameIndex = void 0, + offset = void 0, + stamp = void 0, + len = void 0; + 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 = void 0, + fatal = void 0; + 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 = void 0, + length = void 0; + 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 timestamp = id3["a" /* default */].getTimeStamp(id3Data); + var pts = timestamp ? 90 * timestamp : timeOffset * 90000; + 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/remux/aac-helper.js +function aac_helper__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_helper__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_helper = (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 +*/ + +var 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 = void 0; + 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 // sample_count + ]); + 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 = void 0; + // 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 / (UINT32_MAX + 1)); + var lowerWordDuration = Math.floor(duration % (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 / (UINT32_MAX + 1)); + var lowerWordDuration = Math.floor(duration % (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 = void 0, + i = void 0; + // 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 = void 0, + data = void 0, + len = void 0; + // 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 = sps.concat(Array.prototype.slice.call(data)); + } + + // 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]; + + 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 / (UINT32_MAX + 1)), + lowerWordDuration = Math.floor(duration % (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 / (UINT32_MAX + 1)), + lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (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 = void 0, + sample = void 0, + duration = void 0, + size = void 0, + flags = void 0, + cts = void 0; + 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 = void 0; + 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 { + // logger.log('nb AVC samples:' + videoTrack.samples.length); + if (nbVideoSamples) { + var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, 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 = void 0, + initDTS = void 0; + + 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 = void 0, + mdat = void 0, + moof = void 0, + firstPTS = void 0, + firstDTS = void 0, + nextDTS = void 0, + lastPTS = void 0, + lastDTS = void 0, + 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; + + if (nbSamples === 0) { + return; + } + + // 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 || 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 maxBufferHole. + // 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, + gapTolerance = Math.floor(maxBufferHole * 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 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', + hasAudio: false, + hasVideo: true, + 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 = void 0, + mp4Sample = void 0, + fillFrame = void 0, + mdat = void 0, + moof = void 0, + firstPTS = void 0, + lastPTS = void 0, + 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); + + // compute normalized PTS + inputSamples.forEach(function (sample) { + sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale); + }); + + // filter out sample with negative PTS that are not playable anyway + // if we don't remove these negative samples, they will shift all audio samples forward. + // leading to audio overlap between current / next fragment + inputSamples = inputSamples.filter(function (sample) { + return sample.pts >= 0; + }); + + // in case all samples have negative PTS, and have been filtered out, return now + if (inputSamples.length === 0) { + return; + } + + if (!contiguous) { + if (!accurateTimeOffset) { + // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS + nextAudioPts = inputSamples[0].pts; + } else { + // if timeOffset is accurate, let's use it as predicted next audio PTS + nextAudioPts = timeOffset * inputTimeScale; + } + } + + // 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. + + if (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; + + 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 + } // eslint-disable-line brace-style + + // 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_helper.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_helper.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 + firstPTS = _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_helper.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', + hasAudio: true, + hasVideo: false, + 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_helper.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 = void 0; + 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 = void 0; + 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 = void 0; + 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, + hasAudio: !!audioTrack, + hasVideo: !!videoTrack, + 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, ...) + * + */ + + + + + + + + + + + + + +// see https://stackoverflow.com/a/11237259/589493 +var demuxer_inline_global = Object(get_self_scope["a" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread +var performance = demuxer_inline_global; + +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(this.observer, this.config); + } + + var localthis = this; + // performance.now() not available on WebWorker, at least on Safari Desktop + var startTime = void 0; + try { + startTime = performance.now(); + } catch (error) { + startTime = Date.now(); + } + decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) { + var endTime = void 0; + 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, or track switch + // we might switch from content type (AAC container to TS container, or TS to fmp4 for example) + // so let's check that current demuxer is still valid + (discontinuity || trackSwitch) && !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: mp4demuxer["a" /* default */], remux: passthrough_remuxer }, { demux: aacdemuxer, remux: mp4_remuxer }, { demux: mp3demuxer, remux: mp4_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); + +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); + +// EXTERNAL MODULE: ./node_modules/url-toolkit/src/url-toolkit.js +var url_toolkit = __webpack_require__(5); +var url_toolkit_default = /*#__PURE__*/__webpack_require__.n(url_toolkit); + +// EXTERNAL MODULE: ./src/errors.js +var errors = __webpack_require__(2); + +// EXTERNAL MODULE: ./src/events.js +var events = __webpack_require__(1); + +// 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 FORBIDDEN_EVENT_NAMES = new Set(['hlsEventGeneric', 'hlsHandlerDestroying', 'hlsHandlerDestroyed']); + +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.onHandlerDestroying(); + this.unregisterListeners(); + this.onHandlerDestroyed(); + }; + + EventHandler.prototype.onHandlerDestroying = function onHandlerDestroying() {}; + + EventHandler.prototype.onHandlerDestroyed = function onHandlerDestroyed() {}; + + 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 (FORBIDDEN_EVENT_NAMES.has(event)) { + 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('An internal error happened while handling event ' + event + '. Error message: "' + err.message + '". Here is a stacktrace:', err); + 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); +// EXTERNAL MODULE: ./src/demux/mp4demuxer.js +var mp4demuxer = __webpack_require__(8); + +// CONCATENATED MODULE: ./src/loader/level-key.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 level_key__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + +var level_key_LevelKey = function () { + function LevelKey() { + level_key__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; +}(); + +/* harmony default export */ var level_key = (level_key_LevelKey); +// CONCATENATED MODULE: ./src/loader/fragment.js +var fragment__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 fragment__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + +var fragment_Fragment = function () { + function Fragment() { + var _elementaryStreams; + + fragment__classCallCheck(this, Fragment); + + this._url = null; + this._byteRange = null; + this._decryptdata = null; + this.tagList = []; + + // Holds the types of data this fragment supports + this._elementaryStreams = (_elementaryStreams = {}, _elementaryStreams[Fragment.ElementaryStreamTypes.AUDIO] = false, _elementaryStreams[Fragment.ElementaryStreamTypes.VIDEO] = false, _elementaryStreams); + } + + /** + * `type` property for this._elementaryStreams + * + * @enum + */ + + + /** + * @param {ElementaryStreamType} type + */ + Fragment.prototype.addElementaryStream = function addElementaryStream(type) { + this._elementaryStreams[type] = true; + }; + + /** + * @param {ElementaryStreamType} type + */ + + + Fragment.prototype.hasElementaryStream = function hasElementaryStream(type) { + return this._elementaryStreams[type] === true; + }; + + /** + * 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 level_key(); + decryptdata.method = levelkey.method; + decryptdata.baseuri = levelkey.baseuri; + decryptdata.reluri = levelkey.reluri; + decryptdata.iv = this.createInitializationVector(segmentNumber); + } + + return decryptdata; + }; + + fragment__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 && !this.rawByteRange) { + return []; + } + + if (this._byteRange) { + return this._byteRange; + } + + var byteRange = []; + if (this.rawByteRange) { + var params = this.rawByteRange.split('@', 2); + if (params.length === 1) { + var lastByteRangeEndOffset = this.lastByteRangeEndOffset; + byteRange[0] = lastByteRangeEndOffset || 0; + } else { + byteRange[0] = parseInt(params[1]); + } + byteRange[1] = parseInt(params[0]) + byteRange[0]; + this._byteRange = byteRange; + } + return byteRange; + } + + /** + * @type {number} + */ + + }, { + 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; + } + }, { + key: 'encrypted', + get: function get() { + return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null); + } + }], [{ + key: 'ElementaryStreamTypes', + get: function get() { + return { + AUDIO: 'audio', + VIDEO: 'video' + }; + } + }]); + + return Fragment; +}(); + +/* harmony default export */ var loader_fragment = (fragment_Fragment); +// 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+)$/; // eslint-disable-line no-useless-escape +var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape + +// 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 = void 0, + 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 window.MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs="' + codec + '"'); +} + + +// CONCATENATED MODULE: ./src/loader/m3u8-parser.js +function m3u8_parser__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + + + + + + + + + +/** + * M3U8 parser + * @module + */ + +// 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:<duration>,<title>), 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 MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i; + +var m3u8_parser_M3U8Parser = function () { + function M3U8Parser() { + m3u8_parser__classCallCheck(this, M3U8Parser); + } + + M3U8Parser.findGroup = 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; + }; + + M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) { + var result = void 0, + 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; + }; + + M3U8Parser.resolve = function resolve(url, baseUrl) { + return url_toolkit_default.a.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true }); + }; + + M3U8Parser.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 = M3U8Parser.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 = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec); + } + + levels.push(level); + } + return levels; + }; + + M3U8Parser.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 = M3U8Parser.resolve(attrs.URI, baseurl); + } + + media.lang = attrs.LANGUAGE; + if (!media.name) { + media.name = media.lang; + } + + if (audioGroups.length) { + var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId); + media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec; + } + media.id = id++; + medias.push(media); + } + } + return medias; + }; + + M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) { + var currentSN = 0, + totalduration = 0, + level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 }, + levelkey = new level_key(), + cc = 0, + prevFrag = null, + frag = new loader_fragment(), + result = void 0, + i = void 0; + + 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 || 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.urlId = levelUrlId; + frag.baseurl = baseurl; + // avoid sliced strings https://github.com/video-dev/hls.js/issues/939 + frag.relurl = (' ' + result[3]).slice(1); + + if (level.programDateTime) { + if (prevFrag) { + if (frag.rawProgramDateTime) { + // PDT discontinuity found + frag.pdt = Date.parse(frag.rawProgramDateTime); + } else { + // Contiguous fragment + frag.pdt = prevFrag.pdt + prevFrag.duration * 1000; + } + } else { + // First fragment + frag.pdt = Date.parse(level.programDateTime); + } + frag.endPdt = frag.pdt + frag.duration * 1000; + } + + level.fragments.push(frag); + prevFrag = frag; + totalduration += frag.duration; + + frag = new 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 level_key(); + if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].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 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; + + if (!level.initSegment && level.fragments.length) { + // this is a bit lurky but HLS really has no other way to tell us + // if the fragments are TS or MP4, except if we download them :/ + // but this is to be able to handle SIDX. + if (level.fragments.every(function (frag) { + return MP4_REGEX_SUFFIX.test(frag.relurl); + })) { + logger["b" /* logger */].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX'); + + frag = new loader_fragment(); + frag.relurl = level.fragments[0].relurl; + frag.baseurl = baseurl; + frag.level = id; + frag.type = type; + frag.sn = 'initSegment'; + + level.initSegment = frag; + level.needSidxRanges = true; + } + } + + return level; + }; + + return M3U8Parser; +}(); + +/* harmony default export */ var m3u8_parser = (m3u8_parser_M3U8Parser); +// CONCATENATED MODULE: ./src/loader/playlist-loader.js +var playlist_loader__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 playlist_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +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; } + +/** + * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models. + * + * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks. + * + * Uses loader(s) set in config to do actual internal loading of resource tasks. + * + * @module + * + */ + + + + + + + + + + +var _window = window, + performance = _window.performance; + +/** + * `type` property values for this loaders' context object + * @enum + * + */ + +var ContextType = { + MANIFEST: 'manifest', + LEVEL: 'level', + AUDIO_TRACK: 'audioTrack', + SUBTITLE_TRACK: 'subtitleTrack' +}; + +/** + * @enum {string} + */ +var LevelType = { + MAIN: 'main', + AUDIO: 'audio', + SUBTITLE: 'subtitle' +}; + +/** + * @constructor + */ + +var playlist_loader_PlaylistLoader = function (_EventHandler) { + _inherits(PlaylistLoader, _EventHandler); + + /** + * @constructs + * @param {Hls} hls + */ + 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; + } + + /** + * @param {ContextType} type + * @returns {boolean} + */ + PlaylistLoader.canHaveQualityLevels = function canHaveQualityLevels(type) { + return type !== ContextType.AUDIO_TRACK && type !== ContextType.SUBTITLE_TRACK; + }; + + /** + * Map context.type to LevelType + * @param {{type: ContextType}} context + * @returns {LevelType} + */ + + + PlaylistLoader.mapContextToLevelType = function mapContextToLevelType(context) { + var type = context.type; + + + switch (type) { + case ContextType.AUDIO_TRACK: + return LevelType.AUDIO; + case ContextType.SUBTITLE_TRACK: + return LevelType.SUBTITLE; + default: + return LevelType.MAIN; + } + }; + + PlaylistLoader.getResponseUrl = function getResponseUrl(response, context) { + var url = response.url; + // 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; + } + return url; + }; + + /** + * Returns defaults or configured loader-type overloads (pLoader and loader config params) + * Default loader is XHRLoader (see utils) + * @param {object} context + * @returns {XHRLoader} or other compatible configured overload + */ + + + PlaylistLoader.prototype.createInternalLoader = function createInternalLoader(context) { + var config = this.hls.config; + var PLoader = config.pLoader; + var Loader = config.loader; + var InternalLoader = PLoader || Loader; + + var loader = new InternalLoader(config); + + context.loader = loader; + this.loaders[context.type] = loader; + + return loader; + }; + + PlaylistLoader.prototype.getInternalLoader = function getInternalLoader(context) { + return this.loaders[context.type]; + }; + + PlaylistLoader.prototype.resetInternalLoader = function resetInternalLoader(contextType) { + if (this.loaders[contextType]) { + delete this.loaders[contextType]; + } + }; + + /** + * Call `destroy` on all internal loader instances mapped (one per context type) + */ + + + PlaylistLoader.prototype.destroyInternalLoaders = function destroyInternalLoaders() { + for (var contextType in this.loaders) { + var loader = this.loaders[contextType]; + if (loader) { + loader.destroy(); + } + + this.resetInternalLoader(contextType); + } + }; + + PlaylistLoader.prototype.destroy = function destroy() { + this.destroyInternalLoaders(); + + _EventHandler.prototype.destroy.call(this); + }; + + PlaylistLoader.prototype.onManifestLoading = function onManifestLoading(data) { + this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null }); + }; + + PlaylistLoader.prototype.onLevelLoading = function onLevelLoading(data) { + this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id }); + }; + + PlaylistLoader.prototype.onAudioTrackLoading = function onAudioTrackLoading(data) { + this.load(data.url, { type: ContextType.AUDIO_TRACK, level: 0, id: data.id }); + }; + + PlaylistLoader.prototype.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) { + this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: 0, id: data.id }); + }; + + PlaylistLoader.prototype.load = function load(url, context) { + var config = this.hls.config; + + logger["b" /* logger */].debug('Loading playlist of type ' + context.type + ', level: ' + context.level + ', id: ' + context.id); + + // Check if a loader for this context already exists + var loader = this.getInternalLoader(context); + if (loader) { + var loaderContext = loader.context; + if (loaderContext && loaderContext.url === url) { + // same URL can't overlap + logger["b" /* logger */].trace('playlist request ongoing'); + return false; + } else { + logger["b" /* logger */].warn('aborting previous loader for type: ' + context.type); + loader.abort(); + } + } + + var maxRetry = void 0, + timeout = void 0, + retryDelay = void 0, + maxRetryDelay = void 0; + + // apply different configs for retries depending on + // context (manifest, level, audio/subs playlist) + switch (context.type) { + case ContextType.MANIFEST: + maxRetry = config.manifestLoadingMaxRetry; + timeout = config.manifestLoadingTimeOut; + retryDelay = config.manifestLoadingRetryDelay; + maxRetryDelay = config.manifestLoadingMaxRetryTimeout; + break; + case ContextType.LEVEL: + // Disable internal loader retry logic, since we are managing retries in Level Controller + maxRetry = 0; + timeout = config.levelLoadingTimeOut; + // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config + break; + default: + maxRetry = config.levelLoadingMaxRetry; + timeout = config.levelLoadingTimeOut; + retryDelay = config.levelLoadingRetryDelay; + maxRetryDelay = config.levelLoadingMaxRetryTimeout; + break; + } + + loader = this.createInternalLoader(context); + + context.url = url; + context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this) + + var loaderConfig = { + timeout: timeout, + maxRetry: maxRetry, + retryDelay: retryDelay, + maxRetryDelay: maxRetryDelay + }; + + var loaderCallbacks = { + onSuccess: this.loadsuccess.bind(this), + onError: this.loaderror.bind(this), + onTimeout: this.loadtimeout.bind(this) + }; + + logger["b" /* logger */].debug('Calling internal loader delegate for URL: ' + url); + + loader.load(context, loaderConfig, loaderCallbacks); + + return true; + }; + + PlaylistLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) { + var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + + if (context.isSidxRequest) { + this._handleSidxRequest(response, context); + this._handlePlaylistLoaded(response, stats, context, networkDetails); + return; + } + + this.resetInternalLoader(context.type); + + var string = response.data; + + stats.tload = performance.now(); + // stats.mtime = new Date(target.getResponseHeader('Last-Modified')); + + // Validate if it is an M3U8 at all + if (string.indexOf('#EXTM3U') !== 0) { + this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails); + return; + } + + // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present) + if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) { + this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails); + } else { + this._handleMasterPlaylist(response, stats, context, networkDetails); + } + }; + + PlaylistLoader.prototype.loaderror = function loaderror(response, context) { + var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + this._handleNetworkError(context, networkDetails); + }; + + PlaylistLoader.prototype.loadtimeout = function loadtimeout(stats, context) { + var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + this._handleNetworkError(context, networkDetails, true); + }; + + PlaylistLoader.prototype._handleMasterPlaylist = function _handleMasterPlaylist(response, stats, context, networkDetails) { + var hls = this.hls; + var string = response.data; + + var url = PlaylistLoader.getResponseUrl(response, context); + + var levels = m3u8_parser.parseMasterPlaylist(string, url); + if (!levels.length) { + this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails); + return; + } + + // multi level playlist, parse level info + + var audioGroups = levels.map(function (level) { + return { + id: level.attrs.AUDIO, + codec: level.audioCodec + }; + }); + + var audioTracks = m3u8_parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups); + var subtitles = m3u8_parser.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 + }); + }; + + PlaylistLoader.prototype._handleTrackOrLevelPlaylist = function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) { + var hls = this.hls; + + var id = context.id, + level = context.level, + type = context.type; + + + var url = PlaylistLoader.getResponseUrl(response, context); + + var levelUrlId = isNaN(id) ? 0 : id; + var levelId = isNaN(level) ? levelUrlId : level; // level -> id -> 0 + var levelType = PlaylistLoader.mapContextToLevelType(context); + + var levelDetails = m3u8_parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId); + + // set stats on level structure + levelDetails.tload = stats.tload; + + // We have done our first request (Manifest-type) and receive + // not a master playlist but a chunk-list (track/level) + // We fire the manifest-loaded event anyway with the parsed level-details + // by creating a single-level structure for it. + if (type === ContextType.MANIFEST) { + var singleLevel = { + url: url, + details: levelDetails + }; + + hls.trigger(events["a" /* default */].MANIFEST_LOADED, { + levels: [singleLevel], + audioTracks: [], + url: url, + stats: stats, + networkDetails: networkDetails + }); + } + + // save parsing time + stats.tparsed = performance.now(); + + // in case we need SIDX ranges + // return early after calling load for + // the SIDX box. + if (levelDetails.needSidxRanges) { + var sidxUrl = levelDetails.initSegment.url; + this.load(sidxUrl, { + isSidxRequest: true, + type: type, + level: level, + levelDetails: levelDetails, + id: id, + rangeStart: 0, + rangeEnd: 2048, + responseType: 'arraybuffer' + }); + return; + } + + // extend the context with the new levelDetails property + context.levelDetails = levelDetails; + + this._handlePlaylistLoaded(response, stats, context, networkDetails); + }; + + PlaylistLoader.prototype._handleSidxRequest = function _handleSidxRequest(response, context) { + var sidxInfo = mp4demuxer["a" /* default */].parseSegmentIndex(new Uint8Array(response.data)); + sidxInfo.references.forEach(function (segmentRef, index) { + var segRefInfo = segmentRef.info; + var frag = context.levelDetails.fragments[index]; + + if (frag.byteRange.length === 0) { + frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start); + } + }); + + context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0'; + }; + + PlaylistLoader.prototype._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) { + this.hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].NETWORK_ERROR, + details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, + fatal: true, + url: response.url, + reason: reason, + networkDetails: networkDetails + }); + }; + + PlaylistLoader.prototype._handleNetworkError = function _handleNetworkError(context, networkDetails) { + var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + logger["b" /* logger */].info('A network error occured while loading a ' + context.type + '-type playlist'); + + var details = void 0; + var fatal = void 0; + + var loader = this.getInternalLoader(context); + + switch (context.type) { + case ContextType.MANIFEST: + details = timeout ? errors["a" /* ErrorDetails */].MANIFEST_LOAD_TIMEOUT : errors["a" /* ErrorDetails */].MANIFEST_LOAD_ERROR; + fatal = true; + break; + case ContextType.LEVEL: + details = timeout ? errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT : errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR; + fatal = false; + break; + case ContextType.AUDIO_TRACK: + details = timeout ? errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT : errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR; + fatal = false; + break; + default: + // details = ...? + fatal = false; + } + + if (loader) { + loader.abort(); + this.resetInternalLoader(context.type); + } + + 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 + }); + }; + + PlaylistLoader.prototype._handlePlaylistLoaded = function _handlePlaylistLoaded(response, stats, context, networkDetails) { + var type = context.type, + level = context.level, + id = context.id, + levelDetails = context.levelDetails; + + + if (!levelDetails.targetduration) { + this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails); + return; + } + + var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type); + if (canHaveLevels) { + this.hls.trigger(events["a" /* default */].LEVEL_LOADED, { + details: levelDetails, + level: level || 0, + id: id || 0, + stats: stats, + networkDetails: networkDetails + }); + } else { + switch (type) { + case ContextType.AUDIO_TRACK: + this.hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADED, { + details: levelDetails, + id: id, + stats: stats, + networkDetails: networkDetails + }); + break; + case ContextType.SUBTITLE_TRACK: + this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADED, { + details: levelDetails, + id: id, + stats: stats, + networkDetails: networkDetails + }); + break; + } + } + }; + + playlist_loader__createClass(PlaylistLoader, null, [{ + key: 'ContextType', + get: function get() { + return ContextType; + } + }, { + key: 'LevelType', + get: function get() { + return LevelType; + } + }]); + + 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 = {}; + + _EventHandler.prototype.destroy.call(this); + }; + + FragmentLoader.prototype.onFragLoading = function onFragLoading(data) { + var frag = data.frag, + type = frag.type, + loaders = this.loaders, + config = this.hls.config, + FragmentILoader = config.fLoader, + DefaultILoader = config.loader; + + // reset fragment state + frag.loaded = 0; + + var loader = loaders[type]; + if (loader) { + logger["b" /* logger */].warn('abort previous fragment loader for type: ' + type); + loader.abort(); + } + + loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(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/controller/fragment-tracker.js +function fragment_tracker__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function fragment_tracker__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_tracker__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; } + + + + +var FragmentState = { + NOT_LOADED: 'NOT_LOADED', + APPENDING: 'APPENDING', + PARTIAL: 'PARTIAL', + OK: 'OK' +}; + +var fragment_tracker_FragmentTracker = function (_EventHandler) { + fragment_tracker__inherits(FragmentTracker, _EventHandler); + + function FragmentTracker(hls) { + fragment_tracker__classCallCheck(this, FragmentTracker); + + var _this = fragment_tracker__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].FRAG_BUFFERED, events["a" /* default */].FRAG_LOADED)); + + _this.bufferPadding = 0.2; + + _this.fragments = Object.create(null); + _this.timeRanges = Object.create(null); + + _this.config = hls.config; + return _this; + } + + FragmentTracker.prototype.destroy = function destroy() { + this.fragments = null; + this.timeRanges = null; + this.config = null; + event_handler.prototype.destroy.call(this); + _EventHandler.prototype.destroy.call(this); + }; + + /** + * Return a Fragment that match the position and levelType. + * If not found any Fragment, return null + * @param {number} position + * @param {LevelType} levelType + * @returns {Fragment|null} + */ + + + FragmentTracker.prototype.getBufferedFrag = function getBufferedFrag(position, levelType) { + var fragments = this.fragments; + var bufferedFrags = Object.keys(fragments).filter(function (key) { + var fragmentEntity = fragments[key]; + if (fragmentEntity.body.type !== levelType) { + return false; + } + + if (!fragmentEntity.buffered) { + return false; + } + + var frag = fragmentEntity.body; + return frag.startPTS <= position && position <= frag.endPTS; + }); + if (bufferedFrags.length === 0) { + return null; + } else { + // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566 + var bufferedFragKey = bufferedFrags.pop(); + return fragments[bufferedFragKey].body; + } + }; + + /** + * Partial fragments effected by coded frame eviction will be removed + * The browser will unload parts of the buffer to free up memory for new buffer data + * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable) + * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio) + * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer + */ + + + FragmentTracker.prototype.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) { + var _this2 = this; + + var fragmentTimes = void 0, + time = void 0; + // Check if any flagged fragments have been unloaded + Object.keys(this.fragments).forEach(function (key) { + var fragmentEntity = _this2.fragments[key]; + if (fragmentEntity.buffered === true) { + var esData = fragmentEntity.range[elementaryStream]; + if (esData) { + fragmentTimes = esData.time; + for (var i = 0; i < fragmentTimes.length; i++) { + time = fragmentTimes[i]; + + if (_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) { + // Unregister partial fragment as it needs to load again to be reused + _this2.removeFragment(fragmentEntity.body); + break; + } + } + } + } + }); + }; + + /** + * Checks if the fragment passed in is loaded in the buffer properly + * Partially loaded fragments will be registered as a partial fragment + * @param {Object} fragment Check the fragment against all sourceBuffers loaded + */ + + + FragmentTracker.prototype.detectPartialFragments = function detectPartialFragments(fragment) { + var _this3 = this; + + var fragKey = this.getFragmentKey(fragment); + var fragmentEntity = this.fragments[fragKey]; + if (fragmentEntity) { + fragmentEntity.buffered = true; + + Object.keys(this.timeRanges).forEach(function (elementaryStream) { + if (fragment.hasElementaryStream(elementaryStream) === true) { + var timeRange = _this3.timeRanges[elementaryStream]; + // Check for malformed fragments + // Gaps need to be calculated for each elementaryStream + fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange); + } + }); + } + }; + + FragmentTracker.prototype.getBufferedTimes = function getBufferedTimes(startPTS, endPTS, timeRange) { + var fragmentTimes = []; + var startTime = void 0, + endTime = void 0; + var fragmentPartial = false; + for (var i = 0; i < timeRange.length; i++) { + startTime = timeRange.start(i) - this.bufferPadding; + endTime = timeRange.end(i) + this.bufferPadding; + if (startPTS >= startTime && endPTS <= endTime) { + // Fragment is entirely contained in buffer + // No need to check the other timeRange times since it's completely playable + fragmentTimes.push({ + startPTS: Math.max(startPTS, timeRange.start(i)), + endPTS: Math.min(endPTS, timeRange.end(i)) + }); + break; + } else if (startPTS < endTime && endPTS > startTime) { + // Check for intersection with buffer + // Get playable sections of the fragment + fragmentTimes.push({ + startPTS: Math.max(startPTS, timeRange.start(i)), + endPTS: Math.min(endPTS, timeRange.end(i)) + }); + fragmentPartial = true; + } else if (endPTS <= startTime) { + // No need to check the rest of the timeRange as it is in order + break; + } + } + + return { + time: fragmentTimes, + partial: fragmentPartial + }; + }; + + FragmentTracker.prototype.getFragmentKey = function getFragmentKey(fragment) { + return fragment.type + '_' + fragment.level + '_' + fragment.urlId + '_' + fragment.sn; + }; + + /** + * Gets the partial fragment for a certain time + * @param {Number} time + * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment + */ + + + FragmentTracker.prototype.getPartialFragment = function getPartialFragment(time) { + var _this4 = this; + + var timePadding = void 0, + startTime = void 0, + endTime = void 0; + var bestFragment = null; + var bestOverlap = 0; + Object.keys(this.fragments).forEach(function (key) { + var fragmentEntity = _this4.fragments[key]; + if (_this4.isPartial(fragmentEntity)) { + startTime = fragmentEntity.body.startPTS - _this4.bufferPadding; + endTime = fragmentEntity.body.endPTS + _this4.bufferPadding; + if (time >= startTime && time <= endTime) { + // Use the fragment that has the most padding from start and end time + timePadding = Math.min(time - startTime, endTime - time); + if (bestOverlap <= timePadding) { + bestFragment = fragmentEntity.body; + bestOverlap = timePadding; + } + } + } + }); + return bestFragment; + }; + + /** + * @param {Object} fragment The fragment to check + * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded + */ + + + FragmentTracker.prototype.getState = function getState(fragment) { + var fragKey = this.getFragmentKey(fragment); + var fragmentEntity = this.fragments[fragKey]; + var state = FragmentState.NOT_LOADED; + + if (fragmentEntity !== undefined) { + if (!fragmentEntity.buffered) { + state = FragmentState.APPENDING; + } else if (this.isPartial(fragmentEntity) === true) { + state = FragmentState.PARTIAL; + } else { + state = FragmentState.OK; + } + } + + return state; + }; + + FragmentTracker.prototype.isPartial = function isPartial(fragmentEntity) { + return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true); + }; + + FragmentTracker.prototype.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) { + var startTime = void 0, + endTime = void 0; + for (var i = 0; i < timeRange.length; i++) { + startTime = timeRange.start(i) - this.bufferPadding; + endTime = timeRange.end(i) + this.bufferPadding; + if (startPTS >= startTime && endPTS <= endTime) { + return true; + } + + if (endPTS <= startTime) { + // No need to check the rest of the timeRange as it is in order + return false; + } + } + + return false; + }; + + /** + * Fires when a fragment loading is completed + */ + + + FragmentTracker.prototype.onFragLoaded = function onFragLoaded(e) { + var fragment = e.frag; + // don't track initsegment (for which sn is not a number) + // don't track frags used for bitrateTest, they're irrelevant. + if (!isNaN(fragment.sn) && !fragment.bitrateTest) { + var fragKey = this.getFragmentKey(fragment); + var fragmentEntity = { + body: fragment, + range: Object.create(null), + buffered: false + }; + this.fragments[fragKey] = fragmentEntity; + } + }; + + /** + * Fires when the buffer is updated + */ + + + FragmentTracker.prototype.onBufferAppended = function onBufferAppended(e) { + var _this5 = this; + + // Store the latest timeRanges loaded in the buffer + this.timeRanges = e.timeRanges; + Object.keys(this.timeRanges).forEach(function (elementaryStream) { + var timeRange = _this5.timeRanges[elementaryStream]; + _this5.detectEvictedFragments(elementaryStream, timeRange); + }); + }; + + /** + * Fires after a fragment has been loaded into the source buffer + */ + + + FragmentTracker.prototype.onFragBuffered = function onFragBuffered(e) { + this.detectPartialFragments(e.frag); + }; + + /** + * Return true if fragment tracker has the fragment. + * @param {Object} fragment + * @returns {boolean} + */ + + + FragmentTracker.prototype.hasFragment = function hasFragment(fragment) { + var fragKey = this.getFragmentKey(fragment); + return this.fragments[fragKey] !== undefined; + }; + + /** + * Remove a fragment from fragment tracker until it is loaded again + * @param {Object} fragment The fragment to remove + */ + + + FragmentTracker.prototype.removeFragment = function removeFragment(fragment) { + var fragKey = this.getFragmentKey(fragment); + delete this.fragments[fragKey]; + }; + + /** + * Remove all fragments from fragment tracker. + */ + + + FragmentTracker.prototype.removeAllFragments = function removeAllFragments() { + this.fragments = Object.create(null); + }; + + return FragmentTracker; +}(event_handler); +// 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/utils/buffer-helper.js +function buffer_helper__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @module BufferHelper + * + * Providing methods dealing with buffer length retrieval for example. + * + * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property. + * + * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered +*/ + +var BufferHelper = function () { + function BufferHelper() { + buffer_helper__classCallCheck(this, BufferHelper); + } + + /** + * Return true if `media`'s buffered include `position` + * @param {HTMLMediaElement|SourceBuffer} media + * @param {number} position + * @returns {boolean} + */ + BufferHelper.isBuffered = function isBuffered(media, position) { + try { + 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; + } + } + } + } catch (error) { + // this is to catch + // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': + // This SourceBuffer has been removed from the parent media source + } + return false; + }; + + BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) { + try { + if (media) { + var vbuffered = media.buffered, + buffered = [], + i = void 0; + for (i = 0; i < vbuffered.length; i++) { + buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) }); + } + + return this.bufferedInfo(buffered, pos, maxHoleDuration); + } + } catch (error) { + // this is to catch + // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': + // This SourceBuffer has been removed from the parent media source + } + return { len: 0, start: pos, end: pos, nextStart: undefined }; + }; + + BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) { + var buffered2 = [], + + // bufferStart and bufferEnd are buffer boundaries around current video position + bufferLen = void 0, + bufferStart = void 0, + bufferEnd = void 0, + bufferStartNext = void 0, + i = void 0; + // 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 }; + }; + + return BufferHelper; +}(); +// EXTERNAL MODULE: ./node_modules/events/events.js +var events_events = __webpack_require__(6); +var events_default = /*#__PURE__*/__webpack_require__.n(events_events); + +// EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js +var webworkify_webpack = __webpack_require__(11); +var webworkify_webpack_default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack); + +// EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 15 modules +var demuxer_inline = __webpack_require__(9); + +// CONCATENATED MODULE: ./src/utils/mediasource-helper.js +/** + * MediaSource helper + */ + +function getMediaSource() { + if (typeof window !== 'undefined') { + return window.MediaSource || window.WebKitMediaSource; + } +} +// EXTERNAL MODULE: ./src/utils/get-self-scope.js +var get_self_scope = __webpack_require__(4); + +// 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"); } } + + + + + + + + + + + +// see https://stackoverflow.com/a/11237259/589493 +var global = Object(get_self_scope["a" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread +var 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: MediaSource.isTypeSupported('video/mp4'), + mpeg: MediaSource.isTypeSupported('audio/mpeg'), + mp3: 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*/(12)); + 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 + global.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; + switch (data.event) { + case 'init': + // revoke the Object URL that was used to create demuxer worker, so as not to leak it + global.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/controller/level-helper.js +/** + * @module LevelHelper + * + * Providing methods dealing with playlist sliding and drift + * + * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner. + * + * */ + + + +function addGroupId(level, type, id) { + switch (type) { + case 'audio': + if (!level.audioGroupIds) { + level.audioGroupIds = []; + } + level.audioGroupIds.push(id); + break; + case 'text': + if (!level.textGroupIds) { + level.textGroupIds = []; + } + level.textGroupIds.push(id); + break; + } +} + +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 = void 0, + fragments = void 0, + i = void 0; + 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 = void 0; + + // potentially retrieve cached initsegment + if (newDetails.initSegment && oldDetails.initSegment) { + newDetails.initSegment = oldDetails.initSegment; + } + + // 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/time-ranges.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 time_ranges = (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 && lastLevel.details.fragments && lastLevel.details.fragments.length) { + // 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/task-loop.js +function task_loop__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function task_loop__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 task_loop__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; } + + + +/** + * Sub-class specialization of EventHandler base class. + * + * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop, + * scheduled asynchroneously, avoiding recursive calls in the same tick. + * + * The task itself is implemented in `doTick`. It can be requested and called for single execution + * using the `tick` method. + * + * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick", + * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly. + * + * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`, + * and cancelled with `clearNextTick`. + * + * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`). + * + * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine. + * + * Further explanations: + * + * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously + * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks. + * + * When the task execution (`tick` method) is called in re-entrant way this is detected and + * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further + * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo). + */ + +var TaskLoop = function (_EventHandler) { + task_loop__inherits(TaskLoop, _EventHandler); + + function TaskLoop(hls) { + task_loop__classCallCheck(this, TaskLoop); + + for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + events[_key - 1] = arguments[_key]; + } + + var _this = task_loop__possibleConstructorReturn(this, _EventHandler.call.apply(_EventHandler, [this, hls].concat(events))); + + _this._tickInterval = null; + _this._tickTimer = null; + _this._tickCallCount = 0; + _this._boundTick = _this.tick.bind(_this); + return _this; + } + + /** + * @override + */ + + + TaskLoop.prototype.onHandlerDestroying = function onHandlerDestroying() { + // clear all timers before unregistering from event bus + this.clearNextTick(); + this.clearInterval(); + }; + + /** + * @returns {boolean} + */ + + + TaskLoop.prototype.hasInterval = function hasInterval() { + return !!this._tickInterval; + }; + + /** + * @returns {boolean} + */ + + + TaskLoop.prototype.hasNextTick = function hasNextTick() { + return !!this._tickTimer; + }; + + /** + * @param {number} millis Interval time (ms) + * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect) + */ + + + TaskLoop.prototype.setInterval = function (_setInterval) { + function setInterval(_x) { + return _setInterval.apply(this, arguments); + } + + setInterval.toString = function () { + return _setInterval.toString(); + }; + + return setInterval; + }(function (millis) { + if (!this._tickInterval) { + this._tickInterval = setInterval(this._boundTick, millis); + return true; + } + return false; + }); + + /** + * @returns {boolean} True when interval was cleared, false when none was set (no effect) + */ + + + TaskLoop.prototype.clearInterval = function (_clearInterval) { + function clearInterval() { + return _clearInterval.apply(this, arguments); + } + + clearInterval.toString = function () { + return _clearInterval.toString(); + }; + + return clearInterval; + }(function () { + if (this._tickInterval) { + clearInterval(this._tickInterval); + this._tickInterval = null; + return true; + } + return false; + }); + + /** + * @returns {boolean} True when timeout was cleared, false when none was set (no effect) + */ + + + TaskLoop.prototype.clearNextTick = function clearNextTick() { + if (this._tickTimer) { + clearTimeout(this._tickTimer); + this._tickTimer = null; + return true; + } + return false; + }; + + /** + * Will call the subclass doTick implementation in this main loop tick + * or in the next one (via setTimeout(,0)) in case it has already been called + * in this tick (in case this is a re-entrant call). + */ + + + TaskLoop.prototype.tick = function tick() { + this._tickCallCount++; + if (this._tickCallCount === 1) { + this.doTick(); + // re-entrant call to tick from previous doTick call stack + // -> schedule a call on the next main loop iteration to process this task processing request + if (this._tickCallCount > 1) { + // make sure only one timer exists at any time at max + this.clearNextTick(); + this._tickTimer = setTimeout(this._boundTick, 0); + } + this._tickCallCount = 0; + } + }; + + /** + * For subclass to implement task logic + * @abstract + */ + + + TaskLoop.prototype.doTick = function doTick() {}; + + return TaskLoop; +}(event_handler); + +/* harmony default export */ var task_loop = (TaskLoop); +// CONCATENATED MODULE: ./src/controller/fragment-finders.js + + +/** + * Calculates the PDT of the next load position. + * bufferEnd in this function is usually the position of the playhead. + * @param {number} [start = 0] - The PTS of the first fragment within the level + * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within + * @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level + * @returns {number} nextPdt - The computed PDT + */ +function calculateNextPDT() { + var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var bufferEnd = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var levelDetails = arguments[2]; + + var pdt = 0; + if (levelDetails.programDateTime) { + var parsedDateInt = Date.parse(levelDetails.programDateTime); + if (!isNaN(parsedDateInt)) { + pdt = bufferEnd * 1000 + parsedDateInt - 1000 * start; + } + } + return pdt; +} + +/** + * Finds the first fragment whose endPDT value exceeds the given PDT. + * @param {Array<Fragment>} fragments - The array of candidate fragments + * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded + * @returns {*|null} fragment - The best matching fragment + */ +function findFragmentByPDT(fragments) { + var PDTValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + + if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) { + return null; + } + + // if less than start + var firstSegment = fragments[0]; + + if (PDTValue < firstSegment.pdt) { + return null; + } + + var lastSegment = fragments[fragments.length - 1]; + + if (PDTValue >= lastSegment.endPdt) { + return null; + } + + for (var seg = 0; seg < fragments.length; ++seg) { + var frag = fragments[seg]; + if (PDTValue < frag.endPdt) { + return frag; + } + } + return null; +} + +/** + * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer. + * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus + * breaking any traps which would cause the same fragment to be continuously selected within a small range. + * @param {*} fragPrevious - The last frag successfully appended + * @param {Array<Fragment>} fragments - The array of candidate fragments + * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within + * @param {number} [end = 0] - The computed end time of the stream + * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous + * @returns {*} foundFrag - The best matching fragment + */ +function findFragmentBySN(fragPrevious, fragments) { + var bufferEnd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var maxFragLookUpTolerance = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + + var foundFrag = void 0; + var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null; + if (bufferEnd < end) { + if (bufferEnd > end - maxFragLookUpTolerance) { + maxFragLookUpTolerance = 0; + } + + // Prefer the next fragment if it's within tolerance + if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) { + foundFrag = fragNext; + } else { + foundFrag = binary_search.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance)); + } + } + return foundFrag; +} + +/** + * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions. + * @param {*} candidate - The fragment to test + * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within + * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous + * @returns {number} - 0 if it matches, 1 if too low, -1 if too high + */ +function fragmentWithinToleranceTest() { + var bufferEnd = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var maxFragLookUpTolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var candidate = arguments[2]; + + // 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; + } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) { + // if maxFragLookUpTolerance will have negative value then don't return -1 for first element + return -1; + } + + return 0; +} +// 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 (_TaskLoop) { + stream_controller__inherits(StreamController, _TaskLoop); + + function StreamController(hls, fragmentTracker) { + stream_controller__classCallCheck(this, StreamController); + + var _this = stream_controller__possibleConstructorReturn(this, _TaskLoop.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.fragmentTracker = fragmentTracker; + _this.config = hls.config; + _this.audioCodecSwap = false; + _this._state = State.STOPPED; + _this.stallReported = false; + return _this; + } + + StreamController.prototype.onHandlerDestroying = function onHandlerDestroying() { + this.stopLoad(); + _TaskLoop.prototype.onHandlerDestroying.call(this); + }; + + StreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() { + this.state = State.STOPPED; + this.fragmentTracker = null; + _TaskLoop.prototype.onHandlerDestroyed.call(this); + }; + + StreamController.prototype.startLoad = function startLoad(startPosition) { + if (this.levels) { + var lastCurrentTime = this.lastCurrentTime, + hls = this.hls; + this.stopLoad(); + this.setInterval(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.fragmentTracker.removeFragment(frag); + this.fragCurrent = null; + } + this.fragPrevious = null; + if (this.demuxer) { + this.demuxer.destroy(); + this.demuxer = null; + } + this.clearInterval(); + this.state = State.STOPPED; + this.forceStartLoad = false; + }; + + StreamController.prototype.doTick = function doTick() { + switch (this.state) { + 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 = window.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 = BufferHelper.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 (!levelDetails || 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) { + if (frag.encrypted) { + logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level); + this._loadKey(frag); + } else { + logger["b" /* logger */].log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3)); + this._loadFragment(frag); + } + } + }; + + 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) { + if (!levelDetails.programDateTime) { + // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE) + 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); + } + } + } else { + // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE) + frag = findFragmentByPDT(fragments, fragPrevious.endPdt + 1); + } + } + 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 fragBySN = function fragBySN() { + return findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance); + }; + var frag = void 0; + var foundFrag = void 0; + + if (bufferEnd < end) { + if (!levelDetails.programDateTime) { + // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE) + foundFrag = findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance); + } else { + // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE) + foundFrag = findFragmentByPDT(fragments, calculateNextPDT(start, bufferEnd, levelDetails)); + if (!foundFrag || fragmentWithinToleranceTest(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) { + // Fall back to SN order if finding by PDT returns a frag which won't fit within the stream + // fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise + logger["b" /* logger */].warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN'); + foundFrag = fragBySN(); + } + } + } 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'); + } 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) { + frag = prevFrag; + frag.backtracked = true; + } else if (curSNIdx) { + // can't backtrack on very first fragment + frag = null; + } + } + } + } + } + return frag; + }; + + StreamController.prototype._loadKey = function _loadKey(frag) { + this.state = State.KEY_LOADING; + this.hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag }); + }; + + StreamController.prototype._loadFragment = function _loadFragment(frag) { + // Check if fragment is not loaded + var fragState = this.fragmentTracker.getState(frag); + + 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; + } + + // Allow backtracked fragments to load + if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) { + frag.autoLevel = this.hls.autoLevelEnabled; + frag.bitrateTest = this.bitrateTest; + + this.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(this.hls, 'main'); + } + + this.state = State.FRAG_LOADING; + } else if (fragState === FragmentState.APPENDING) { + // Lower the buffer size and try again + if (this._reduceMaxBufferLength(frag.duration)) { + this.fragmentTracker.removeFragment(frag); + } + } + }; + + StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) { + return this.fragmentTracker.getBufferedFrag(position, playlist_loader.LevelType.MAIN); + }; + + 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 = void 0, + currentTime = void 0, + 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 > this.lastCurrentTime) { + this.lastCurrentTime = currentTime; + } + + if (BufferHelper.isBuffered(video, currentTime)) { + fragPlayingCurrent = this.getBufferedFrag(currentTime); + } else if (BufferHelper.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; + // 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 (BufferHelper.isBuffered(media, media.currentTime)) { + // only nudge if currentTime is buffered + media.currentTime -= 0.0001; + } + if (!this.previouslyPaused) { + media.play(); + } + } + }; + + /** + * 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 + */ + + + StreamController.prototype.nextLevelSwitch = function nextLevelSwitch() { + 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; + 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 backtracked flag + var levels = this.levels; + if (levels) { + levels.forEach(function (level) { + if (level.details) { + level.details.fragments.forEach(function (fragment) { + 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 = BufferHelper.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; + } + + // 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.fragmentTracker.removeAllFragments(); + this.stalled = false; + this.startPosition = this.lastCurrentTime = 0; + }; + + StreamController.prototype.onManifestParsed = function onManifestParsed(data) { + var aac = false, + heaac = false, + codec = void 0; + 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; + var currentLevel = this.levels[fragCurrent.level]; + var 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 = window.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 = window.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 = void 0, + track = void 0; + + // 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; + } + + if (data.hasAudio === true) { + frag.addElementaryStream(loader_fragment.ElementaryStreamTypes.AUDIO); + } + + if (data.hasVideo === true) { + frag.addElementaryStream(loader_fragment.ElementaryStreamTypes.VIDEO); + } + + 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', frag.sn); + } else { + logger["b" /* logger */].warn('missing video frame(s), backtracking fragment', frag.sn); + // 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 + this.fragmentTracker.removeFragment(frag); + 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', frag.sn); + } + } 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 = window.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 : ' + time_ranges.toString(media.buffered)); + this.fragPrevious = frag; + var stats = this.stats; + stats.tbuffered = window.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 && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.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); + logger["b" /* logger */].warn('mediaController: frag loading failed, retry in ' + delay + ' ms'); + this.retryDate = window.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 */].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'); + return true; + } + return false; + }; + + /** + * Checks the health of the buffer and attempts to resolve playback stalls. + * @private + */ + + + StreamController.prototype._checkBuffer = function _checkBuffer() { + var config = this.config, + media = this.media; + + var stallDebounceInterval = 1000; + if (!media || media.readyState === 0) { + // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0) + return; + } + + var currentTime = media.currentTime; + var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media; + var buffered = mediaBuffer.buffered; + + if (!this.loadedmetadata && buffered.length) { + this.loadedmetadata = true; + this._seekToStartPos(); + } else if (this.immediateSwitch) { + this.immediateLevelSwitchEnd(); + } else { + var expectedPlaying = !(media.paused && media.readyState > 1 || // not playing when media is paused and sufficiently buffered + media.ended || // not playing when media is ended + media.buffered.length === 0); // not playing if nothing buffered + var tnow = window.performance.now(); + + if (currentTime !== this.lastCurrentTime) { + // The playhead is now moving, but was previously stalled + if (this.stallReported) { + logger["b" /* logger */].warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(tnow - this.stalled) + 'ms'); + this.stallReported = false; + } + this.stalled = null; + this.nudgeRetry = 0; + } else if (expectedPlaying) { + // The playhead isn't moving but it should be + // Allow some slack time to for small stalls to resolve themselves + var stalledDuration = tnow - this.stalled; + var bufferInfo = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole); + if (!this.stalled) { + this.stalled = tnow; + return; + } else if (stalledDuration >= stallDebounceInterval) { + // Report stalling after trying to fix + this._reportStall(bufferInfo.len); + } + + this._tryFixBufferStall(bufferInfo, stalledDuration); + } + } + }; + + 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; + if (media) { + // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams + this.fragmentTracker.detectEvictedFragments(loader_fragment.ElementaryStreamTypes.VIDEO, media.buffered); + } + // 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); + }; + + /** + * Detects and attempts to fix known buffer stalling issues. + * @param bufferInfo - The properties of the current buffer. + * @param stalledDuration - The amount of time Hls.js has been stalling for. + * @private + */ + + + StreamController.prototype._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDuration) { + var config = this.config, + media = this.media; + + var currentTime = media.currentTime; + var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end + + var partial = this.fragmentTracker.getPartialFragment(currentTime); + if (partial) { + // Try to skip over the buffer hole caused by a partial fragment + // This method isn't limited by the size of the gap between buffered ranges + this._trySkipBufferHole(partial); + } + + if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) { + // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds + // We only try to jump the hole if it's under the configured size + // Reset stalled so to rearm watchdog timer + this.stalled = null; + this._tryNudgeBuffer(); + } + }; + + /** + * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period. + * @param bufferLen - The playhead distance from the end of the current buffer segment. + * @private + */ + + + StreamController.prototype._reportStall = function _reportStall(bufferLen) { + var hls = this.hls, + media = this.media, + stallReported = this.stallReported; + + if (!stallReported) { + // Report stalled error once + this.stallReported = true; + logger["b" /* logger */].warn('Playback stalling at @' + media.currentTime + ' due to low buffer'); + hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].MEDIA_ERROR, + details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, + fatal: false, + buffer: bufferLen + }); + } + }; + + /** + * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments + * @param partial - The partial fragment found at the current time (where playback is stalling). + * @private + */ + + + StreamController.prototype._trySkipBufferHole = function _trySkipBufferHole(partial) { + var hls = this.hls, + media = this.media; + + var currentTime = media.currentTime; + var lastEndTime = 0; + // Check if currentTime is between unbuffered regions of partial fragments + for (var i = 0; i < media.buffered.length; i++) { + var startTime = media.buffered.start(i); + if (currentTime >= lastEndTime && currentTime < startTime) { + media.currentTime = Math.max(startTime, media.currentTime + 0.1); + logger["b" /* logger */].warn('skipping hole, adjusting currentTime from ' + currentTime + ' to ' + media.currentTime); + this.stalled = null; + hls.trigger(events["a" /* default */].ERROR, { + type: errors["b" /* ErrorTypes */].MEDIA_ERROR, + details: errors["a" /* ErrorDetails */].BUFFER_SEEK_OVER_HOLE, + fatal: false, + reason: 'fragment loaded with buffer holes, seeking from ' + currentTime + ' to ' + media.currentTime, + frag: partial + }); + return; + } + lastEndTime = media.buffered.end(i); + } + }; + + /** + * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount. + * @private + */ + + + StreamController.prototype._tryNudgeBuffer = function _tryNudgeBuffer() { + var config = this.config, + hls = this.hls, + media = this.media; + + var currentTime = media.currentTime; + var nudgeRetry = (this.nudgeRetry || 0) + 1; + this.nudgeRetry = nudgeRetry; + + if (nudgeRetry < config.nudgeMaxRetry) { + 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 + }); + } + }; + + /** + * Seeks to the set startPosition if not equal to the mediaElement's current time. + * @private + */ + + + StreamController.prototype._seekToStartPos = function _seekToStartPos() { + var media = this.media; + + var currentTime = media.currentTime; + // 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; + // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered + if (currentTime !== startPosition) { + // if startPosition not buffered, let's seek to buffered.start(0) + logger["b" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition + ' from current time ' + currentTime + ' '); + media.currentTime = startPosition; + } + }; + + 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; +}(task_loop); + +/* harmony default export */ var stream_controller = (stream_controller_StreamController); +// CONCATENATED MODULE: ./src/controller/level-controller.js +var level_controller__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; }; + +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__window = window, + level_controller_performance = level_controller__window.performance; + +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 */].AUDIO_TRACK_SWITCHED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].ERROR)); + + _this.canload = false; + _this.currentLevelIndex = null; + _this.manualLevelIndex = -1; + _this.timer = null; + return _this; + } + + LevelController.prototype.onHandlerDestroying = function onHandlerDestroying() { + this.clearTimer(); + this.manualLevelIndex = -1; + }; + + LevelController.prototype.clearTimer = function clearTimer() { + 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 !== null) { + this.loadLevel(); + } + }; + + 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 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) { + level.audioCodec = undefined; + } + + levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here + + if (!levelFromSet) { + level.url = [level.url]; + level.urlId = 0; + levelSet[level.bitrate] = level; + levels.push(level); + } else { + levelFromSet.url.push(level.url); + } + + if (level.attrs && level.attrs.AUDIO) { + addGroupId(levelFromSet || level, 'audio', level.attrs.AUDIO); + } + + if (level.attrs && level.attrs.SUBTITLES) { + addGroupId(levelFromSet || level, 'text', level.attrs.SUBTITLES); + } + }); + + // remove audio-only level if we also have levels with audio+video codecs signalled + if (videoCodecFound && audioCodecFound) { + 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 > 0) { + // 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 && videoCodecFound + }); + } 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.clearTimer(); + if (this.currentLevelIndex !== newLevel) { + logger["b" /* logger */].log('switching to level ' + newLevel); + this.currentLevelIndex = newLevel; + var levelProperties = levels[newLevel]; + levelProperties.level = newLevel; + hls.trigger(events["a" /* default */].LEVEL_SWITCHING, levelProperties); + } + var level = levels[newLevel]; + var levelDetails = level.details; + + // check if we need to load playlist for this level + if (!levelDetails || levelDetails.live) { + // 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) { + if (data.fatal) { + if (data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) { + this.clearTimer(); + } + + return; + } + + var levelError = false, + fragmentError = false; + var levelIndex = void 0; + + // try to recover not fatal errors + 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: + 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; + levelError = true; + break; + } + + if (levelIndex !== undefined) { + this.recoverLevel(data, levelIndex, levelError, fragmentError); + } + }; + + /** + * Switch to a redundant stream if any available. + * If redundant stream is not available, emergency switch down if ABR mode is enabled. + * + * @param {Object} errorEvent + * @param {Number} levelIndex current level index + * @param {Boolean} levelError + * @param {Boolean} fragmentError + */ + // FIXME Find a better abstraction where fragment/level retry management is well decoupled + + + LevelController.prototype.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) { + var _this2 = this; + + var config = this.hls.config; + var errorDetails = errorEvent.details; + + var level = this._levels[levelIndex]; + var redundantLevels = void 0, + delay = void 0, + nextLevel = void 0; + + level.loadError++; + level.fragmentError = fragmentError; + + if (levelError) { + if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) { + // exponential backoff capped to max retry timeout + delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); + // Schedule level reload + this.timer = setTimeout(function () { + return _this2.loadLevel(); + }, delay); + // boolean used to inform stream controller not to switch back to IDLE on non fatal error + errorEvent.levelRetry = true; + this.levelRetryCount++; + logger["b" /* logger */].warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount); + } else { + logger["b" /* logger */].error('level controller, cannot recover from ' + errorDetails + ' error'); + this.currentLevelIndex = null; + // stopping live reloading timer if any + this.clearTimer(); + // switch error to fatal + errorEvent.fatal = true; + return; + } + } + + // Try any redundant streams if available for both errors: level and fragment + // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down + if (levelError || fragmentError) { + 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, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant URL-id ' + level.urlId); + + // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId); + // console.log('New video quality level audio group id:', level.attrs.AUDIO); + } else { + // Search for available level + if (this.manualLevelIndex === -1) { + // When lowest level has been reached, let's start hunt from the top + nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1; + logger["b" /* logger */].warn('level controller, ' + errorDetails + ': switch to ' + nextLevel); + this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel; + } else if (fragmentError) { + // Allow fragment retry as long as configuration allows. + // reset this._level so that another call to set level() will trigger again a frag load + logger["b" /* logger */].warn('level controller, ' + errorDetails + ': reload a fragment'); + this.currentLevelIndex = null; + } + } + } + }; + + // 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.currentLevelIndex) { + return; + } + + 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) { + 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 targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration); + var reloadInterval = targetdurationMs, + 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 -= level_controller_performance.now() - data.stats.trequest; + // in any case, don't reload more than half of target duration + reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval)); + logger["b" /* logger */].log('live playlist, reload in ' + Math.round(reloadInterval) + ' ms'); + this.timer = setTimeout(function () { + return _this3.loadLevel(); + }, reloadInterval); + } else { + this.clearTimer(); + } + }; + + LevelController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) { + var audioGroupId = this.hls.audioTracks[data.id].groupId; + + var currentLevel = this.hls.levels[this.currentLevelIndex]; + if (!currentLevel) { + return; + } + + if (currentLevel.audioGroupIds) { + var urlId = currentLevel.audioGroupIds.findIndex(function (groupId) { + return groupId === audioGroupId; + }); + if (urlId !== currentLevel.urlId) { + currentLevel.urlId = urlId; + this.startLoad(); + } + } + }; + + LevelController.prototype.loadLevel = function loadLevel() { + logger["b" /* logger */].debug('call to loadLevel'); + + if (this.currentLevelIndex !== null && this.canload) { + var levelObject = this._levels[this.currentLevelIndex]; + + if ((typeof levelObject === 'undefined' ? 'undefined' : level_controller__typeof(levelObject)) === 'object' && levelObject.url.length > 0) { + var level = this.currentLevelIndex; + var id = levelObject.urlId; + var url = levelObject.url[id]; + + logger["b" /* logger */].log('Attempt loading level index ' + level + ' with URL-id ' + id); + + // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId); + // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level); + + this.hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: url, level: level, id: id }); + } + } + }; + + level_controller__createClass(LevelController, [{ + key: 'levels', + get: function get() { + return this._levels; + } + }, { + key: 'level', + get: function get() { + return this.currentLevelIndex; + }, + set: function set(newLevel) { + var levels = this._levels; + if (levels) { + newLevel = Math.min(newLevel, levels.length - 1); + if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) { + this.setLevelInternal(newLevel); + } + } + } + }, { + key: 'manualLevel', + get: function get() { + return this.manualLevelIndex; + }, + set: function set(newLevel) { + this.manualLevelIndex = 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.manualLevelIndex !== -1) { + return this.manualLevelIndex; + } else { + return this.hls.nextAutoLevel; + } + }, + set: function set(nextLevel) { + this.level = nextLevel; + if (this.manualLevelIndex === -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__(7); + +// CONCATENATED MODULE: ./src/utils/texttrack-utils.js + +function sendAddTrackEvent(track, videoEl) { + var event = null; + try { + event = new window.Event('addtrack'); + } catch (err) { + // for IE11 + event = document.createEvent('Event'); + event.initEvent('addtrack', false, false); + } + event.track = track; + videoEl.dispatchEvent(event); +} + +function clearCurrentCues(track) { + if (track && track.cues) { + while (track.cues.length > 0) { + track.removeCue(track.cues[0]); + } + } +} +// 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) {} + }; + + ID3TrackController.prototype.onMediaDetaching = function onMediaDetaching() { + clearCurrentCues(this.id3Track); + this.id3Track = undefined; + this.media = undefined; + }; + + ID3TrackController.prototype.getID3Track = function getID3Track(textTracks) { + for (var i = 0; i < textTracks.length; i++) { + var textTrack = textTracks[i]; + if (textTrack.kind === 'metadata' && textTrack.label === 'id3') { + // send 'addtrack' when reusing the textTrack for metadata, + // same as what we do for captions + sendAddTrackEvent(textTrack, this.media); + + return textTrack; + } + } + return this.media.addTextTrack('metadata', 'id3'); + }; + + ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) { + var fragment = data.frag; + var samples = data.samples; + + // create track dynamically + if (!this.id3Track) { + this.id3Track = this.getID3Track(this.media.textTracks); + 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/is-supported.js + + +function is_supported_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; +} +// 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__window = window, + abr_controller_performance = abr_controller__window.performance; + +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.fragCurrent = frag; + this.timer = setInterval(this.onCheck, 100); + } + + // lazy init of BwEstimator, 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; + var config = hls.config; + var level = frag.level; + var isLive = hls.levels[level].details.live; + + var 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); + } + } + }; + + 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; + var video = hls.media; + var frag = this.fragCurrent; + + if (!frag) { + return; + } + + var loader = frag.loader; + var 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(); + // reset forced auto level value so that next level will be selected + this._nextAutoLevel = -1; + 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 (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) { + var requestDelay = abr_controller_performance.now() - stats.trequest, + playbackRate = Math.abs(video.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 = video.currentTime, + fragLoadedDelay = (expectedLen - stats.loaded) / loadRate, + bufferStarvationDelay = (BufferHelper.bufferInfo(video, 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; + var 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.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 video = hls.media, + currentLevel = this.lastLoadedFragLevel, + currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0, + pos = video ? video.currentTime : 0, + + // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as + // if we're playing back at the normal rate. + playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.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 = (BufferHelper.bufferInfo(video, 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; + // current stream state: true - for live broadcast, false - for VoD content + _this._live = null; + // cache the self generated object url to detect hijack of video tag + _this._objectUrl = 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.altAudio, + 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 = window.URL.createObjectURL(ms); + // cache the locally generated object url + this._objectUrl = media.src; + } + }; + + 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) { + window.URL.revokeObjectURL(this._objectUrl); + + // clean up video tag src only if it's our own url. some external libraries might + // hijack the video tag and change its 'src' without destroying the Hls instance first + if (this.media.src === this._objectUrl) { + this.media.removeAttribute('src'); + this.media.load(); + } else { + logger["b" /* logger */].warn('media.src was changed by a third party - skip cleanup'); + } + } + + this.mediaSource = null; + this.media = null; + this._objectUrl = 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.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments + var timeRanges = {}; + var sourceBuffer = this.sourceBuffer; + for (var streamType in sourceBuffer) { + timeRanges[streamType] = sourceBuffer[streamType].buffered; + } + + this.hls.trigger(events["a" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges }); + // 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 immediately + this.flushBufferCounter = 0; + this.doFlush(); + }; + + BufferController.prototype.onLevelUpdated = function onLevelUpdated(_ref) { + var details = _ref.details; + + if (details.fragments.length > 0) { + this._levelDuration = details.totalduration + details.fragments[0].start; + this._live = details.live; + this.updateMediaElementDuration(); + } + }; + + /** + * Update Media Source duration to current level duration or override to Infinity if configuration parameter + * 'liveDurationInfinity` is set to `true` + * More details: https://github.com/video-dev/hls.js/issues/355 + */ + + + BufferController.prototype.updateMediaElementDuration = function updateMediaElementDuration() { + var config = this.hls.config; + + var duration = void 0; + + if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') { + return; + } + + for (var type in this.sourceBuffer) { + if (this.sourceBuffer[type].updating === true) { + // can't set duration whilst a buffer is updating + return; + } + } + + duration = this.media.duration; + // initialise to the value that the media source is reporting + if (this._msDuration === null) { + this._msDuration = this.mediaSource.duration; + } + + if (this._live === true && config.liveDurationInfinity === true) { + // Override duration to Infinity + logger["b" /* logger */].log('Media Source duration is set to Infinity'); + this._msDuration = this.mediaSource.duration = Infinity; + } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || duration === Infinity || isNaN(duration)) { + // levelDuration was the last value we set. + // not using mediaSource.duration as the browser may tweak this value + // only update Media Source duration if its value increase, this is to avoid + // flushing already buffered portion when switching between quality level + logger["b" /* logger */].log('Updating Media Source duration to ' + this._levelDuration.toFixed(3)); + this._msDuration = this.mediaSource.duration = this._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); + } 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); + } + } + } + } + }; + + /* + 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 = void 0, + i = void 0, + bufStart = void 0, + bufEnd = void 0, + flushStart = void 0, + flushEnd = void 0, + 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); + + var _this = 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, events["a" /* default */].BUFFER_CODECS)); + + _this.autoLevelCapping = Number.POSITIVE_INFINITY; + _this.firstLevel = null; + _this.levels = []; + _this.media = null; + _this.restrictedLevels = []; + _this.timer = null; + return _this; + } + + CapLevelController.prototype.destroy = function destroy() { + if (this.hls.config.capLevelToPlayerSize) { + this.media = null; + this._stopCapping(); + } + }; + + 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 window.HTMLVideoElement ? data.media : null; + }; + + CapLevelController.prototype.onManifestParsed = function onManifestParsed(data) { + var hls = this.hls; + this.restrictedLevels = []; + this.levels = data.levels; + this.firstLevel = data.firstLevel; + if (hls.config.capLevelToPlayerSize && (data.video || data.levels.length && data.altAudio)) { + // Start capping immediately if the manifest has signaled video codecs + this._startCapping(); + } + }; + + // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted + // to the first level + + + CapLevelController.prototype.onBufferCodecs = function onBufferCodecs(data) { + var hls = this.hls; + if (hls.config.capLevelToPlayerSize && data.video) { + // If the manifest did not signal a video codec capping has been deferred until we're certain video is present + this._startCapping(); + } + }; + + CapLevelController.prototype.onLevelsUpdated = function onLevelsUpdated(data) { + this.levels = data.levels; + }; + + 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.prototype._startCapping = function _startCapping() { + if (this.timer) { + // Don't reset capping if started twice; this can happen if the manifest signals a video codec + return; + } + this.autoLevelCapping = Number.POSITIVE_INFINITY; + this.hls.firstLevel = this.getMaxLevel(this.firstLevel); + clearInterval(this.timer); + this.timer = setInterval(this.detectPlayerSize.bind(this), 1000); + this.detectPlayerSize(); + }; + + CapLevelController.prototype._stopCapping = function _stopCapping() { + this.restrictedLevels = []; + this.firstLevel = null; + this.autoLevelCapping = Number.POSITIVE_INFINITY; + if (this.timer) { + this.timer = clearInterval(this.timer); + this.timer = null; + } + }; + + 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__window = window, + fps_controller_performance = fps_controller__window.performance; + +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 window.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 = fps_controller_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__window = window, + xhr_loader_performance = xhr_loader__window.performance, + XMLHttpRequest = xhr_loader__window.XMLHttpRequest; + +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: xhr_loader_performance.now(), retry: 0 }; + this.retryDelay = config.retryDelay; + this.loadInternal(); + }; + + XhrLoader.prototype.loadInternal = function loadInternal() { + var xhr = void 0, + 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(xhr_loader_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, xhr_loader_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); +// EXTERNAL MODULE: ./src/empty.js +var empty = __webpack_require__(3); +var empty_default = /*#__PURE__*/__webpack_require__.n(empty); + +// CONCATENATED MODULE: ./src/utils/mediakeys-helper.js +var requestMediaKeySystemAccess = function () { + if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) { + return window.navigator.requestMediaKeySystemAccess.bind(window.navigator); + } else { + return null; + } +}(); + + +// 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 + + 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 + liveDurationInfinity: false, // used by buffer-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 + 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, // used by fragment-loader + pLoader: undefined, // used by playlist-loader + xhrSetup: undefined, // used by xhr-loader + licenseXhrSetup: undefined, // used by eme-controller + // 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 + emeEnabled: false, // used by eme-controller + widevineLicenseUrl: undefined, // used by eme-controller + requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess // used by eme-controller +}; + +if (false) { + hlsDefaultConfig.subtitleStreamController = SubtitleStreamController; + hlsDefaultConfig.subtitleTrackController = SubtitleTrackController; + hlsDefaultConfig.timelineController = TimelineController; + hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller + 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 (false) { + hlsDefaultConfig.audioStreamController = AudioStreamController; + hlsDefaultConfig.audioTrackController = AudioTrackController; +} + +if (false) { + hlsDefaultConfig.emeController = EMEController; +} +// 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"); } } + + + + + + + + + + + + + + + + + + + + + +// polyfill for IE11 +__webpack_require__(13); + +/** + * @module Hls + * @class + * @constructor + */ + +var hls_Hls = function () { + + /** + * @type {boolean} + */ + Hls.isSupported = function isSupported() { + return is_supported_isSupported(); + }; + + /** + * @type {HlsEvents} + */ + + + hls__createClass(Hls, null, [{ + key: 'version', + + /** + * @type {string} + */ + get: function get() { + return "0.10.0"; + } + }, { + key: 'Events', + get: function get() { + return events["a" /* default */]; + } + + /** + * @type {HlsErrorTypes} + */ + + }, { + key: 'ErrorTypes', + get: function get() { + return errors["b" /* ErrorTypes */]; + } + + /** + * @type {HlsErrorDetails} + */ + + }, { + key: 'ErrorDetails', + get: function get() { + return errors["a" /* ErrorDetails */]; + } + + /** + * @type {HlsConfig} + */ + + }, { + key: 'DefaultConfig', + get: function get() { + if (!Hls.defaultConfig) { + return hlsDefaultConfig; + } + + return Hls.defaultConfig; + } + + /** + * @type {HlsConfig} + */ + , + set: function set(defaultConfig) { + Hls.defaultConfig = defaultConfig; + } + + /** + * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`. + * + * @constructs Hls + * @param {HlsConfig} config + */ + + }]); + + 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.once = observer.once.bind(observer); + this.trigger = observer.trigger.bind(observer); + + // core controllers and network loaders + + /** + * @member {AbrController} abrController + */ + 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 + + /** + * @member {LevelController} levelController + */ + var levelController = this.levelController = new level_controller(this); + + // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important + var fragmentTracker = new fragment_tracker_FragmentTracker(this); + + /** + * @member {StreamController} streamController + */ + var streamController = this.streamController = new stream_controller(this, fragmentTracker); + + var networkControllers = [levelController, streamController]; + + // optional audio stream controller + /** + * @var {ICoreComponent | Controller} + */ + var Controller = config.audioStreamController; + if (Controller) { + networkControllers.push(new Controller(this, fragmentTracker)); + } + + /** + * @member {INetworkController[]} networkControllers + */ + this.networkControllers = networkControllers; + + /** + * @var {ICoreComponent[]} + */ + var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker]; + + // optional audio track and subtitle controller + Controller = config.audioTrackController; + if (Controller) { + var audioTrackController = new Controller(this); + + /** + * @member {AudioTrackController} audioTrackController + */ + this.audioTrackController = audioTrackController; + coreComponents.push(audioTrackController); + } + + Controller = config.subtitleTrackController; + if (Controller) { + var subtitleTrackController = new Controller(this); + + /** + * @member {SubtitleTrackController} subtitleTrackController + */ + this.subtitleTrackController = subtitleTrackController; + coreComponents.push(subtitleTrackController); + } + + Controller = config.emeController; + if (Controller) { + var emeController = new Controller(this); + + /** + * @member {EMEController} emeController + */ + this.emeController = emeController; + coreComponents.push(emeController); + } + + // optional subtitle controller + [config.subtitleStreamController, config.timelineController].forEach(function (Controller) { + if (Controller) { + coreComponents.push(new Controller(_this)); + } + }); + + /** + * @member {ICoreComponent[]} + */ + this.coreComponents = coreComponents; + } + + /** + * Dispose of the instance + */ + + + 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; + }; + + /** + * Attach a media element + * @param {HTMLMediaElement} media + */ + + + Hls.prototype.attachMedia = function attachMedia(media) { + logger["b" /* logger */].log('attachMedia'); + this.media = media; + this.trigger(events["a" /* default */].MEDIA_ATTACHING, { media: media }); + }; + + /** + * Detach from the media + */ + + + Hls.prototype.detachMedia = function detachMedia() { + logger["b" /* logger */].log('detachMedia'); + this.trigger(events["a" /* default */].MEDIA_DETACHING); + this.media = null; + }; + + /** + * Set the source URL. Can be relative or absolute. + * @param {string} url + */ + + + 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 }); + }; + + /** + * Start loading data from the stream source. + * Depending on default config, client starts loading automatically when a source is set. + * + * @param {number} startPosition Set the start position to stream from + * @default -1 None (from earliest point) + */ + + + 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); + }); + }; + + /** + * Stop loading of any stream data. + */ + + + Hls.prototype.stopLoad = function stopLoad() { + logger["b" /* logger */].log('stopLoad'); + this.networkControllers.forEach(function (controller) { + controller.stopLoad(); + }); + }; + + /** + * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1) + */ + + + Hls.prototype.swapAudioCodec = function swapAudioCodec() { + logger["b" /* logger */].log('swapAudioCodec'); + this.streamController.swapAudioCodec(); + }; + + /** + * When the media-element fails, this allows to detach and then re-attach it + * as one call (convenience method). + * + * Automatic recovery of media-errors by this process is configurable. + */ + + + Hls.prototype.recoverMediaError = function recoverMediaError() { + logger["b" /* logger */].log('recoverMediaError'); + var media = this.media; + this.detachMedia(); + this.attachMedia(media); + }; + + /** + * @type {QualityLevel[]} + */ + + + hls__createClass(Hls, [{ + key: 'levels', + get: function get() { + return this.levelController.levels; + } + + /** + * Index of quality level currently played + * @type {number} + */ + + }, { + key: 'currentLevel', + get: function get() { + return this.streamController.currentLevel; + } + + /** + * Set quality level index immediately . + * This will flush the current buffer to replace the quality asap. + * That means playback will interrupt at least shortly to re-buffer and re-sync eventually. + * @type {number} -1 for automatic level selection + */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set currentLevel:' + newLevel); + this.loadLevel = newLevel; + this.streamController.immediateLevelSwitch(); + } + + /** + * Index of next quality level loaded as scheduled by stream controller. + * @type {number} + */ + + }, { + key: 'nextLevel', + get: function get() { + return this.streamController.nextLevel; + } + + /** + * Set quality level index for next loaded data. + * This will switch the video quality asap, without interrupting playback. + * May abort current loading of data, and flush parts of buffer (outside currently played fragment region). + * @type {number} -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 the currently or last (of none is loaded currently) segment + * @type {number} + */ + + }, { + key: 'loadLevel', + get: function get() { + return this.levelController.level; + } + + /** + * Set quality level index for next loaded data in a conservative way. + * This will switch the quality without flushing, but interrupt current loading. + * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer. + * @type {number} newLevel -1 for automatic level selection + */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set loadLevel:' + newLevel); + this.levelController.manualLevel = newLevel; + } + + /** + * get next quality level loaded + * @type {number} + */ + + }, { + key: 'nextLoadLevel', + get: function get() { + return this.levelController.nextLoadLevel; + } + + /** + * Set quality level of next loaded segment in a fully "non-destructive" way. + * Same as `loadLevel` but will wait for next switch (until current loading is done). + * @type {number} level + */ + , + set: function set(level) { + this.levelController.nextLoadLevel = level; + } + + /** + * Return "first level": like a default level, if not set, + * falls back to index of first level referenced in manifest + * @type {number} + */ + + }, { + key: 'firstLevel', + get: function get() { + return Math.max(this.levelController.firstLevel, this.minAutoLevel); + } + + /** + * Sets "first-level", see getter. + * @type {number} + */ + , + 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) + * @type {number} + */ + + }, { + 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) + * @type {number} newLevel + */ + , + 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; + } + + /** + * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) + * @type {number} + */ + + }, { + key: 'autoLevelCapping', + get: function get() { + return this._autoLevelCapping; + } + + /** + * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`) + * @type {number} + */ + , + set: function set(newLevel) { + logger["b" /* logger */].log('set autoLevelCapping:' + newLevel); + this._autoLevelCapping = newLevel; + } + + /** + * True when automatic level selection enabled + * @type {boolean} + */ + + }, { + key: 'autoLevelEnabled', + get: function get() { + return this.levelController.manualLevel === -1; + } + + /** + * Level set manually (if any) + * @type {number} + */ + + }, { + key: 'manualLevel', + get: function get() { + return this.levelController.manualLevel; + } + + /** + * min level selectable in auto mode according to config.minAutoBitrate + * @type {number} + */ + + }, { + 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; + } + + /** + * max level selectable in auto mode according to autoLevelCapping + * @type {number} + */ + + }, { + 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; + } + + /** + * next automatically selected quality level + * @type {number} + */ + + }, { + 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. + * @type {number} + */ + , + set: function set(nextLevel) { + var hls = this; + hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel); + } + + /** + * @type {AudioTrack[]} + */ + + }, { + key: 'audioTracks', + get: function get() { + var audioTrackController = this.audioTrackController; + return audioTrackController ? audioTrackController.audioTracks : []; + } + + /** + * index of the selected audio track (index in audio track lists) + * @type {number} + */ + + }, { + key: 'audioTrack', + get: function get() { + var audioTrackController = this.audioTrackController; + return audioTrackController ? audioTrackController.audioTrack : -1; + } + + /** + * selects an audio track, based on its index in audio track lists + * @type {number} + */ + , + set: function set(audioTrackId) { + var audioTrackController = this.audioTrackController; + if (audioTrackController) { + audioTrackController.audioTrack = audioTrackId; + } + } + + /** + * @type {Seconds} + */ + + }, { + key: 'liveSyncPosition', + get: function get() { + return this.streamController.liveSyncPosition; + } + + /** + * get alternate subtitle tracks list from playlist + * @type {SubtitleTrack[]} + */ + + }, { + key: 'subtitleTracks', + get: function get() { + var subtitleTrackController = this.subtitleTrackController; + return subtitleTrackController ? subtitleTrackController.subtitleTracks : []; + } + + /** + * index of the selected subtitle track (index in subtitle track lists) + * @type {number} + */ + + }, { + 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 + * @type{number} + */ + , + set: function set(subtitleTrackId) { + var subtitleTrackController = this.subtitleTrackController; + if (subtitleTrackController) { + subtitleTrackController.subtitleTrack = subtitleTrackId; + } + } + + /** + * @type {boolean} + */ + + }, { + key: 'subtitleDisplay', + get: function get() { + var subtitleTrackController = this.subtitleTrackController; + return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false; + } + + /** + * Enable/disable subtitle display rendering + * @type {boolean} + */ + , + 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); + +/***/ }), +/* 11 */ +/***/ (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 +} + +var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+' +var dependencyRegExp = '\\((\/\\*.*?\\*\/)?\s?.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true + +// http://stackoverflow.com/a/2593661/130442 +function quoteRegExp (str) { + return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') +} + +function getModuleDependencies (sources, module, queueName) { + var retval = {} + retval[queueName] = [] + + var fnString = module.toString() + var wrapperSignature = fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/) + if (!wrapperSignature) return retval + var webpackRequireName = wrapperSignature[1] + + // main bundle deps + var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g') + var match + while ((match = re.exec(fnString))) { + if (match[3] === 'dll-reference') continue + retval[queueName].push(match[3]) + } + + // dll deps + re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g') + while ((match = re.exec(fnString))) { + if (!sources[match[2]]) { + retval[queueName].push(match[1]) + sources[match[2]] = __webpack_require__(match[1]).m + } + retval[match[2]] = retval[match[2]] || [] + retval[match[2]].push(match[4]) + } + + return retval +} + +function hasValuesInQueues (queues) { + var keys = Object.keys(queues) + return keys.reduce(function (hasValues, key) { + return hasValues || queues[key].length > 0 + }, false) +} + +function getRequiredModules (sources, moduleId) { + var modulesQueue = { + main: [moduleId] + } + var requiredModules = { + main: [] + } + var seenModules = { + main: {} + } + + while (hasValuesInQueues(modulesQueue)) { + var queues = Object.keys(modulesQueue) + for (var i = 0; i < queues.length; i++) { + var queueName = queues[i] + var queue = modulesQueue[queueName] + var moduleToCheck = queue.pop() + seenModules[queueName] = seenModules[queueName] || {} + if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue + seenModules[queueName][moduleToCheck] = true + requiredModules[queueName] = requiredModules[queueName] || [] + requiredModules[queueName].push(moduleToCheck) + var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName) + var newModulesKeys = Object.keys(newModules) + for (var j = 0; j < newModulesKeys.length; j++) { + modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || [] + modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]]) + } + } + } + + return requiredModules +} + +module.exports = function (moduleId, options) { + options = options || {} + var sources = { + main: __webpack_require__.m + } + + var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId) + + var src = '' + + Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) { + var entryModule = 0 + while (requiredModules[module][entryModule]) { + entryModule++ + } + requiredModules[module].push(entryModule) + sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })' + src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n' + }) + + src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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 +} + + +/***/ }), +/* 12 */ +/***/ (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__(9); +/* 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__(6); +/* 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); + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + +/*! http://mths.be/endswith v0.2.0 by @mathias */ +if (!String.prototype.endsWith) { + (function() { + 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` + var defineProperty = (function() { + // IE 8 only supports `Object.defineProperty` on DOM elements + try { + var object = {}; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch(error) {} + return result; + }()); + var toString = {}.toString; + var endsWith = function(search) { + if (this == null) { + throw TypeError(); + } + var string = String(this); + if (search && toString.call(search) == '[object RegExp]') { + throw TypeError(); + } + var stringLength = string.length; + var searchString = String(search); + var searchLength = searchString.length; + var pos = stringLength; + if (arguments.length > 1) { + var position = arguments[1]; + if (position !== undefined) { + // `ToInteger` + pos = position ? Number(position) : 0; + if (pos != pos) { // better `isNaN` + pos = 0; + } + } + } + var end = Math.min(Math.max(pos, 0), stringLength); + var start = end - searchLength; + if (start < 0) { + return false; + } + var index = -1; + while (++index < searchLength) { + if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) { + return false; + } + } + return true; + }; + if (defineProperty) { + defineProperty(String.prototype, 'endsWith', { + 'value': endsWith, + 'configurable': true, + 'writable': true + }); + } else { + String.prototype.endsWith = endsWith; + } + }()); +} + + +/***/ }) +/******/ ])["default"]; +}); +//# sourceMappingURL=hls.light.js.map \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls.light.js.map b/grails-app/assets/bower/hls.js/dist/hls.light.js.map new file mode 100644 index 000000000..065a9e9de --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls.light.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap d3b1ee6a92843b970ab8","webpack:///./src/utils/logger.js","webpack:///./src/events.js","webpack:///./src/errors.js","webpack:///./src/empty.js","webpack:///./src/utils/get-self-scope.js","webpack:///./node_modules/url-toolkit/src/url-toolkit.js","webpack:///./node_modules/events/events.js","webpack:///./src/demux/id3.js","webpack:///./src/demux/mp4demuxer.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:///./src/demux/adts.js","webpack:///./src/demux/aacdemuxer.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/remux/aac-helper.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/loader/level-key.js","webpack:///./src/loader/fragment.js","webpack:///./src/utils/attr-list.js","webpack:///./src/utils/codecs.js","webpack:///./src/loader/m3u8-parser.js","webpack:///./src/loader/playlist-loader.js","webpack:///./src/loader/fragment-loader.js","webpack:///./src/loader/key-loader.js","webpack:///./src/controller/fragment-tracker.js","webpack:///./src/utils/binary-search.js","webpack:///./src/utils/buffer-helper.js","webpack:///./src/utils/mediasource-helper.js","webpack:///./src/demux/demuxer.js","webpack:///./src/controller/level-helper.js","webpack:///./src/utils/time-ranges.js","webpack:///./src/utils/discontinuities.js","webpack:///./src/task-loop.js","webpack:///./src/controller/fragment-finders.js","webpack:///./src/controller/stream-controller.js","webpack:///./src/controller/level-controller.js","webpack:///./src/utils/texttrack-utils.js","webpack:///./src/controller/id3-track-controller.js","webpack:///./src/is-supported.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/utils/mediakeys-helper.js","webpack:///./src/config.js","webpack:///./src/hls.js","webpack:///./node_modules/webworkify-webpack/index.js","webpack:///./src/demux/demuxer-worker.js","webpack:///./node_modules/string.prototype.endswith/endswith.js"],"names":["noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","formatMsg","type","msg","global","getSelfScope","consolePrintFn","func","console","args","apply","exportLoggerFunctions","debugConfig","functions","forEach","bind","enableLogs","e","logger","HlsEvents","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_SWITCHING","LEVEL_SWITCHED","LEVEL_LOADING","LEVEL_LOADED","LEVEL_UPDATED","LEVEL_PTS_UPDATED","AUDIO_TRACKS_UPDATED","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","KEY_SYSTEM_ERROR","MUX_ERROR","OTHER_ERROR","ErrorDetails","KEY_SYSTEM_NO_KEYS","KEY_SYSTEM_NO_ACCESS","KEY_SYSTEM_NO_SESSION","KEY_SYSTEM_LICENSE_REQUEST_FAILED","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_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","module","exports","window","self","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","exitOnNull","len","c","char2","char3","out","utf8ArrayToStr","UINT32_MAX","pow","MP4Demuxer","observer","remuxer","resetTimeStamp","initPTS","resetInitSegment","initSegment","audioCodec","videoCodec","duration","initData","parseInitSegment","tracks","audio","video","audiovideo","container","codec","trigger","Event","probe","findBox","start","min","bin2str","readUint16","val","readUint32","writeUint32","path","results","subresults","endbox","slice","concat","parseSegmentIndex","moov","moovEndOffset","sidx","references","version","timescale","earliestPresentationTime","firstOffset","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","referenceType","subsegmentDuration","result","traks","tkhd","trak","trackId","mdhd","hdlr","hdlrType","codecBox","codecType","id","getStartDTS","fragment","trafs","baseTimes","map","traf","tfhd","scale","baseTime","tfdt","isFinite","offsetStartDTS","timeOffset","baseMediaDecodeTime","max","upper","floor","lower","append","contiguous","accurateTimeOffset","startDTS","remux","destroy","AESCrypto","subtle","iv","aesIV","decrypt","name","FastAESKey","expandKey","importKey","removePadding","outputBytes","paddingBytes","DataView","getUint8","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","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","removePKCS7Padding","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","swapWord","config","logEnabled","browserCrypto","crypto","webkitSubtle","disableWebCrypto","isSync","enableSoftwareAES","callback","decryptor","fastAesKey","then","aesKey","catch","err","onWebCryptoError","message","details","fatal","reason","getAudioConfig","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","navigator","toLowerCase","manifestCodec","adtsSampleingRates","test","Array","indexOf","samplerate","channelCount","isHeaderPattern","getHeaderLength","getFullFrameLength","headerLength","frameLength","newOffset","initTrackConfig","track","getFrameDuration","parseFrameHeader","pts","frameIndex","frameDuration","stamp","appendFrame","header","aacSample","unit","dts","samples","sample","_audioTrack","sequenceNumber","isAAC","inputTimeScale","id3Samples","ADTS","MpegAudio","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","parseInt","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","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","gapTolerance","deltaToFrameEnd","nextAudioPts","data1","data2","endDTS","hasAudio","hasVideo","nb","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","mp4Sample","fillFrame","filter","maxAudioFramesDrift","nextPts","toFixed","missing","newStamp","audioSample","numMissingFrames","unitLen","lastSampleDuration","sampleDuration","silentFrame","reference","rawData","streamType","performance","demuxer","discontinuity","trackSwitch","defaultInitPTS","startTime","now","Date","endTime","stats","tstart","tdecrypt","pushDecrypted","muxConfig","demux","mux","FORBIDDEN_EVENT_NAMES","Set","hls","onEvent","events","handledEvents","useGenericHandler","registerListeners","onHandlerDestroying","unregisterListeners","onHandlerDestroyed","isEventHandler","event","has","on","off","onEventGeneric","eventToFunction","funcName","replace","constructor","_uri","reluri","URLToolkit","buildAbsoluteURL","baseuri","alwaysNormalize","_url","_byteRange","_decryptdata","tagList","_elementaryStreams","Fragment","ElementaryStreamTypes","AUDIO","VIDEO","addElementaryStream","hasElementaryStream","createInitializationVector","segmentNumber","uint8View","fragmentDecryptdataFromLevelkey","levelkey","uri","relurl","baseurl","_programDateTime","rawProgramDateTime","parse","rawByteRange","byteRange","params","split","lastByteRangeEndOffset","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","parseAttrList","attr","decimalInteger","attrName","intValue","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","MP4_REGEX_SUFFIX","findGroup","groups","mediaGroupId","matchingGroup","group","convertAVC1ToAVCOTI","avcdata","substr","resolve","baseUrl","parseMasterPlaylist","string","levels","setCodecs","codecs","level","filtered","preferred","unknownCodecs","M3U8Parser","resolution","bitrate","NAME","CODECS","parseMasterPlaylistMedia","audioGroups","medias","media","TYPE","groupId","default","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","URI","lang","LANGUAGE","groupCodec","parseLevelPlaylist","levelUrlId","currentSN","totalduration","fragments","live","startSN","cc","prevFrag","title","isNaN","urlId","programDateTime","pdt","endPdt","byteRangeEndOffset","value1","value2","toUpperCase","targetduration","decryptparams","keyAttrs","decryptmethod","decrypturi","decryptiv","startParams","startAttrs","startTimeOffset","mapAttrs","BYTERANGE","pop","averagetargetduration","endSN","startCC","endCC","every","needSidxRanges","ContextType","MANIFEST","LEVEL","AUDIO_TRACK","SUBTITLE_TRACK","LevelType","MAIN","SUBTITLE","loaders","canHaveQualityLevels","mapContextToLevelType","context","getResponseUrl","response","createInternalLoader","PLoader","pLoader","Loader","loader","InternalLoader","getInternalLoader","resetInternalLoader","contextType","destroyInternalLoaders","onManifestLoading","load","onLevelLoading","onAudioTrackLoading","onSubtitleTrackLoading","loaderContext","abort","maxRetry","timeout","retryDelay","maxRetryDelay","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","responseType","loaderConfig","loaderCallbacks","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","networkDetails","isSidxRequest","_handleSidxRequest","_handlePlaylistLoaded","tload","_handleManifestParsingError","_handleTrackOrLevelPlaylist","_handleMasterPlaylist","_handleNetworkError","PlaylistLoader","audioTracks","subtitles","embeddedAudioFound","unshift","levelId","levelType","levelDetails","singleLevel","tparsed","sidxUrl","rangeStart","rangeEnd","sidxInfo","segmentRef","segRefInfo","canHaveLevels","loaderName","onFragLoading","FragmentILoader","fLoader","DefaultILoader","loaded","progressData","byteRangeStartOffset","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","decryptkey","decrypturl","EventHandler","onKeyLoading","fragLoadingMaxRetry","fragLoadingRetryDelay","FragmentState","NOT_LOADED","APPENDING","PARTIAL","OK","bufferPadding","create","timeRanges","getBufferedFrag","bufferedFrags","fragmentEntity","body","buffered","bufferedFragKey","detectEvictedFragments","elementaryStream","timeRange","fragmentTimes","time","esData","range","isTimeBuffered","removeFragment","detectPartialFragments","fragKey","getFragmentKey","getBufferedTimes","fragmentPartial","partial","getPartialFragment","timePadding","bestFragment","bestOverlap","isPartial","getState","onFragLoaded","bitrateTest","onBufferAppended","onFragBuffered","hasFragment","removeAllFragments","BinarySearch","search","list","comparisonFunction","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","BufferHelper","isBuffered","bufferInfo","maxHoleDuration","vbuffered","bufferedInfo","nextStart","buffered2","bufferLen","bufferStart","bufferEnd","bufferStartNext","diff","buf2len","buf2end","getMediaSource","WebKitMediaSource","emit","removeListener","forwardMessage","ev","mp4","enableWorker","Worker","w","work","onwmsg","onWorkerMessage","addEventListener","onerror","filename","lineno","postMessage","cmd","JSON","stringify","URL","revokeObjectURL","objectURL","removeEventListener","terminate","removeAllListeners","lastFrag","nextSN","ArrayBuffer","addGroupId","audioGroupIds","textGroupIds","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","TaskLoop","_tickInterval","_tickTimer","_tickCallCount","_boundTick","tick","clearNextTick","clearInterval","hasInterval","hasNextTick","setInterval","millis","clearTimeout","doTick","setTimeout","calculateNextPDT","parsedDateInt","findFragmentByPDT","PDTValue","isArray","firstSegment","lastSegment","seg","findFragmentBySN","fragPrevious","maxFragLookUpTolerance","foundFrag","fragNext","fragmentWithinToleranceTest","candidateLookupTolerance","State","STOPPED","IDLE","FRAG_LOADING_WAITING_RETRY","WAITING_LEVEL","PARSING","PARSED","ENDED","fragmentTracker","audioCodecSwap","_state","stallReported","stopLoad","startLoad","startPosition","lastCurrentTime","fragLoadError","startFragRequested","startLevel","nextLoadLevel","loadedmetadata","nextLoadPosition","forceStartLoad","fragCurrent","_doTickIdle","retryDate","seeking","_checkBuffer","_checkFragmentChanged","levelLastLoaded","startFragPrefetch","currentTime","levelInfo","levelBitrate","maxBufLen","maxBufferSize","maxBufferLength","maxMaxBufferLength","mediaBuffer","altAudio","_fetchPayloadOrEos","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","encrypted","_loadKey","_loadFragment","maxLatency","liveMaxLatencyDuration","liveMaxLatencyDurationCount","liveSyncPosition","computeLivePosition","readyState","targetSN","fragBySN","curSNIdx","sameLevel","nextFrag","fragState","autoLevel","autoLevelEnabled","_reduceMaxBufferLength","followingBufferedFrag","fragPlayingCurrent","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","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","pending","total","tfirst","mediaBuffered","delay","levelRetry","minLength","stallDebounceInterval","_seekToStartPos","expectedPlaying","tnow","nudgeRetry","stalledDuration","_reportStall","_tryFixBufferStall","onFragLoadEmergencyAborted","onBufferFlushed","swapAudioCodec","targetLatency","liveSyncDuration","liveSyncDurationCount","jumpThreshold","_trySkipBufferHole","highBufferWatchdogPeriod","_tryNudgeBuffer","lastEndTime","nudgeMaxRetry","targetTime","nudgeOffset","nextState","previousState","_liveSyncPosition","canload","currentLevelIndex","manualLevelIndex","timer","clearTimer","_levels","levelRetryCount","loadError","loadLevel","onManifestLoaded","bitrateStart","levelSet","levelFromSet","videoCodecFound","audioCodecFound","chromeOrFirefox","fragmentError","SUBTITLES","_firstLevel","firstLevel","setLevelInternal","newLevel","levelProperties","levelError","levelIndex","recoverLevel","errorEvent","errorDetails","redundantLevels","nextAutoLevel","targetdurationMs","reloadInterval","trequest","audioGroupId","findIndex","levelObject","_startLevel","configStartLevel","sendAddTrackEvent","videoEl","document","createEvent","initEvent","dispatchEvent","clearCurrentCues","cues","removeCue","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","mode","Cue","WebKitDataCue","VTTCue","TextTrackCue","cue","addCue","mediaSource","sourceBuffer","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","appendBuffer","remove","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","isLive","ewmaFast","ewmaSlow","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","minAutoLevel","aborted","playbackRate","requestDelay","loadRate","bw","realBitrate","expectedLen","fragLoadedDelay","bufferStarvationDelay","fragLevelNextLoadedDelay","levelNextBitrate","abrMaxWithRealBitrate","loadedBytes","loadedDuration","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","_live","_objectUrl","onsbue","onSBUpdateEnd","onsbe","onSBUpdateError","pendingTracks","onLevelPtsUpdated","audioBuffer","timestampOffset","updating","audioTimestampOffset","audioExpected","videoExpected","sourceBufferNb","onMediaAttaching","ms","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","liveDurationInfinity","flushBuffer","appendError","code","appendErrorMaxRetry","typeIn","bufStart","bufEnd","flushStart","flushEnd","autoLevelCapping","restrictedLevels","capLevelToPlayerSize","_stopCapping","onFpsDropLevelCapping","CapLevelController","isLevelAllowed","droppedLevel","HTMLVideoElement","_startCapping","onLevelsUpdated","detectPlayerSize","levelsLength","getMaxLevel","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","XMLHttpRequest","xhrSetup","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","requestMediaKeySystemAccess","hlsDefaultConfig","lowBufferWatchdogPeriod","licenseXhrSetup","abrController","bufferController","capLevelController","fpsController","minAutoBitrate","emeEnabled","widevineLicenseUrl","requestMediaKeySystemAccessFunc","subtitleStreamController","SubtitleStreamController","subtitleTrackController","SubtitleTrackController","timelineController","TimelineController","cueHandler","Cues","enableCEA708Captions","enableWebVTT","captionsTextTrack1Label","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","audioStreamController","AudioStreamController","audioTrackController","AudioTrackController","emeController","EMEController","require","isSupported","Hls","defaultConfig","DefaultConfig","prop","_autoLevelCapping","once","playListLoader","fragmentLoader","keyLoader","id3TrackController","levelController","networkControllers","Controller","coreComponents","detachMedia","component","attachMedia","loadSource","location","href","controller","recoverMediaError","manualLevel","audioTrackId","subtitleTracks","subtitleTrack","subtitleTrackId","subtitleDisplay","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;;;;;;;;;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AAuB1B;AACAC,mBAAiB,eAxBS;AAyB1B;AACAC,qBAAmB,iBA1BO;AA2B1B;AACAC,sBAAoB,kBA5BM;AA6B1B;AACA;AACAC,sBAAoB,kBA/BM;AAgC1B;AACAC,qBAAmB,iBAjCO;AAkC1B;AACAC,kBAAgB,cAnCU;AAoC1B;AACAC,oBAAkB,gBArCQ;AAsC1B;AACAC,0BAAwB,qBAvCE;AAwC1B;AACAC,uBAAqB,mBAzCK;AA0C1B;AACAC,0BAAwB,sBA3CE;AA4C1B;AACAC,wBAAsB,oBA7CI;AA8C1B;AACAC,qBAAmB,iBA/CO;AAgD1B;AACAC,yBAAuB,oBAjDG;AAkD1B;AACAC,yBAAuB,oBAnDG;AAoD1B;AACAC,sBAAoB;AArDM,CAArB,C;;;;;;ACjBP;AACA;AACAC,OAAOC,OAAP,GAAiB,KAAK,CAAtB,C;;;;;;;;ACFO,SAAStG,YAAT,GAAyB;AAC9B;AACA,MAAI,OAAOuG,MAAP,KAAkB,WAAtB,EAAmC;AACjC;AACA,WAAOC,IAAP;AACD,GAHD,MAGO;AACL,WAAOD,MAAP;AACD;AACF,C;;;;;;ACRD;;AAEA;AACA,iB;AACA;;AAEA,uDAAuD,eAAe;AACtE,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;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sFAAsF;AACtF;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,2BAA2B,mBAAmB,EAAE;AAChD;AACA;AACA;AACA;AACA,CAAC;AACD;;;;;;;AClKA;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;;AAE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;;;AC3EA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA,GAAG;AACH,mBAAmB;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,GAAG;AACH;AACA;AACA,EAAE;AACF","file":"hls.light.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 = 10);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap d3b1ee6a92843b970ab8","import { getSelfScope } from './get-self-scope';\n\nfunction noop () {}\n\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nlet exportedLogger = fakeLogger;\n\n// 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\nconst global = getSelfScope();\n\nfunction consolePrintFn (type) {\n const func = global.console[type];\n if (func) {\n return function (...args) {\n if (args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n\n func.apply(global.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 } else {\n exportedLogger = fakeLogger;\n }\n};\n\nexport var logger = exportedLogger;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/logger.js","/**\n * @readonly\n * @enum {string}\n */\nconst HlsEvents = {\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 }\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 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\nexport default HlsEvents;\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 // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR: 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nexport const ErrorDetails = {\n KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',\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 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","// This file is inserted as a shim for modules which we do not want to include into the distro.\n// This replacement is done in the \"resolve\" section of the webpack config.\nmodule.exports = void 0;\n\n\n\n// WEBPACK FOOTER //\n// ./src/empty.js","export function getSelfScope () {\n // see https://stackoverflow.com/a/11237259/589493\n if (typeof window === 'undefined') {\n /* eslint-disable-next-line no-undef */\n return self;\n } else {\n return window;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/get-self-scope.js","// 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 = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\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 (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 = 5\n// module chunks = 0","// 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 = 6\n// module chunks = 0","/**\n * ID3 parser\n */\nclass 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\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;\n } // 2^32 / 90\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, true);\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, exitOnNull = false) {\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 (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\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","/**\n * MP4 demuxer\n */\nimport { logger } from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4Demuxer {\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\n if (videoCodec == null) {\n videoCodec = 'avc1.42e01e';\n }\n\n const 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\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 });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\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 static bin2str (buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint16 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 8 |\n buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\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 // Find the data for a box specified by its path\n static findBox (data, path) {\n let 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 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 static parseSegmentIndex (initSegment) {\n const moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n const moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n let index = 0;\n let sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n let references;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n const version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n const timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.end + firstOffset;\n\n const referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7FFFFFFF;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n const subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n moovEndOffset\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 let result = [];\n let 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 * 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 */\n static getStartDTS (initData, fragment) {\n let 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 let 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 let 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 static 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 let id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n let 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 let version = tfdt.data[tfdt.start];\n let 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, false);\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\nexport default MP4Demuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/mp4demuxer.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","// PKCS7\nexport function removePadding (buffer) {\n const outputBytes = buffer.byteLength;\n const paddingBytes = outputBytes && (new DataView(buffer)).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return buffer.slice(0, outputBytes - paddingBytes);\n } else {\n return buffer;\n }\n}\n\nclass 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\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, removePKCS7Padding) {\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 let 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 removePKCS7Padding ? removePadding(outputInt32.buffer) : 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\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nclass Decrypter {\n constructor (observer, config, { removePKCS7Padding = true } = {}) {\n this.logEnabled = true;\n this.observer = observer;\n this.config = config;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = global.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {}\n }\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\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));\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 } 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","/**\n * ADTS parser helper\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\nexport function getAudioConfig (observer, data, offset, audioCodec) {\n let 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\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\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 let 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 let headerLength, frameLength, stamp;\n let 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 let frameDuration = getFrameDuration(track.samplerate);\n let header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n let stamp = header.stamp;\n let headerLength = header.headerLength;\n let frameLength = header.frameLength;\n\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n let 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// 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 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\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 let 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\nexport default AACDemuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/aacdemuxer.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 SamplesCoefficients: [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]\n ],\n\n BytesInSlot: [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\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 let header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n let frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;\n let stamp = pts + frameIndex * frameDuration;\n let 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 let headerB = (data[offset + 1] >> 3) & 3;\n let headerC = (data[offset + 1] >> 1) & 3;\n let headerE = (data[offset + 2] >> 4) & 15;\n let headerF = (data[offset + 2] >> 2) & 3;\n let headerG = (data[offset + 2] >> 1) & 1;\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n let columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n let bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n let columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n let sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n let channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n let sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n let bytesInSlot = MpegAudio.BytesInSlot[headerC];\n let samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n let frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\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\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\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 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 let\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\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 let 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 let\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\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\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 let leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\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 let clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG () {\n let 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 this.readBits(1) === 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 let\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 let\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 let chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // 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 let 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();\n } // offset_for_ref_frame[ i ]\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);\n } // 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\nimport Decrypter from '../crypt/decrypter';\n\nclass SampleAesDecrypter {\n constructor (observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config, { removePKCS7Padding: false });\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\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\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\nexport 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\nimport * as ADTS from './adts';\nimport MpegAudio from './mpegaudio';\nimport Event from '../events';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\n// import Hex from '../utils/hex';\nimport { logger } from '../utils/logger';\nimport { 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: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nclass TSDemuxer {\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\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 let start, len = data.length, stt, pid, atf, offset, pes,\n unknownPIDs = false;\n this.contiguous = contiguous;\n let 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)) && pes.pts !== undefined) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n parseID3PES(pes);\n }\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\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\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\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\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)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\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\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)) && pes.pts !== undefined) {\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 let 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\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\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\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 let 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\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 let 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\n if (debug) {\n avcSample.debug += 'NDR ';\n }\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\n if (debug) {\n avcSample.debug += 'IDR ';\n }\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\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 endOfCaptions = true;\n\n let countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n let providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n let userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n let userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n let firstByte = expGolombDecoder.readUByte();\n let secondByte = expGolombDecoder.readUByte();\n\n let totalCCs = 31 & firstByte;\n let 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 } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\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\n if (!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n let 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 let codecarray = unit.data.subarray(1, 4);\n let codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\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\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\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\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 let len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\n } else {\n for (let 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 } 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 let i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n let 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 let 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 let 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 let 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 let 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 let 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 let 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 let 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\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES (pes) {\n let data = pes.data;\n let length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let 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 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 let 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 timestamp = ID3.getTimeStamp(id3Data);\n let pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n let offset = id3Data.length;\n let length = data.length;\n let frameIndex = 0, stamp = 0;\n let 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 let 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\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/remux/aac-helper.js","/**\n * Generate MP4 Box\n*/\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 let 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 let 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 let 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 let 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 let 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 let majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n let avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n let 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 let\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\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 let\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 let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\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 let\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 let\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 let 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\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\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\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n let 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\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 let 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 let 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 let 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\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 let 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 let 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 let 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 let 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\n let 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\nimport AAC from './aac-helper';\nimport MP4 from './mp4-generator';\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\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\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 // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED);\n }\n\n generateIS (audioTrack, videoTrack, timeOffset) {\n let 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\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 let 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 if (nbSamples === 0) {\n return;\n }\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 || (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\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\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 maxBufferHole.\n // 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 gapTolerance = Math.floor(maxBufferHole * 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 should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\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 // 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 hasAudio: false,\n hasVideo: true,\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 let 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 // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter(function (sample) {\n return sample.pts >= 0;\n });\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = timeOffset * inputTimeScale;\n }\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 if (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 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 } // eslint-disable-line brace-style\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 let 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 (let 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 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\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\n firstPTS = 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 let lastSampleDuration = 0;\n let 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\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 hasAudio: true,\n hasVideo: false,\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 (let i = 0; i < nbSamples; i++) {\n let 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 let 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 (let 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 let length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if (length) {\n for (let 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 let offset;\n if (reference === undefined) {\n return value;\n }\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\n return value;\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 let observer = this.observer;\n let streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\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","/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\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\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst performance = global;\n\nclass DemuxerInline {\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 let 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\n let localthis = this;\n // performance.now() not available on WebWorker, at least on Safari Desktop\n let 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 let 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 let demuxer = this.demuxer;\n if (!demuxer ||\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n // so let's check that current demuxer is still valid\n ((discontinuity || trackSwitch) && !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: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer }\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\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\nconst FORBIDDEN_EVENT_NAMES = new Set([\n 'hlsEventGeneric',\n 'hlsHandlerDestroying',\n 'hlsHandlerDestroyed'\n]);\n\nclass EventHandler {\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.onHandlerDestroying();\n this.unregisterListeners();\n this.onHandlerDestroyed();\n }\n\n onHandlerDestroying () {}\n onHandlerDestroyed () {}\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 (FORBIDDEN_EVENT_NAMES.has(event)) {\n throw new Error('Forbidden event-name: ' + event);\n }\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 let eventToFunction = function (event, data) {\n let 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\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n logger.error(`An internal error happened while handling event ${event}. Error message: \"${err.message}\". Here is a stacktrace:`, err);\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","import URLToolkit from 'url-toolkit';\n\nexport default class LevelKey {\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\n return this._uri;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/level-key.js","\nimport URLToolkit from 'url-toolkit';\n\nimport LevelKey from './level-key';\n\nexport default class Fragment {\n constructor () {\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n this.tagList = [];\n\n // Holds the types of data this fragment supports\n this._elementaryStreams = {\n [Fragment.ElementaryStreamTypes.AUDIO]: false,\n [Fragment.ElementaryStreamTypes.VIDEO]: false\n };\n }\n\n /**\n * `type` property for this._elementaryStreams\n *\n * @enum\n */\n static get ElementaryStreamTypes () {\n return {\n AUDIO: 'audio',\n VIDEO: 'video'\n };\n }\n\n get url () {\n if (!this._url && this.relurl) {\n this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\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\n return this._programDateTime;\n }\n\n get byteRange () {\n if (!this._byteRange && !this.rawByteRange) {\n return [];\n }\n\n if (this._byteRange) {\n return this._byteRange;\n }\n\n let 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 || 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n return byteRange;\n }\n\n /**\n * @type {number}\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\n return this._decryptdata;\n }\n\n get encrypted () {\n return !!((this.decryptdata && this.decryptdata.uri !== null) && (this.decryptdata.key === null));\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n addElementaryStream (type) {\n this._elementaryStreams[type] = true;\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n hasElementaryStream (type) {\n return this._elementaryStreams[type] === true;\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 let uint8View = new Uint8Array(16);\n\n for (let 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 let 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\n\n\n// WEBPACK FOOTER //\n// ./src/loader/fragment.js","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n constructor (attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (let 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\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\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\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\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList (input) {\n let match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let 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\n attrs[match[1]] = value;\n }\n return attrs;\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 window.MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/codecs.js","\nimport URLToolkit from 'url-toolkit';\n\nimport Fragment from './fragment';\nimport LevelKey from './level-key';\n\nimport AttrList from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport { isCodecType } from '../utils/codecs';\n\n/**\n * M3U8 parser\n * @module\n */\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\nconst MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nexport default class M3U8Parser {\n static 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\n static convertAVC1ToAVCOTI (codec) {\n let 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 static resolve (url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static 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 const attrs = level.attrs = new AttrList(result[1]);\n level.url = M3U8Parser.resolve(result[2], baseurl);\n\n const 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 = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n }\n return levels;\n }\n\n static 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 = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n media.lang = attrs.LANGUAGE;\n if (!media.name) {\n media.name = media.lang;\n }\n\n if (audioGroups.length) {\n const groupCodec = M3U8Parser.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 static parseLevelPlaylist (string, baseurl, id, type, levelUrlId) {\n let 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 || 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.urlId = levelUrlId;\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 if (level.programDateTime) {\n if (prevFrag) {\n if (frag.rawProgramDateTime) { // PDT discontinuity found\n frag.pdt = Date.parse(frag.rawProgramDateTime);\n } else { // Contiguous fragment\n frag.pdt = prevFrag.pdt + (prevFrag.duration * 1000);\n }\n } else { // First fragment\n frag.pdt = Date.parse(level.programDateTime);\n }\n frag.endPdt = frag.pdt + (frag.duration * 1000);\n }\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', 'SAMPLE-AES-CENC'].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\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\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every((frag) => MP4_REGEX_SUFFIX.test(frag.relurl))) {\n logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new Fragment();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n return level;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/m3u8-parser.js","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport M3U8Parser from './m3u8-parser';\n\nconst { performance } = window;\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\nconst ContextType = {\n MANIFEST: 'manifest',\n LEVEL: 'level',\n AUDIO_TRACK: 'audioTrack',\n SUBTITLE_TRACK: 'subtitleTrack'\n};\n\n/**\n * @enum {string}\n */\nconst LevelType = {\n MAIN: 'main',\n AUDIO: 'audio',\n SUBTITLE: 'subtitle'\n};\n\n/**\n * @constructor\n */\nclass PlaylistLoader extends EventHandler {\n /**\n * @constructs\n * @param {Hls} hls\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\n this.loaders = {};\n }\n\n static get ContextType () {\n return ContextType;\n }\n\n static get LevelType () {\n return LevelType;\n }\n\n /**\n * @param {ContextType} type\n * @returns {boolean}\n */\n static canHaveQualityLevels (type) {\n return (type !== ContextType.AUDIO_TRACK &&\n type !== ContextType.SUBTITLE_TRACK);\n }\n\n /**\n * Map context.type to LevelType\n * @param {{type: ContextType}} context\n * @returns {LevelType}\n */\n static mapContextToLevelType (context) {\n const { type } = context;\n\n switch (type) {\n case ContextType.AUDIO_TRACK:\n return LevelType.AUDIO;\n case ContextType.SUBTITLE_TRACK:\n return LevelType.SUBTITLE;\n default:\n return LevelType.MAIN;\n }\n }\n\n static getResponseUrl (response, context) {\n let url = response.url;\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 return url;\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {object} context\n * @returns {XHRLoader} or other compatible configured overload\n */\n createInternalLoader (context) {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n\n const loader = new InternalLoader(config);\n\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n getInternalLoader (context) {\n return this.loaders[context.type];\n }\n\n resetInternalLoader (contextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n destroyInternalLoaders () {\n for (let contextType in this.loaders) {\n let loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n }\n\n destroy () {\n this.destroyInternalLoaders();\n\n super.destroy();\n }\n\n onManifestLoading (data) {\n this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });\n }\n\n onLevelLoading (data) {\n this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });\n }\n\n onAudioTrackLoading (data) {\n this.load(data.url, { type: ContextType.AUDIO_TRACK, level: 0, id: data.id });\n }\n\n onSubtitleTrackLoading (data) {\n this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: 0, id: data.id });\n }\n\n load (url, context) {\n const config = this.hls.config;\n\n logger.debug(`Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) { // same URL can't overlap\n logger.trace('playlist request ongoing');\n return false;\n } else {\n logger.warn(`aborting previous loader for type: ${context.type}`);\n loader.abort();\n }\n }\n\n let maxRetry,\n timeout,\n retryDelay,\n maxRetryDelay;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case ContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case ContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n context.url = url;\n context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)\n\n const loaderConfig = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay\n };\n\n const loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n logger.debug(`Calling internal loader delegate for URL: ${url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n }\n\n loadsuccess (response, stats, context, networkDetails = null) {\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n\n const string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n }\n\n loaderror (response, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails);\n }\n\n loadtimeout (stats, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, true);\n }\n\n _handleMasterPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n const string = response.data;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levels = M3U8Parser.parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n\n const audioGroups = levels.map(level => ({\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n }));\n\n let audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n let subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n\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\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // 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({\n type: 'main',\n name: 'main'\n });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n url,\n stats,\n networkDetails\n });\n }\n\n _handleTrackOrLevelPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n\n const { id, level, type } = context;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levelUrlId = isNaN(id) ? 0 : id;\n const levelId = isNaN(level) ? levelUrlId : level; // level -> id -> 0\n const levelType = PlaylistLoader.mapContextToLevelType(context);\n\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n levelDetails.tload = stats.tload;\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === ContextType.MANIFEST) {\n const singleLevel = {\n url,\n details: levelDetails\n };\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n const sidxUrl = levelDetails.initSegment.url;\n this.load(sidxUrl, {\n isSidxRequest: true,\n type,\n level,\n levelDetails,\n id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n }\n\n _handleSidxRequest (response, context) {\n const sidxInfo = MP4Demuxer.parseSegmentIndex(new Uint8Array(response.data));\n sidxInfo.references.forEach((segmentRef, index) => {\n const segRefInfo = segmentRef.info;\n const frag = context.levelDetails.fragments[index];\n\n if (frag.byteRange.length === 0) {\n frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);\n }\n });\n\n context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';\n }\n\n _handleManifestParsingError (response, context, reason, networkDetails) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason,\n networkDetails\n });\n }\n\n _handleNetworkError (context, networkDetails, timeout = false) {\n logger.info(`A network error occured while loading a ${context.type}-type playlist`);\n\n let details;\n let fatal;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case ContextType.MANIFEST:\n details = (timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR);\n fatal = true;\n break;\n case ContextType.LEVEL:\n details = (timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR);\n fatal = false;\n break;\n case ContextType.AUDIO_TRACK:\n details = (timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR);\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: loader.url,\n loader,\n context,\n networkDetails\n });\n }\n\n _handlePlaylistLoaded (response, stats, context, networkDetails) {\n const { type, level, id, levelDetails } = context;\n\n if (!levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n const canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(Event.LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats,\n networkDetails\n });\n } else {\n switch (type) {\n case ContextType.AUDIO_TRACK:\n this.hls.trigger(Event.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n case ContextType.SUBTITLE_TRACK:\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n }\n }\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 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\n super.destroy();\n }\n\n onFragLoading (data) {\n const frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n let loader = loaders[type];\n if (loader) {\n logger.warn(`abort previous fragment loader for type: ${type}`);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader =\n config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n let start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (!isNaN(start) && !isNaN(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\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\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\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 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\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\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","import EventHandler from '../event-handler';\nimport Event from '../events';\n\nexport const FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nexport class FragmentTracker extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.BUFFER_APPENDED,\n Event.FRAG_BUFFERED,\n Event.FRAG_LOADED\n );\n\n this.bufferPadding = 0.2;\n\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n\n this.config = hls.config;\n }\n\n destroy () {\n this.fragments = null;\n this.timeRanges = null;\n this.config = null;\n EventHandler.prototype.destroy.call(this);\n super.destroy();\n }\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n getBufferedFrag (position, levelType) {\n const fragments = this.fragments;\n const bufferedFrags = Object.keys(fragments).filter(key => {\n const fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n const frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n const bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n detectEvictedFragments (elementaryStream, timeRange) {\n let fragmentTimes, time;\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (fragmentEntity.buffered === true) {\n const esData = fragmentEntity.range[elementaryStream];\n if (esData) {\n fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n time = fragmentTimes[i];\n\n if (this.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n break;\n }\n }\n }\n }\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n detectPartialFragments (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n if (fragment.hasElementaryStream(elementaryStream) === true) {\n let timeRange = this.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n }\n\n getBufferedTimes (startPTS, endPTS, timeRange) {\n let fragmentTimes = [];\n let startTime, endTime;\n let fragmentPartial = false;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n }\n\n getFragmentKey (fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n }\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n getPartialFragment (time) {\n let timePadding, startTime, endTime;\n let bestFragment = null;\n let bestOverlap = 0;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (this.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - this.bufferPadding;\n endTime = fragmentEntity.body.endPTS + this.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n getState (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n let state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n }\n\n isPartial (fragmentEntity) {\n return fragmentEntity.buffered === true &&\n ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||\n (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));\n }\n\n isTimeBuffered (startPTS, endPTS, timeRange) {\n let startTime, endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n /**\n * Fires when a fragment loading is completed\n */\n onFragLoaded (e) {\n let fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!isNaN(fragment.sn) && !fragment.bitrateTest) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n this.fragments[fragKey] = fragmentEntity;\n }\n }\n\n /**\n * Fires when the buffer is updated\n */\n onBufferAppended (e) {\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n let timeRange = this.timeRanges[elementaryStream];\n this.detectEvictedFragments(elementaryStream, timeRange);\n });\n }\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n onFragBuffered (e) {\n this.detectPartialFragments(e.frag);\n }\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n hasFragment (fragment) {\n const fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n }\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n removeFragment (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n }\n\n /**\n * Remove all fragments from fragment tracker.\n */\n removeAllFragments () {\n this.fragments = Object.create(null);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fragment-tracker.js","let 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 let minIndex = 0;\n let maxIndex = list.length - 1;\n let currentIndex = null;\n let currentElement = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n\n let comparisonResult = comparisonFunction(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\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 * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n * @param {HTMLMediaElement|SourceBuffer} media\n * @param {number} position\n * @returns {boolean}\n */\n static isBuffered (media, position) {\n try {\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 } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo (media, pos, maxHoleDuration) {\n try {\n if (media) {\n let 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\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo (buffered, pos, maxHoleDuration) {\n let 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 let 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 let buf2len = buffered2.length;\n if (buf2len) {\n let 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 let start = buffered2[i].start,\n end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/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/utils/mediasource-helper.js","import EventEmitter from 'events';\nimport work from 'webworkify-webpack';\n\nimport Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst MediaSource = getMediaSource();\n\nclass Demuxer {\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 let 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) {\n 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 };\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 global.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\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\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 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 global.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\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// WEBPACK FOOTER //\n// ./src/demux/demuxer.js","/**\n * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\nimport { logger } from '../utils/logger';\n\nexport function addGroupId (level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nexport function updatePTS (fragments, fromIdx, toIdx) {\n let 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\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\n let 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\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 let 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 // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\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 let 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 let 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/controller/level-helper.js","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r) {\n let log = '', len = r.length;\n for (let i = 0; i < len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n\n return log;\n }\n};\n\nexport default TimeRanges;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/time-ranges.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 && lastLevel.details.fragments && lastLevel.details.fragments.length) {\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","import EventHandler from './event-handler';\n\n/**\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\n\nexport default class TaskLoop extends EventHandler {\n constructor (hls, ...events) {\n super(hls, ...events);\n\n this._tickInterval = null;\n this._tickTimer = null;\n this._tickCallCount = 0;\n this._boundTick = this.tick.bind(this);\n }\n\n /**\n * @override\n */\n onHandlerDestroying () {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n /**\n * @returns {boolean}\n */\n hasInterval () {\n return !!this._tickInterval;\n }\n\n /**\n * @returns {boolean}\n */\n hasNextTick () {\n return !!this._tickTimer;\n }\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n */\n setInterval (millis) {\n if (!this._tickInterval) {\n this._tickInterval = setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n */\n clearInterval () {\n if (this._tickInterval) {\n clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n clearNextTick () {\n if (this._tickTimer) {\n clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n tick () {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.clearNextTick();\n this._tickTimer = setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n doTick () {}\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/task-loop.js","import BinarySearch from '../utils/binary-search';\n\n/**\n * Calculates the PDT of the next load position.\n * bufferEnd in this function is usually the position of the playhead.\n * @param {number} [start = 0] - The PTS of the first fragment within the level\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level\n * @returns {number} nextPdt - The computed PDT\n */\nexport function calculateNextPDT (start = 0, bufferEnd = 0, levelDetails) {\n let pdt = 0;\n if (levelDetails.programDateTime) {\n const parsedDateInt = Date.parse(levelDetails.programDateTime);\n if (!isNaN(parsedDateInt)) {\n pdt = (bufferEnd * 1000) + parsedDateInt - (1000 * start);\n }\n }\n return pdt;\n}\n\n/**\n * Finds the first fragment whose endPDT value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @returns {*|null} fragment - The best matching fragment\n */\nexport function findFragmentByPDT (fragments, PDTValue = null) {\n if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) {\n return null;\n }\n\n // if less than start\n let firstSegment = fragments[0];\n\n if (PDTValue < firstSegment.pdt) {\n return null;\n }\n\n let lastSegment = fragments[fragments.length - 1];\n\n if (PDTValue >= lastSegment.endPdt) {\n return null;\n }\n\n for (let seg = 0; seg < fragments.length; ++seg) {\n let frag = fragments[seg];\n if (PDTValue < frag.endPdt) {\n return frag;\n }\n }\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} [end = 0] - The computed end time of the stream\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nexport function findFragmentBySN (fragPrevious, fragments, bufferEnd = 0, end = 0, maxFragLookUpTolerance = 0) {\n let foundFrag;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n }\n }\n return foundFrag;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest (bufferEnd = 0, maxFragLookUpTolerance = 0, 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 } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fragment-finders.js","/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment from '../loader/fragment';\nimport PlaylistLoader from '../loader/playlist-loader';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { alignDiscontinuities } from '../utils/discontinuities';\nimport TaskLoop from '../task-loop';\nimport { calculateNextPDT, findFragmentByPDT, findFragmentBySN, fragmentWithinToleranceTest } from './fragment-finders';\n\nexport const 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 TaskLoop {\n constructor (hls, fragmentTracker) {\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.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.stallReported = false;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n super.onHandlerDestroyed();\n }\n\n startLoad (startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n this.setInterval(100);\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 let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.clearInterval();\n this.state = State.STOPPED;\n this.forceStartLoad = false;\n }\n\n doTick () {\n switch (this.state) {\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\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log('mediaController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle () {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n // if 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\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\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 (!levelDetails || (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\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 } 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\n if (frag) {\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);\n this._loadKey(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 this._loadFragment(frag);\n }\n }\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\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 if (!levelDetails.programDateTime) { // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\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 } else { // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPDT(fragments, fragPrevious.endPdt + 1);\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 const fragBySN = () => findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n let frag;\n let foundFrag;\n\n if (bufferEnd < end) {\n if (!levelDetails.programDateTime) { // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n } else {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = findFragmentByPDT(fragments, calculateNextPDT(start, bufferEnd, levelDetails));\n if (!foundFrag || fragmentWithinToleranceTest(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) {\n // Fall back to SN order if finding by PDT returns a frag which won't fit within the stream\n // fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise\n logger.warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN');\n foundFrag = fragBySN();\n }\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 } 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 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 _loadKey (frag) {\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\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\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n this.hls.trigger(Event.FRAG_LOADING, { 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(this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\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 this.fragmentTracker.getBufferedFrag(position, PlaylistLoader.LevelType.MAIN);\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 let 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 > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\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 let 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\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 let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\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 const 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 /**\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 nextLevelSwitch () {\n const 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 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 let 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 let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\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\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached (data) {\n let 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 let 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 backtracked flag\n let levels = this.levels;\n if (levels) {\n levels.forEach(level => {\n if (level.details) {\n level.details.fragments.forEach(fragment => {\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\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\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\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\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\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 onManifestLoading () {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed (data) {\n let 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\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\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 let 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\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 let 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 const stats = data.stats;\n const currentLevel = this.levels[fragCurrent.level];\n const 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 = window.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 = window.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\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\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\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let 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\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n let 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 let 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 let 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 if (data.hasAudio === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.VIDEO);\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', frag.sn);\n } else {\n logger.warn('missing video frame(s), backtracking fragment', frag.sn);\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 this.fragmentTracker.removeFragment(frag);\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', frag.sn);\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 let 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 // 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 = window.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 let 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 let 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 onBufferCreated (data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for (let 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 this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = window.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\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 logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = window.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.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 return true;\n }\n return false;\n }\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n _checkBuffer () {\n const { config, media } = this;\n const stallDebounceInterval = 1000;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n const currentTime = media.currentTime;\n const mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n const buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n const expectedPlaying = !((media.paused && media.readyState > 1) || // not playing when media is paused and sufficiently buffered\n media.ended || // not playing when media is ended\n media.buffered.length === 0); // not playing if nothing buffered\n const tnow = window.performance.now();\n\n if (currentTime !== this.lastCurrentTime) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(tnow - this.stalled)}ms`);\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n } else if (expectedPlaying) {\n // The playhead isn't moving but it should be\n // Allow some slack time to for small stalls to resolve themselves\n const stalledDuration = tnow - this.stalled;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);\n if (!this.stalled) {\n this.stalled = tnow;\n return;\n } else if (stalledDuration >= stallDebounceInterval) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n this._tryFixBufferStall(bufferInfo, stalledDuration);\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 if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n this.fragmentTracker.detectEvictedFragments(Fragment.ElementaryStreamTypes.VIDEO, media.buffered);\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 /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDuration - The amount of time Hls.js has been stalling for.\n * @private\n */\n _tryFixBufferStall (bufferInfo, stalledDuration) {\n const { config, media } = this;\n const currentTime = media.currentTime;\n const jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end\n\n const partial = this.fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n this._trySkipBufferHole(partial);\n }\n\n if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n _reportStall (bufferLen) {\n const { hls, media, stallReported } = this;\n if (!stallReported) {\n // Report stalled error once\n this.stallReported = true;\n logger.warn(`Playback stalling at @${media.currentTime} due to low buffer`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n _trySkipBufferHole (partial) {\n const { hls, media } = this;\n const currentTime = media.currentTime;\n let lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (let i = 0; i < media.buffered.length; i++) {\n let startTime = media.buffered.start(i);\n if (currentTime >= lastEndTime && currentTime < startTime) {\n media.currentTime = Math.max(startTime, media.currentTime + 0.1);\n logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${media.currentTime}`);\n this.stalled = null;\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${media.currentTime}`,\n frag: partial\n });\n return;\n }\n lastEndTime = media.buffered.end(i);\n }\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n _tryNudgeBuffer () {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n const nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\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, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, raise fatal error`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n _seekToStartPos () {\n const { media } = this;\n const currentTime = media.currentTime;\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 const startPosition = media.seeking ? currentTime : this.startPosition;\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition) {\n // if startPosition not buffered, let's seek to buffered.start(0)\n logger.log(`target start position not buffered, seek to buffered.start(0) ${startPosition} from current time ${currentTime} `);\n media.currentTime = startPosition;\n }\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// 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';\nimport { addGroupId } from './level-helper';\n\nconst { performance } = window;\n\nexport default class LevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.FRAG_LOADED,\n Event.ERROR);\n\n this.canload = false;\n this.currentLevelIndex = null;\n this.manualLevelIndex = -1;\n this.timer = null;\n }\n\n onHandlerDestroying () {\n this.clearTimer();\n this.manualLevelIndex = -1;\n }\n\n clearTimer () {\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 !== null) {\n this.loadLevel();\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 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (level.attrs && level.attrs.AUDIO) {\n addGroupId(levelFromSet || level, 'audio', level.attrs.AUDIO);\n }\n\n if (level.attrs && level.attrs.SUBTITLES) {\n addGroupId(levelFromSet || level, 'text', level.attrs.SUBTITLES);\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\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 > 0) {\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, {\n levels,\n audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: audioTracks.length > 0 && videoCodecFound\n });\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.currentLevelIndex;\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.currentLevelIndex !== newLevel || !levels[newLevel].details) {\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.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this.currentLevelIndex = newLevel;\n const levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n const level = levels[newLevel];\n const levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n let 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, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n }\n\n get manualLevel () {\n return this.manualLevelIndex;\n }\n\n set manualLevel (newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel () {\n return this._firstLevel;\n }\n\n set firstLevel (newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel () {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel (newLevel) {\n this._startLevel = newLevel;\n }\n\n onError (data) {\n if (data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n let levelError = false, fragmentError = false;\n let levelIndex;\n\n // try to recover not fatal errors\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 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 levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {\n let { config } = this.hls;\n let { details: errorDetails } = errorEvent;\n let level = this._levels[levelIndex];\n let redundantLevels, delay, nextLevel;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(() => this.loadLevel(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`level controller, cannot recover from ${errorDetails} error`);\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;\n logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n logger.warn(`level controller, ${errorDetails}: reload a fragment`);\n this.currentLevelIndex = null;\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.currentLevelIndex) {\n return;\n }\n\n const 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) {\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 const targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration);\n let reloadInterval = targetdurationMs,\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 half of target duration\n reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval));\n logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);\n this.timer = setTimeout(() => this.loadLevel(), reloadInterval);\n } else {\n this.clearTimer();\n }\n }\n\n onAudioTrackSwitched (data) {\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n const urlId = currentLevel.audioGroupIds.findIndex((groupId) => groupId === audioGroupId);\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n loadLevel () {\n logger.debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n const levelObject = this._levels[this.currentLevelIndex];\n\n if (typeof levelObject === 'object' &&\n levelObject.url.length > 0) {\n const level = this.currentLevelIndex;\n const id = levelObject.urlId;\n const url = levelObject.url[id];\n\n logger.log(`Attempt loading level index ${level} with URL-id ${id}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });\n }\n }\n }\n\n get nextLoadLevel () {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel (nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/level-controller.js","\nexport function sendAddTrackEvent (track, videoEl) {\n let event = null;\n try {\n event = new window.Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n event.track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function clearCurrentCues (track) {\n if (track && track.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/texttrack-utils.js","/*\n * id3 metadata track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport ID3 from '../demux/id3';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\n\nclass ID3TrackController extends EventHandler {\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\n }\n }\n\n onMediaDetaching () {\n clearCurrentCues(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n getID3Track (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n let textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\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.getID3Track(this.media.textTracks);\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","import { getMediaSource } from './utils/mediasource-helper';\n\nexport function 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\n\n// WEBPACK FOOTER //\n// ./src/is-supported.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 // 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 let 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 let 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\nclass EwmaBandWidthEstimator {\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 let 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 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// 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 '../utils/buffer-helper';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\n\nconst { performance } = window;\n\nclass AbrController extends EventHandler {\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 const frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, 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 const hls = this.hls;\n const config = hls.config;\n const level = frag.level;\n const isLive = hls.levels[level].details.live;\n\n let ewmaFast, ewmaSlow;\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 }\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 const hls = this.hls;\n const video = hls.media;\n const frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n const loader = frag.loader;\n const 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 // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\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 (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {\n let requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(video.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 = video.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (BufferHelper.bufferInfo(video, 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 const 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 const stats = data.stats;\n const 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.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\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\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel () {\n let hls = this.hls, maxAutoLevel = hls.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = hls.minAutoLevel;\n const video = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = (video ? video.currentTime : 0),\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.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(video, 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\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// 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 '../utils/mediasource-helper';\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\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 // current stream state: true - for live broadcast, false - for VoD content\n this._live = null;\n // cache the self generated object url to detect hijack of video tag\n this._objectUrl = 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.altAudio),\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 let 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 = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n }\n\n onMediaDetaching () {\n logger.log('media source detaching');\n let 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 window.URL.revokeObjectURL(this._objectUrl);\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n logger.warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = 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 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\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\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n let timeRanges = {};\n const sourceBuffer = this.sourceBuffer;\n for (let streamType in sourceBuffer) {\n timeRanges[streamType] = sourceBuffer[streamType].buffered;\n }\n\n this.hls.trigger(Event.BUFFER_APPENDED, { parent, pending, timeRanges });\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 let sourceBuffer = this.sourceBuffer;\n for (let type in sourceBuffer) {\n let 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 (let 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 createSourceBuffers (tracks) {\n let 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\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 let 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 let 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\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 onBufferFlushing (data) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n onLevelUpdated ({ details }) {\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n updateMediaElementDuration () {\n let { config } = this.hls;\n let duration;\n\n if (this._levelDuration === null ||\n !this.media ||\n !this.mediaSource ||\n !this.sourceBuffer ||\n this.media.readyState === 0 ||\n this.mediaSource.readyState !== 'open') {\n return;\n }\n\n for (let type in this.sourceBuffer) {\n if (this.sourceBuffer[type].updating === true) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n\n duration = this.media.duration;\n // initialise to the value that the media source is reporting\n if (this._msDuration === null) {\n this._msDuration = this.mediaSource.duration;\n }\n\n if (this._live === true && config.liveDurationInfinity === true) {\n // Override duration to Infinity\n logger.log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if ((this._levelDuration > this._msDuration && this._levelDuration > duration) ||\n (duration === Infinity || isNaN(duration))) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(`Updating Media Source duration to ${this._levelDuration.toFixed(3)}`);\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n }\n\n doFlush () {\n // loop through all buffer ranges to flush\n while (this.flushRange.length) {\n let 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 let appended = 0;\n let sourceBuffer = this.sourceBuffer;\n try {\n for (let 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 let 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 let 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\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 } 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 }\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 let 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 (let 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\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 constructor (hls) {\n super(hls,\n Event.FPS_DROP_LEVEL_CAPPING,\n Event.MEDIA_ATTACHING,\n Event.MANIFEST_PARSED,\n Event.BUFFER_CODECS);\n\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = null;\n this.levels = [];\n this.media = null;\n this.restrictedLevels = [];\n this.timer = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this._stopCapping();\n }\n }\n\n onFpsDropLevelCapping (data) {\n // 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 onMediaAttaching (data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed (data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && (data.video || (data.levels.length && data.altAudio))) {\n // Start capping immediately if the manifest has signaled video codecs\n this._startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs (data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this._startCapping();\n }\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\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 _startCapping () {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n _stopCapping () {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\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\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\nconst { performance } = window;\n\nclass FPSController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy () {\n if (this.timer) {\n clearInterval(this.timer);\n }\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 window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\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// WEBPACK FOOTER //\n// ./src/controller/fps-controller.js","/**\n * XHR based logger\n*/\n\nimport { logger } from '../utils/logger';\n\nconst { performance, XMLHttpRequest } = window;\n\nclass XhrLoader {\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 let 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 let 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\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 let 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\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 let xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\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","const requestMediaKeySystemAccess = (function () {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {\n return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);\n } else {\n return null;\n }\n})();\n\nexport {\n requestMediaKeySystemAccess\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/mediakeys-helper.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';\nimport EMEController from './controller/eme-controller';\n\nimport { requestMediaKeySystemAccess } from './utils/mediakeys-helper';\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\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 liveDurationInfinity: false, // used by buffer-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 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, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\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 emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n requestMediaKeySystemAccessFunc:\n requestMediaKeySystemAccess // used by eme-controller\n};\n\nif (__USE_SUBTITLES__) {\n hlsDefaultConfig.subtitleStreamController = SubtitleStreamController;\n hlsDefaultConfig.subtitleTrackController = SubtitleTrackController;\n hlsDefaultConfig.timelineController = TimelineController;\n hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller\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 (__USE_ALT_AUDIO__) {\n hlsDefaultConfig.audioStreamController = AudioStreamController;\n hlsDefaultConfig.audioTrackController = AudioTrackController;\n}\n\nif (__USE_EME_DRM__) {\n hlsDefaultConfig.emeController = EMEController;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/config.js","import URLToolkit from 'url-toolkit';\n\nimport {\n ErrorTypes,\n ErrorDetails\n} from './errors';\n\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { hlsDefaultConfig } from './config';\n\nimport HlsEvents from './events';\nimport EventEmitter from 'events';\n\n// polyfill for IE11\nrequire('string.prototype.endswith');\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\nexport default class Hls {\n /**\n * @type {string}\n */\n static get version () {\n return __VERSION__;\n }\n\n /**\n * @type {boolean}\n */\n static isSupported () {\n return isSupported();\n }\n\n /**\n * @type {HlsEvents}\n */\n static get Events () {\n return HlsEvents;\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n static get ErrorTypes () {\n return ErrorTypes;\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n static get ErrorDetails () {\n return ErrorDetails;\n }\n\n /**\n * @type {HlsConfig}\n */\n static get DefaultConfig () {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n static set DefaultConfig (defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n constructor (config = {}) {\n let 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 (let 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 let 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.once = observer.once.bind(observer);\n this.trigger = observer.trigger.bind(observer);\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n const abrController = this.abrController = new config.abrController(this);\n\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\n /**\n * @member {LevelController} levelController\n */\n const levelController = this.levelController = new LevelController(this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n\n /**\n * @member {StreamController} streamController\n */\n const streamController = this.streamController = new StreamController(this, fragmentTracker);\n\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n const coreComponents = [\n playListLoader,\n fragmentLoader,\n keyLoader,\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker\n ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n const audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n const subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n coreComponents.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n const emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\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\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n destroy () {\n logger.log('destroy');\n this.trigger(HlsEvents.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {\n component.destroy();\n });\n this.url = null;\n this.observer.removeAllListeners();\n this._autoLevelCapping = -1;\n }\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n attachMedia (media) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(HlsEvents.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach from the media\n */\n detachMedia () {\n logger.log('detachMedia');\n this.trigger(HlsEvents.MEDIA_DETACHING);\n this.media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\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(HlsEvents.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n startLoad (startPosition = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach(controller => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad () {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec () {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError () {\n logger.log('recoverMediaError');\n let media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n }\n\n /**\n * @type {QualityLevel[]}\n */\n get levels () {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel () {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @type {number} -1 for automatic level selection\n */\n set currentLevel (newLevel) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n get nextLevel () {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n set nextLevel (newLevel) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n get loadLevel () {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n set loadLevel (newLevel) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n get nextLoadLevel () {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n set nextLoadLevel (level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n get firstLevel () {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n set firstLevel (newLevel) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\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\n * (determined from download of first segment)\n * @type {number}\n */\n get startLevel () {\n return this.levelController.startLevel;\n }\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\n * (determined from download of first segment)\n * @type {number} newLevel\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\n hls.levelController.startLevel = newLevel;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n get autoLevelCapping () {\n return this._autoLevelCapping;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n set autoLevelCapping (newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n get autoLevelEnabled () {\n return (this.levelController.manualLevel === -1);\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n get manualLevel () {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\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 /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\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\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\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 /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * 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,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n set nextAutoLevel (nextLevel) {\n const hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n get audioTracks () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n get audioTrack () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n set audioTrack (audioTrackId) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n get liveSyncPosition () {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n get subtitleTracks () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n get subtitleTrack () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type{number}\n */\n set subtitleTrack (subtitleTrackId) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n get subtitleDisplay () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\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\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\((\\/\\\\*.*?\\\\*\\/)?\\s?.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_modules__\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\\n'\n })\n\n src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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 = 11\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\nimport DemuxerInline from '../demux/demuxer-inline';\nimport Event from '../events';\nimport { enableLogs } from '../utils/logger';\nimport EventEmitter from 'events';\n\nlet DemuxerWorker = function (self) {\n // observer setup\n let 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 let forwardMessage = function (ev, data) {\n self.postMessage({ event: ev, data: data });\n };\n\n self.addEventListener('message', function (ev) {\n let 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// WEBPACK FOOTER //\n// ./src/demux/demuxer-worker.js","/*! http://mths.be/endswith v0.2.0 by @mathias */\nif (!String.prototype.endsWith) {\n\t(function() {\n\t\t'use strict'; // needed to support `apply`/`call` with `undefined`/`null`\n\t\tvar defineProperty = (function() {\n\t\t\t// IE 8 only supports `Object.defineProperty` on DOM elements\n\t\t\ttry {\n\t\t\t\tvar object = {};\n\t\t\t\tvar $defineProperty = Object.defineProperty;\n\t\t\t\tvar result = $defineProperty(object, object, object) && $defineProperty;\n\t\t\t} catch(error) {}\n\t\t\treturn result;\n\t\t}());\n\t\tvar toString = {}.toString;\n\t\tvar endsWith = function(search) {\n\t\t\tif (this == null) {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar string = String(this);\n\t\t\tif (search && toString.call(search) == '[object RegExp]') {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar stringLength = string.length;\n\t\t\tvar searchString = String(search);\n\t\t\tvar searchLength = searchString.length;\n\t\t\tvar pos = stringLength;\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tvar position = arguments[1];\n\t\t\t\tif (position !== undefined) {\n\t\t\t\t\t// `ToInteger`\n\t\t\t\t\tpos = position ? Number(position) : 0;\n\t\t\t\t\tif (pos != pos) { // better `isNaN`\n\t\t\t\t\t\tpos = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar end = Math.min(Math.max(pos, 0), stringLength);\n\t\t\tvar start = end - searchLength;\n\t\t\tif (start < 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar index = -1;\n\t\t\twhile (++index < searchLength) {\n\t\t\t\tif (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\tif (defineProperty) {\n\t\t\tdefineProperty(String.prototype, 'endsWith', {\n\t\t\t\t'value': endsWith,\n\t\t\t\t'configurable': true,\n\t\t\t\t'writable': true\n\t\t\t});\n\t\t} else {\n\t\t\tString.prototype.endsWith = endsWith;\n\t\t}\n\t}());\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/string.prototype.endswith/endswith.js\n// module id = 13\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls.light.min.js b/grails-app/assets/bower/hls.js/dist/hls.light.min.js new file mode 100644 index 000000000..3f9bb2648 --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls.light.min.js @@ -0,0 +1,3 @@ +!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=23)}([function(t,e,r){"use strict";function i(){}function a(t,e){return e="["+t+"] > "+e}function n(t){var e=f.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(f.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 c}),r.d(e,"b",function(){return h});var s=r(5),l="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},d={trace:i,debug:i,log:i,warn:i,info:i,error:i},u=d,f=Object(s.a)(),c=function(t){if(!0===t||"object"===(void 0===t?"undefined":l(t))){o(t,"debug","log","info","warn","error");try{u.log()}catch(t){u=d}}else u=d},h=u},function(t,e,r){"use strict";var i={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_SWITCHING:"hlsLevelSwitching",LEVEL_SWITCHED:"hlsLevelSwitched",LEVEL_LOADING:"hlsLevelLoading",LEVEL_LOADED:"hlsLevelLoaded",LEVEL_UPDATED:"hlsLevelUpdated",LEVEL_PTS_UPDATED:"hlsLevelPtsUpdated",AUDIO_TRACKS_UPDATED:"hlsAudioTracksUpdated",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"};e.a=i},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",KEY_SYSTEM_ERROR:"keySystemError",MUX_ERROR:"muxError",OTHER_ERROR:"otherError"},a={KEY_SYSTEM_NO_KEYS:"keySystemNoKeys",KEY_SYSTEM_NO_ACCESS:"keySystemNoAccess",KEY_SYSTEM_NO_SESSION:"keySystemNoSession",KEY_SYSTEM_LICENSE_REQUEST_FAILED:"keySystemLicenseRequestFailed",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_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")}var a=r(0),n=r(2),o=r(1),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=new Set(["hlsEventGeneric","hlsHandlerDestroying","hlsHandlerDestroyed"]),d=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.onHandlerDestroying(),this.unregisterListeners(),this.onHandlerDestroyed()},t.prototype.onHandlerDestroying=function(){},t.prototype.onHandlerDestroyed=function(){},t.prototype.isEventHandler=function(){return"object"===s(this.handledEvents)&&this.handledEvents.length&&"function"==typeof this.onEvent},t.prototype.registerListeners=function(){this.isEventHandler()&&this.handledEvents.forEach(function(t){if(l.has(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){a.b.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),this.hls.trigger(o.a.ERROR,{type:n.b.OTHER_ERROR,details:n.a.INTERNAL_EXCEPTION,fatal:!1,event:t,err:e})}},t}();e.a=d},function(t,e){t.exports=void 0},function(t,e,r){"use strict";function i(){return"undefined"==typeof window?self:window}e.a=i},function(t,e,r){!function(e){var r=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,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 d={scheme:s.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(d.netLoc=s.netLoc,"/"!==n.path[0]))if(n.path){var u=s.path,f=u.substring(0,u.lastIndexOf("/")+1)+n.path;d.path=o.normalizePath(f)}else d.path=s.path,n.params||(d.params=s.params,n.query||(d.query=s.query));return null===d.path&&(d.path=r.alwaysNormalize?o.normalizePath(n.path):n.path),o.buildURLFromParts(d)},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";var i={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}};e.a=i},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,d;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 u=new Error('Uncaught, unspecified "error" event. ('+e+")");throw u.context=e,u}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),d=r.slice(),a=d.length,l=0;l<a;l++)d[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){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}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,!0),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=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t.length,i=void 0,a=void 0,n=void 0,o="",s=0;s<r;){if(0===(i=t[s++])&&e)return o;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:a=t[s++],o+=String.fromCharCode((31&i)<<6|63&a);break;case 14:a=t[s++],n=t[s++],o+=String.fromCharCode((15&i)<<12|(63&a)<<6|(63&n)<<0)}}return o},t}();a._utf8ArrayToStr;e.a=a},function(t,e,r){"use strict";function i(){if("undefined"!=typeof window)return window.MediaSource||window.WebKitMediaSource}e.a=i},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)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)}var o=r(1),s=r(3),l=r(2),d=r(0),u=r(12),f=r(24),c=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}}(),h=window,p=h.performance,v={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},g={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},m=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MANIFEST_LOADING,o.a.LEVEL_LOADING,o.a.AUDIO_TRACK_LOADING,o.a.SUBTITLE_TRACK_LOADING));return n.loaders={},n}return n(e,t),e.canHaveQualityLevels=function(t){return t!==v.AUDIO_TRACK&&t!==v.SUBTITLE_TRACK},e.mapContextToLevelType=function(t){switch(t.type){case v.AUDIO_TRACK:return g.AUDIO;case v.SUBTITLE_TRACK:return g.SUBTITLE;default:return g.MAIN}},e.getResponseUrl=function(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r},e.prototype.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,a=r||i,n=new a(e);return t.loader=n,this.loaders[t.type]=n,n},e.prototype.getInternalLoader=function(t){return this.loaders[t.type]},e.prototype.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.prototype.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.prototype.destroy=function(){this.destroyInternalLoaders(),t.prototype.destroy.call(this)},e.prototype.onManifestLoading=function(t){this.load(t.url,{type:v.MANIFEST,level:0,id:null})},e.prototype.onLevelLoading=function(t){this.load(t.url,{type:v.LEVEL,level:t.level,id:t.id})},e.prototype.onAudioTrackLoading=function(t){this.load(t.url,{type:v.AUDIO_TRACK,level:0,id:t.id})},e.prototype.onSubtitleTrackLoading=function(t){this.load(t.url,{type:v.SUBTITLE_TRACK,level:0,id:t.id})},e.prototype.load=function(t,e){var r=this.hls.config;d.b.debug("Loading playlist of type "+e.type+", level: "+e.level+", id: "+e.id);var i=this.getInternalLoader(e);if(i){var a=i.context;if(a&&a.url===t)return d.b.trace("playlist request ongoing"),!1;d.b.warn("aborting previous loader for type: "+e.type),i.abort()}var n=void 0,o=void 0,s=void 0,l=void 0;switch(e.type){case v.MANIFEST:n=r.manifestLoadingMaxRetry,o=r.manifestLoadingTimeOut,s=r.manifestLoadingRetryDelay,l=r.manifestLoadingMaxRetryTimeout;break;case v.LEVEL:n=0,o=r.levelLoadingTimeOut;break;default:n=r.levelLoadingMaxRetry,o=r.levelLoadingTimeOut,s=r.levelLoadingRetryDelay,l=r.levelLoadingMaxRetryTimeout}i=this.createInternalLoader(e),e.url=t,e.responseType=e.responseType||"";var u={timeout:o,maxRetry:n,retryDelay:s,maxRetryDelay:l},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};return d.b.debug("Calling internal loader delegate for URL: "+t),i.load(e,u,f),!0},e.prototype.loadsuccess=function(t,e,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(r.isSidxRequest)return this._handleSidxRequest(t,r),void this._handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var a=t.data;if(e.tload=p.now(),0!==a.indexOf("#EXTM3U"))return void this._handleManifestParsingError(t,r,"no EXTM3U delimiter",i);a.indexOf("#EXTINF:")>0||a.indexOf("#EXT-X-TARGETDURATION:")>0?this._handleTrackOrLevelPlaylist(t,e,r,i):this._handleMasterPlaylist(t,e,r,i)},e.prototype.loaderror=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this._handleNetworkError(e,r)},e.prototype.loadtimeout=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this._handleNetworkError(e,r,!0)},e.prototype._handleMasterPlaylist=function(t,r,i,a){var n=this.hls,s=t.data,l=e.getResponseUrl(t,i),u=f.a.parseMasterPlaylist(s,l);if(!u.length)return void this._handleManifestParsingError(t,i,"no level found in manifest",a);var c=u.map(function(t){return{id:t.attrs.AUDIO,codec:t.audioCodec}}),h=f.a.parseMasterPlaylistMedia(s,l,"AUDIO",c),p=f.a.parseMasterPlaylistMedia(s,l,"SUBTITLES");if(h.length){var v=!1;h.forEach(function(t){t.url||(v=!0)}),!1===v&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(d.b.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),h.unshift({type:"main",name:"main"}))}n.trigger(o.a.MANIFEST_LOADED,{levels:u,audioTracks:h,subtitles:p,url:l,stats:r,networkDetails:a})},e.prototype._handleTrackOrLevelPlaylist=function(t,r,i,a){var n=this.hls,s=i.id,l=i.level,d=i.type,u=e.getResponseUrl(t,i),c=isNaN(s)?0:s,h=isNaN(l)?c:l,g=e.mapContextToLevelType(i),m=f.a.parseLevelPlaylist(t.data,u,h,g,c);if(m.tload=r.tload,d===v.MANIFEST){var y={url:u,details:m};n.trigger(o.a.MANIFEST_LOADED,{levels:[y],audioTracks:[],url:u,stats:r,networkDetails:a})}if(r.tparsed=p.now(),m.needSidxRanges){var b=m.initSegment.url;return void this.load(b,{isSidxRequest:!0,type:d,level:l,levelDetails:m,id:s,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer"})}i.levelDetails=m,this._handlePlaylistLoaded(t,r,i,a)},e.prototype._handleSidxRequest=function(t,e){var r=u.a.parseSegmentIndex(new Uint8Array(t.data));r.references.forEach(function(t,r){var i=t.info,a=e.levelDetails.fragments[r];0===a.byteRange.length&&(a.rawByteRange=String(1+i.end-i.start)+"@"+String(i.start))}),e.levelDetails.initSegment.rawByteRange=String(r.moovEndOffset)+"@0"},e.prototype._handleManifestParsingError=function(t,e,r,i){this.hls.trigger(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.a.MANIFEST_PARSING_ERROR,fatal:!0,url:t.url,reason:r,networkDetails:i})},e.prototype._handleNetworkError=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];d.b.info("A network error occured while loading a "+t.type+"-type playlist");var i=void 0,a=void 0,n=this.getInternalLoader(t);switch(t.type){case v.MANIFEST:i=r?l.a.MANIFEST_LOAD_TIMEOUT:l.a.MANIFEST_LOAD_ERROR,a=!0;break;case v.LEVEL:i=r?l.a.LEVEL_LOAD_TIMEOUT:l.a.LEVEL_LOAD_ERROR,a=!1;break;case v.AUDIO_TRACK:i=r?l.a.AUDIO_TRACK_LOAD_TIMEOUT:l.a.AUDIO_TRACK_LOAD_ERROR,a=!1;break;default:a=!1}n&&(n.abort(),this.resetInternalLoader(t.type)),this.hls.trigger(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:i,fatal:a,url:n.url,loader:n,context:t,networkDetails:e})},e.prototype._handlePlaylistLoaded=function(t,r,i,a){var n=i.type,s=i.level,l=i.id,d=i.levelDetails;if(!d.targetduration)return void this._handleManifestParsingError(t,i,"invalid target duration",a);if(e.canHaveQualityLevels(i.type))this.hls.trigger(o.a.LEVEL_LOADED,{details:d,level:s||0,id:l||0,stats:r,networkDetails:a});else switch(n){case v.AUDIO_TRACK:this.hls.trigger(o.a.AUDIO_TRACK_LOADED,{details:d,id:l,stats:r,networkDetails:a});break;case v.SUBTITLE_TRACK:this.hls.trigger(o.a.SUBTITLE_TRACK_LOADED,{details:d,id:l,stats:r,networkDetails:a})}},c(e,null,[{key:"ContextType",get:function(){return v}},{key:"LevelType",get:function(){return g}}]),e}(s.a);e.a=m},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(0),n=r(1),o=Math.pow(2,32)-1,s=function(){function t(e,r){i(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 o=this.initData=t.parseInitSegment(e);null==r&&(r="mp4a.40.5"),null==i&&(i="avc1.42e01e");var s={};o.audio&&o.video?s.audiovideo={container:"video/mp4",codec:r+","+i,initSegment:a?e:null}:(o.audio&&(s.audio={container:"audio/mp4",codec:r,initSegment:a?e:null}),o.video&&(s.video={container:"video/mp4",codec:i,initSegment:a?e:null})),this.observer.trigger(n.a.FRAG_PARSING_INIT_SEGMENT,{tracks:s})}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.readUint16=function(t,e){t.data&&(e+=t.start,t=t.data);var r=t[e]<<8|t[e+1];return r<0?65536+r:r},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=void 0,n=void 0,o=void 0,s=void 0,l=void 0,d=void 0,u=void 0;if(e.data?(d=e.start,s=e.end,e=e.data):(d=0,s=e.byteLength),!r.length)return null;for(a=d;a<s;)n=t.readUint32(e,a),o=t.bin2str(e.subarray(a+4,a+8)),u=n>1?a+n:s,o===r[0]&&(1===r.length?i.push({data:e,start:a+8,end:u}):(l=t.findBox({data:e,start:a+8,end:u},r.slice(1)),l.length&&(i=i.concat(l)))),a=u;return i},t.parseSegmentIndex=function(e){var r=t.findBox(e,["moov"])[0],i=r?r.end:null,a=0,n=t.findBox(e,["sidx"]),o=void 0;if(!n||!n[0])return null;o=[],n=n[0];var s=n.data[0];a=0===s?8:16;var l=t.readUint32(n,a);a+=4;a+=0===s?8:16,a+=2;var d=n.end+0,u=t.readUint16(n,a);a+=2;for(var f=0;f<u;f++){var c=a,h=t.readUint32(n,c);c+=4;var p=2147483647&h;if(1===(2147483648&h)>>>31)return void console.warn("SIDX has hierarchical references (not supported)");var v=t.readUint32(n,c);c+=4,o.push({referenceSize:p,subsegmentDuration:v,info:{duration:v/l,start:d,end:d+p-1}}),d+=p,c+=4,a=c}return{earliestPresentationTime:0,timescale:l,version:s,referencesCount:u,references:o,moovEndOffset:i}},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 n=i.data[i.start],o=0===n?12:20,s=t.readUint32(i,o),l=t.findBox(e,["mdia","mdhd"])[0];if(l){n=l.data[l.start],o=0===n?12:20;var d=t.readUint32(l,o),u=t.findBox(e,["mdia","hdlr"])[0];if(u){var f=t.bin2str(u.data.subarray(u.start+8,u.start+12)),c={soun:"audio",vide:"video"}[f];if(c){var h=t.findBox(e,["mdia","minf","stbl","stsd"]);if(h.length){h=h[0];var p=t.bin2str(h.data.subarray(h.start+12,h.start+16));a.b.log("MP4Demuxer:"+c+":"+p+" found")}r[s]={timescale:d,type:c},r[c]={timescale:d,id:s}}}}}}),r},t.getStartDTS=function(e,r){var i=void 0,a=void 0,n=void 0;return i=t.findBox(r,["moof","traf"]),a=[].concat.apply([],i.map(function(r){return t.findBox(r,["tfhd"]).map(function(i){var a=void 0,n=void 0;return a=t.readUint32(i,4),n=e[a].timescale||9e4,t.findBox(r,["tfdt"]).map(function(e){var r=void 0,i=void 0;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),s=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*s);else{a*=Math.pow(2,32),a+=t.readUint32(e,8),a-=i*s,a=Math.max(a,0);var n=Math.floor(a/(o+1)),l=Math.floor(a%(o+1));t.writeUint32(e,4,n),t.writeUint32(e,8,l)}})})})},t.prototype.append=function(e,r,i,a){var o=this.initData;o||(this.resetInitSegment(e,this.audioCodec,this.videoCodec,!1),o=this.initData);var s=void 0,l=this.initPTS;if(void 0===l){var d=t.getStartDTS(o,e);this.initPTS=l=d-r,this.observer.trigger(n.a.INIT_PTS_FOUND,{initPTS:l})}t.offsetStartDTS(o,e,l),s=t.getStartDTS(o,e),this.remuxer.remux(o.audio,o.video,null,null,s,i,a,e)},t.prototype.destroy=function(){},t}();e.a=s},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(6),n=r.n(a),o=r(14),s=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}}(),l=function(){function t(){var e;i(this,t),this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this._elementaryStreams=(e={},e[t.ElementaryStreamTypes.AUDIO]=!1,e[t.ElementaryStreamTypes.VIDEO]=!1,e)}return t.prototype.addElementaryStream=function(t){this._elementaryStreams[t]=!0},t.prototype.hasElementaryStream=function(t){return!0===this._elementaryStreams[t]},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 o.a,r.method=t.method,r.baseuri=t.baseuri,r.reluri=t.reluri,r.iv=this.createInitializationVector(e)),r},s(t,[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=n.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&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;var t=[];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],this._byteRange=t}return t}},{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}},{key:"encrypted",get:function(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}}],[{key:"ElementaryStreamTypes",get:function(){return{AUDIO:"audio",VIDEO:"video"}}}]),t}();e.a=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(6),n=r.n(a),o=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}}(),s=function(){function t(){i(this,t),this.method=null,this.key=null,this.iv=null,this._uri=null}return o(t,[{key:"uri",get:function(){return!this._uri&&this.reluri&&(this._uri=n.a.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}]),t}();e.a=s},function(t,e,r){"use strict";function i(t,e){var r=n[e];return!!r&&!0===r[t.slice(0,4)]}function a(t,e){return window.MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}r.d(e,"b",function(){return i}),r.d(e,"a",function(){return a});var n={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}}},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)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)}r.d(e,"a",function(){return l}),r.d(e,"b",function(){return d});var o=r(3),s=r(1),l={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},d=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,s.a.BUFFER_APPENDED,s.a.FRAG_BUFFERED,s.a.FRAG_LOADED));return n.bufferPadding=.2,n.fragments=Object.create(null),n.timeRanges=Object.create(null),n.config=r.config,n}return n(e,t),e.prototype.destroy=function(){this.fragments=null,this.timeRanges=null,this.config=null,o.a.prototype.destroy.call(this),t.prototype.destroy.call(this)},e.prototype.getBufferedFrag=function(t,e){var r=this.fragments,i=Object.keys(r).filter(function(i){var a=r[i];if(a.body.type!==e)return!1;if(!a.buffered)return!1;var n=a.body;return n.startPTS<=t&&t<=n.endPTS});if(0===i.length)return null;var a=i.pop();return r[a].body},e.prototype.detectEvictedFragments=function(t,e){var r=this,i=void 0,a=void 0;Object.keys(this.fragments).forEach(function(n){var o=r.fragments[n];if(!0===o.buffered){var s=o.range[t];if(s){i=s.time;for(var l=0;l<i.length;l++)if(a=i[l],!1===r.isTimeBuffered(a.startPTS,a.endPTS,e)){r.removeFragment(o.body);break}}}})},e.prototype.detectPartialFragments=function(t){var e=this,r=this.getFragmentKey(t),i=this.fragments[r];i&&(i.buffered=!0,Object.keys(this.timeRanges).forEach(function(r){if(!0===t.hasElementaryStream(r)){var a=e.timeRanges[r];i.range[r]=e.getBufferedTimes(t.startPTS,t.endPTS,a)}}))},e.prototype.getBufferedTimes=function(t,e,r){for(var i=[],a=void 0,n=void 0,o=!1,s=0;s<r.length;s++){if(a=r.start(s)-this.bufferPadding,n=r.end(s)+this.bufferPadding,t>=a&&e<=n){i.push({startPTS:Math.max(t,r.start(s)),endPTS:Math.min(e,r.end(s))});break}if(t<n&&e>a)i.push({startPTS:Math.max(t,r.start(s)),endPTS:Math.min(e,r.end(s))}),o=!0;else if(e<=a)break}return{time:i,partial:o}},e.prototype.getFragmentKey=function(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn},e.prototype.getPartialFragment=function(t){var e=this,r=void 0,i=void 0,a=void 0,n=null,o=0;return Object.keys(this.fragments).forEach(function(s){var l=e.fragments[s];e.isPartial(l)&&(i=l.body.startPTS-e.bufferPadding,a=l.body.endPTS+e.bufferPadding,t>=i&&t<=a&&(r=Math.min(t-i,a-t),o<=r&&(n=l.body,o=r)))}),n},e.prototype.getState=function(t){var e=this.getFragmentKey(t),r=this.fragments[e],i=l.NOT_LOADED;return void 0!==r&&(i=r.buffered?!0===this.isPartial(r)?l.PARTIAL:l.OK:l.APPENDING),i},e.prototype.isPartial=function(t){return!0===t.buffered&&(void 0!==t.range.video&&!0===t.range.video.partial||void 0!==t.range.audio&&!0===t.range.audio.partial)},e.prototype.isTimeBuffered=function(t,e,r){for(var i=void 0,a=void 0,n=0;n<r.length;n++){if(i=r.start(n)-this.bufferPadding,a=r.end(n)+this.bufferPadding,t>=i&&e<=a)return!0;if(e<=i)return!1}return!1},e.prototype.onFragLoaded=function(t){var e=t.frag;if(!isNaN(e.sn)&&!e.bitrateTest){var r=this.getFragmentKey(e),i={body:e,range:Object.create(null),buffered:!1};this.fragments[r]=i}},e.prototype.onBufferAppended=function(t){var e=this;this.timeRanges=t.timeRanges,Object.keys(this.timeRanges).forEach(function(t){var r=e.timeRanges[t];e.detectEvictedFragments(t,r)})},e.prototype.onFragBuffered=function(t){this.detectPartialFragments(t.frag)},e.prototype.hasFragment=function(t){var e=this.getFragmentKey(t);return void 0!==this.fragments[e]},e.prototype.removeFragment=function(t){var e=this.getFragmentKey(t);delete this.fragments[e]},e.prototype.removeAllFragments=function(){this.fragments=Object.create(null)},e}(o.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")}r.d(e,"a",function(){return a});var a=function(){function t(){i(this,t)}return t.isBuffered=function(t,e){try{if(t)for(var r=t.buffered,i=0;i<r.length;i++)if(e>=r.start(i)&&e<=r.end(i))return!0}catch(t){}return!1},t.bufferInfo=function(t,e,r){try{if(t){var i=t.buffered,a=[],n=void 0;for(n=0;n<i.length;n++)a.push({start:i.start(n),end:i.end(n)});return this.bufferedInfo(a,e,r)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}},t.bufferedInfo=function(t,e,r){var i=[],a=void 0,n=void 0,o=void 0,s=void 0,l=void 0;for(t.sort(function(t,e){var r=t.start-e.start;return r||e.end-t.end}),l=0;l<t.length;l++){var d=i.length;if(d){var u=i[d-1].end;t[l].start-u<r?t[l].end>u&&(i[d-1].end=t[l].end):i.push(t[l])}else i.push(t[l])}for(l=0,a=0,n=o=e;l<i.length;l++){var f=i[l].start,c=i[l].end;if(e+r>=f&&e<c)n=f,o=c,a=o-e;else if(e+r<f){s=f;break}}return{len:a,start:n,end:o,nextStart:s}},t}()},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(1),n=r(2),o=r(19),s=r(34),l=r(12),d=r(35),u=r(38),f=r(39),c=r(42),h=r(5),p=Object(h.a)(),v=p,g=function(){function t(e,r,a,n){i(this,t),this.observer=e,this.typeSupported=r,this.config=a,this.vendor=n}return t.prototype.destroy=function(){var t=this.demuxer;t&&t.destroy()},t.prototype.push=function(t,e,r,i,n,s,l,d,u,f,c,h){if(t.byteLength>0&&null!=e&&null!=e.key&&"AES-128"===e.method){var p=this.decrypter;null==p&&(p=this.decrypter=new o.a(this.observer,this.config));var g=this,m=void 0;try{m=v.now()}catch(t){m=Date.now()}p.decrypt(t,e.key.buffer,e.iv.buffer,function(t){var o=void 0;try{o=v.now()}catch(t){o=Date.now()}g.observer.trigger(a.a.FRAG_DECRYPTED,{stats:{tstart:m,tdecrypt:o}}),g.pushDecrypted(new Uint8Array(t),e,new Uint8Array(r),i,n,s,l,d,u,f,c,h)})}else this.pushDecrypted(new Uint8Array(t),e,new Uint8Array(r),i,n,s,l,d,u,f,c,h)},t.prototype.pushDecrypted=function(t,e,r,i,o,h,p,v,g,m,y,b){var E=this.demuxer;if(!E||(p||v)&&!this.probe(t)){for(var T=this.observer,S=this.typeSupported,A=this.config,_=[{demux:d.a,remux:f.a},{demux:l.a,remux:c.a},{demux:s.a,remux:f.a},{demux:u.a,remux:f.a}],R=0,L=_.length;R<L;R++){var w=_[R],D=w.demux.probe;if(D(t)){var O=this.remuxer=new w.remux(T,A,S,this.vendor);E=new w.demux(T,O,A,S),this.probe=D;break}}if(!E)return void T.trigger(a.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});this.demuxer=E}var I=this.remuxer;(p||v)&&(E.resetInitSegment(r,i,o,m),I.resetInitSegment()),p&&(E.resetTimeStamp(b),I.resetTimeStamp(b)),"function"==typeof E.setDecryptData&&E.setDecryptData(e),E.append(t,h,g,y)},t}();e.a=g},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(31),n=r(32),o=r(33),s=r(2),l=r(0),d=r(1),u=r(5),f=Object(u.a)(),c=function(){function t(e,r){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=a.removePKCS7Padding,o=void 0===n||n;if(i(this,t),this.logEnabled=!0,this.observer=e,this.config=r,this.removePKCS7Padding=o,o)try{var s=f.crypto;s&&(this.subtle=s.subtle||s.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 s=this;if(this.disableWebCrypto&&this.config.enableSoftwareAES){this.logEnabled&&(l.b.log("JS AES decrypt"),this.logEnabled=!1);var d=this.decryptor;d||(this.decryptor=d=new o.a),d.expandKey(e),i(d.decrypt(t,0,r,this.removePKCS7Padding))}else{this.logEnabled&&(l.b.log("WebCrypto AES decrypt"),this.logEnabled=!1);var u=this.subtle;this.key!==e&&(this.key=e,this.fastAesKey=new n.a(u,e)),this.fastAesKey.expandKey().then(function(n){new a.a(u,r).decrypt(t,n).catch(function(a){s.onWebCryptoError(a,t,e,r,i)}).then(function(t){i(t)})}).catch(function(a){s.onWebCryptoError(a,t,e,r,i)})}},t.prototype.onWebCryptoError=function(t,e,r,i,a){this.config.enableSoftwareAES?(l.b.log("WebCrypto Error, disable WebCrypto API"),this.disableWebCrypto=!0,this.logEnabled=!0,this.decrypt(e,r,i,a)):(l.b.error("decrypting error : "+t.message),this.observer.trigger(d.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.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=c},function(t,e,r){"use strict";function i(t,e,r,i){var a=void 0,n=void 0,o=void 0,s=void 0,l=void 0,d=navigator.userAgent.toLowerCase(),u=i,f=[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)>f.length-1?void t.trigger(v.a.ERROR,{type:p.b.MEDIA_ERROR,details:p.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+n}):(s=(1&e[r+2])<<2,s|=(192&e[r+3])>>>6,h.b.log("manifest codec:"+i+",ADTS data:type:"+a+",sampleingIndex:"+n+"["+f[n]+"Hz],channelConfig:"+s),/firefox/i.test(d)?n>=6?(a=5,l=new Array(4),o=n-3):(a=2,l=new Array(2),o=n):-1!==d.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(d))||!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:f[n],channelCount:s,codec:"mp4a.40."+a,manifestCodec:u})}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 d(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,h.b.log("parsed codec:"+t.codec+",rate:"+o.samplerate+",nb channel:"+o.channelCount)}}function u(t){return 9216e4/t}function f(t,e,r,i,a){var s=void 0,l=void 0,d=void 0,u=t.length;if(s=n(t,e),l=o(t,e),(l-=s)>0&&e+s+l<=u)return d=r+i*a,{headerLength:s,frameLength:l,stamp:d}}function c(t,e,r,i,a){var n=u(t.samplerate),o=f(e,r,i,a,n);if(o){var s=o.stamp,l=o.headerLength,d=o.frameLength,c={unit:e.subarray(r+l,r+l+d),pts:s,dts:s};return t.samples.push(c),t.len+=d,{sample:c,length:d+l}}}e.d=s,e.e=l,e.c=d,e.b=u,e.a=c;var h=r(0),p=r(2),v=r(1);r(5)},function(t,e,r){"use strict";var i={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],SamplesCoefficients:[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot:[0,1,1,4],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=9e4*n.samplesPerFrame/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,a=t[e+1]>>1&3,n=t[e+2]>>4&15,o=t[e+2]>>2&3,s=t[e+2]>>1&1;if(1!==r&&0!==n&&15!==n&&3!==o){var l=3===r?3-a:3===a?3:4,d=1e3*i.BitratesMap[14*l+n-1],u=3===r?0:2===r?1:2,f=i.SamplingRateMap[3*u+o],c=t[e+3]>>6==3?1:2,h=i.SamplesCoefficients[r][a],p=i.BytesInSlot[a],v=8*h*p;return{sampleRate:f,channelCount:c,frameLength:parseInt(h*d/f+s,10)*p,samplesPerFrame:v}}},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}};e.a=i},function(t,e,r){"use strict";function i(t,e,r){switch(e){case"audio":t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds.push(r);break;case"text":t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds.push(r)}}function a(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&&s.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&&s.b.warn("negative duration computed for frag "+a.sn+",level "+a.level+", there should be some duration drift between playlist and fragment!"))}function n(t,e,r,i,n,o){var s=r;if(!isNaN(e.startPTS)){var l=Math.abs(e.startPTS-r);isNaN(e.deltaPTS)?e.deltaPTS=l:e.deltaPTS=Math.max(l,e.deltaPTS),s=Math.max(r,e.startPTS),r=Math.min(r,e.startPTS),i=Math.max(i,e.endPTS),n=Math.min(n,e.startDTS),o=Math.max(o,e.endDTS)}var d=r-e.start;e.start=e.startPTS=r,e.maxStartPTS=s,e.endPTS=i,e.startDTS=n,e.endDTS=o,e.duration=i-r;var u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;var f=void 0,c=void 0,h=void 0;for(f=u-t.startSN,c=t.fragments,c[f]=e,h=f;h>0;h--)a(c,h,h-1);for(h=f;h<c.length-1;h++)a(c,h,h+1);return t.PTSKnown=!0,d}function o(t,e){var r=Math.max(t.startSN,e.startSN)-e.startSN,i=Math.min(t.endSN,e.endSN)-e.startSN,a=e.startSN-t.startSN,o=t.fragments,l=e.fragments,d=0,u=void 0;if(e.initSegment&&t.initSegment&&(e.initSegment=t.initSegment),i<r)return void(e.PTSKnown=!1);for(var f=r;f<=i;f++){var c=o[a+f],h=l[f];h&&c&&(d=c.cc-h.cc,isNaN(c.startPTS)||(h.start=h.startPTS=c.startPTS,h.endPTS=c.endPTS,h.duration=c.duration,h.backtracked=c.backtracked,h.dropped=c.dropped,u=h))}if(d)for(s.b.log("discontinuity sliding from playlist, take drift into account"),f=0;f<l.length;f++)l[f].cc+=d;if(u)n(e,u,u.startPTS,u.endPTS,u.startDTS,u.endDTS);else if(a>=0&&a<o.length){var p=o[a].start;for(f=0;f<l.length;f++)l[f].start+=p}e.PTSKnown=t.PTSKnown}e.a=i,e.c=n,e.b=o;var s=r(0)},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var a=r(6),n=r.n(a),o=r(2),s=r(11),l=r(26),d=r(27),u=r(16),f=r(28),c=r(48),h=r(49),p=r(51),v=r(0),g=r(52),m=r(1),y=r(8),b=r.n(y),E=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}}();r(61);var T=function(){function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(this,t);var a=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 n in a)n in r||(r[n]=a[n]);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(v.a)(r.debug),this.config=r,this._autoLevelCapping=-1;var o=this.observer=new b.a;o.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];o.emit.apply(o,[t,t].concat(r))},o.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];o.removeListener.apply(o,[t].concat(r))},this.on=o.on.bind(o),this.off=o.off.bind(o),this.once=o.once.bind(o),this.trigger=o.trigger.bind(o);var p=this.abrController=new r.abrController(this),g=new r.bufferController(this),m=new r.capLevelController(this),y=new r.fpsController(this),E=new s.a(this),T=new l.a(this),S=new d.a(this),A=new h.a(this),_=this.levelController=new c.a(this),R=new u.b(this),L=this.streamController=new f.a(this,R),w=[_,L],D=r.audioStreamController;D&&w.push(new D(this,R)),this.networkControllers=w;var O=[E,T,S,p,g,m,y,A,R];if(D=r.audioTrackController){var I=new D(this);this.audioTrackController=I,O.push(I)}if(D=r.subtitleTrackController){var x=new D(this);this.subtitleTrackController=x,O.push(x)}if(D=r.emeController){var k=new D(this);this.emeController=k,O.push(k)}[r.subtitleStreamController,r.timelineController].forEach(function(t){t&&O.push(new t(e))}),this.coreComponents=O}return t.isSupported=function(){return Object(p.a)()},E(t,null,[{key:"version",get:function(){return"0.10.0"}},{key:"Events",get:function(){return m.a}},{key:"ErrorTypes",get:function(){return o.b}},{key:"ErrorDetails",get:function(){return o.a}},{key:"DefaultConfig",get:function(){return t.defaultConfig?t.defaultConfig:g.a},set:function(e){t.defaultConfig=e}}]),t.prototype.destroy=function(){v.b.log("destroy"),this.trigger(m.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){v.b.log("attachMedia"),this.media=t,this.trigger(m.a.MEDIA_ATTACHING,{media:t})},t.prototype.detachMedia=function(){v.b.log("detachMedia"),this.trigger(m.a.MEDIA_DETACHING),this.media=null},t.prototype.loadSource=function(t){t=n.a.buildAbsoluteURL(window.location.href,t,{alwaysNormalize:!0}),v.b.log("loadSource:"+t),this.url=t,this.trigger(m.a.MANIFEST_LOADING,{url:t})},t.prototype.startLoad=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;v.b.log("startLoad("+t+")"),this.networkControllers.forEach(function(e){e.startLoad(t)})},t.prototype.stopLoad=function(){v.b.log("stopLoad"),this.networkControllers.forEach(function(t){t.stopLoad()})},t.prototype.swapAudioCodec=function(){v.b.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.prototype.recoverMediaError=function(){v.b.log("recoverMediaError");var t=this.media;this.detachMedia(),this.attachMedia(t)},E(t,[{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){v.b.log("set currentLevel:"+t),this.loadLevel=t,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){v.b.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){v.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){v.b.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(t){v.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){v.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=T},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(6),n=r.n(a),o=r(13),s=r(14),l=r(25),d=r(0),u=r(15),f=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,c=/#EXT-X-MEDIA:(.*)/g,h=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)(\S+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),p=/(?:(?:#(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?/,v=/\.(mp4|m4s|m4v|m4a)$/i,g=function(){function t(){i(this,t)}return t.findGroup=function(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},t.convertAVC1ToAVCOTI=function(t){var e=void 0,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},t.resolve=function(t,e){return n.a.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i=[],a=void 0;for(f.lastIndex=0;null!=(a=f.exec(e));){var n={},o=n.attrs=new l.a(a[1]);n.url=t.resolve(a[2],r);var s=o.decimalResolution("RESOLUTION");s&&(n.width=s.width,n.height=s.height),n.bitrate=o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),n.name=o.NAME,function(t,e){["video","audio"].forEach(function(r){var i=t.filter(function(t){return Object(u.b)(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(/[ ,]+/)),n),n.videoCodec&&-1!==n.videoCodec.indexOf("avc1")&&(n.videoCodec=t.convertAVC1ToAVCOTI(n.videoCodec)),i.push(n)}return i},t.parseMasterPlaylistMedia=function(e,r,i){var a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],n=void 0,o=[],s=0;for(c.lastIndex=0;null!==(n=c.exec(e));){var d={},u=new l.a(n[1]);if(u.TYPE===i){if(d.groupId=u["GROUP-ID"],d.name=u.NAME,d.type=i,d.default="YES"===u.DEFAULT,d.autoselect="YES"===u.AUTOSELECT,d.forced="YES"===u.FORCED,u.URI&&(d.url=t.resolve(u.URI,r)),d.lang=u.LANGUAGE,d.name||(d.name=d.lang),a.length){var f=t.findGroup(a,d.groupId);d.audioCodec=f?f.codec:a[0].codec}d.id=s++,o.push(d)}}return o},t.parseLevelPlaylist=function(t,e,r,i,a){var n=0,u=0,f={type:null,version:null,url:e,fragments:[],live:!0,startSN:0},c=new s.a,g=0,m=null,y=new o.a,b=void 0,E=void 0;for(h.lastIndex=0;null!==(b=h.exec(t));){var T=b[1];if(T){y.duration=parseFloat(T);var S=(" "+b[2]).slice(1);y.title=S||null,y.tagList.push(S?["INF",T,S]:["INF",T])}else if(b[3]){if(!isNaN(y.duration)){var A=n++;y.type=i,y.start=u,y.levelkey=c,y.sn=A,y.level=r,y.cc=g,y.urlId=a,y.baseurl=e,y.relurl=(" "+b[3]).slice(1),f.programDateTime&&(m?y.rawProgramDateTime?y.pdt=Date.parse(y.rawProgramDateTime):y.pdt=m.pdt+1e3*m.duration:y.pdt=Date.parse(f.programDateTime),y.endPdt=y.pdt+1e3*y.duration),f.fragments.push(y),m=y,u+=y.duration,y=new o.a}}else if(b[4]){if(y.rawByteRange=(" "+b[4]).slice(1),m){var _=m.byteRangeEndOffset;_&&(y.lastByteRangeEndOffset=_)}}else if(b[5])y.rawProgramDateTime=(" "+b[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),void 0===f.programDateTime&&(f.programDateTime=new Date(new Date(Date.parse(b[5]))-1e3*u));else{for(b=b[0].match(p),E=1;E<b.length&&void 0===b[E];E++);var R=(" "+b[E+1]).slice(1),L=(" "+b[E+2]).slice(1);switch(b[E]){case"#":y.tagList.push(L?[R,L]:[R]);break;case"PLAYLIST-TYPE":f.type=R.toUpperCase();break;case"MEDIA-SEQUENCE":n=f.startSN=parseInt(R);break;case"TARGETDURATION":f.targetduration=parseFloat(R);break;case"VERSION":f.version=parseInt(R);break;case"EXTM3U":break;case"ENDLIST":f.live=!1;break;case"DIS":g++,y.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":g=parseInt(R);break;case"KEY":var w=R,D=new l.a(w),O=D.enumeratedString("METHOD"),I=D.URI,x=D.hexadecimalInteger("IV");O&&(c=new s.a,I&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(O)>=0&&(c.method=O,c.baseuri=e,c.reluri=I,c.key=null,c.iv=x));break;case"START":var k=R,P=new l.a(k),C=P.decimalFloatingPoint("TIME-OFFSET");isNaN(C)||(f.startTimeOffset=C);break;case"MAP":var F=new l.a(R);y.relurl=F.URI,y.rawByteRange=F.BYTERANGE,y.baseurl=e,y.level=r,y.type=i,y.sn="initSegment",f.initSegment=y,y=new o.a;break;default:d.b.warn("line parsed but not handled: "+b)}}}return y=m,y&&!y.relurl&&(f.fragments.pop(),u-=y.duration),f.totalduration=u,f.averagetargetduration=u/f.fragments.length,f.endSN=n-1,f.startCC=f.fragments[0]?f.fragments[0].cc:0,f.endCC=g,!f.initSegment&&f.fragments.length&&f.fragments.every(function(t){return v.test(t.relurl)})&&(d.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),y=new o.a,y.relurl=f.fragments[0].relurl,y.baseurl=e,y.level=r,y.type=i,y.sn="initSegment",f.initSegment=y,f.needSidxRanges=!0),f},t}();e.a=g},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=/^(\d+)x(\d+)$/,n=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,o=function(){function t(e){i(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=a.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e=void 0,r={};for(n.lastIndex=0;null!==(e=n.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}();e.a=o},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)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)}var o=r(1),s=r(3),l=r(2),d=r(0),u=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.FRAG_LOADING));return n.loaders={},n}return n(e,t),e.prototype.destroy=function(){var e=this.loaders;for(var r in e){var i=e[r];i&&i.destroy()}this.loaders={},t.prototype.destroy.call(this)},e.prototype.onFragLoading=function(t){var e=t.frag,r=e.type,i=this.loaders,a=this.hls.config,n=a.fLoader,o=a.loader;e.loaded=0;var s=i[r];s&&(d.b.warn("abort previous fragment loader for type: "+r),s.abort()),s=i[r]=e.loader=a.fLoader?new n(a):new o(a);var l=void 0,u=void 0,f=void 0;l={url:e.url,frag:e,responseType:"arraybuffer",progressData:!1};var c=e.byteRangeStartOffset,h=e.byteRangeEndOffset;isNaN(c)||isNaN(h)||(l.rangeStart=c,l.rangeEnd=h),u={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},s.load(l,u,f)},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(o.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(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.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(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.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(o.a.FRAG_LOAD_PROGRESS,{frag:a,stats:t,networkDetails:i})},e}(s.a);e.a=u},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)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)}var o=r(1),s=r(3),l=r(2),d=r(0),u=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.KEY_LOADING));return n.loaders={},n.decryptkey=null,n.decrypturl=null,n}return n(e,t),e.prototype.destroy=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={},s.a.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 s=this.hls.config;i&&(d.b.warn("abort previous key loader for type:"+r),i.abort()),e.loader=this.loaders[r]=new s.loader(s),this.decrypturl=n,this.decryptkey=null;var l=void 0,u=void 0,f=void 0;l={url:n,frag:e,responseType:"arraybuffer"},u={timeout:s.fragLoadingTimeOut,maxRetry:s.fragLoadingMaxRetry,retryDelay:s.fragLoadingRetryDelay,maxRetryDelay:s.fragLoadingMaxRetryTimeout},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},e.loader.load(l,u,f)}else this.decryptkey&&(a.key=this.decryptkey,this.hls.trigger(o.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(o.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(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.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(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},e}(s.a);e.a=u},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)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)}var o=r(7),s=r(17),l=r(29),d=r(1),u=r(16),f=r(13),c=r(11),h=r(22),p=r(44),v=r(2),g=r(0),m=r(45),y=r(46),b=r(47),E=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}}(),T={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"},S=function(t){function e(r,n){i(this,e);var o=a(this,t.call(this,r,d.a.MEDIA_ATTACHED,d.a.MEDIA_DETACHING,d.a.MANIFEST_LOADING,d.a.MANIFEST_PARSED,d.a.LEVEL_LOADED,d.a.KEY_LOADED,d.a.FRAG_LOADED,d.a.FRAG_LOAD_EMERGENCY_ABORTED,d.a.FRAG_PARSING_INIT_SEGMENT,d.a.FRAG_PARSING_DATA,d.a.FRAG_PARSED,d.a.ERROR,d.a.AUDIO_TRACK_SWITCHING,d.a.AUDIO_TRACK_SWITCHED,d.a.BUFFER_CREATED,d.a.BUFFER_APPENDED,d.a.BUFFER_FLUSHED));return o.fragmentTracker=n,o.config=r.config,o.audioCodecSwap=!1,o._state=T.STOPPED,o.stallReported=!1,o}return n(e,t),e.prototype.onHandlerDestroying=function(){this.stopLoad(),t.prototype.onHandlerDestroying.call(this)},e.prototype.onHandlerDestroyed=function(){this.state=T.STOPPED,this.fragmentTracker=null,t.prototype.onHandlerDestroyed.call(this)},e.prototype.startLoad=function(t){if(this.levels){var e=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(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&&(g.b.log("override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=T.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this.forceStartLoad=!0,this.state=T.STOPPED},e.prototype.stopLoad=function(){var t=this.fragCurrent;t&&(t.loader&&t.loader.abort(),this.fragmentTracker.removeFragment(t),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.clearInterval(),this.state=T.STOPPED,this.forceStartLoad=!1},e.prototype.doTick=function(){switch(this.state){case T.BUFFER_FLUSHING:this.fragLoadError=0;break;case T.IDLE:this._doTickIdle();break;case T.WAITING_LEVEL:var t=this.levels[this.level];t&&t.details&&(this.state=T.IDLE);break;case T.FRAG_LOADING_WAITING_RETRY:var e=window.performance.now(),r=this.retryDate;(!r||e>=r||this.media&&this.media.seeking)&&(g.b.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=T.IDLE);break;case T.ERROR:case T.STOPPED:case T.FRAG_LOADING:case T.PARSING:case T.PARSED:case T.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,l=void 0;l=o?Math.max(8*e.maxBufferSize/o,e.maxBufferLength):e.maxBufferLength,l=Math.min(l,e.maxMaxBufferLength);var u=s.a.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,e.maxBufferHole),f=u.len;if(!(f>=l)){g.b.trace("buffer length of "+f.toFixed(3)+" is below max of "+l.toFixed(3)+". checking for more payload ..."),this.level=t.nextLoadLevel=a;var c=n.details;if(!c||c.live&&this.levelLastLoaded!==a)return void(this.state=T.WAITING_LEVEL);var h=this.fragPrevious;if(!c.live&&h&&!h.backtracked&&h.sn===c.endSN&&!u.nextStart){if(Math.min(r.duration,h.start+h.duration)-Math.max(u.end,h.start)<=Math.max(.2,h.duration)){var p={};return this.altAudio&&(p.type="video"),this.hls.trigger(d.a.BUFFER_EOS,p),void(this.state=T.ENDED)}}this._fetchPayloadOrEos(i,u,c)}}}},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,d=e.end,u=void 0;if(r.initSegment&&!r.initSegment.data)u=r.initSegment;else if(r.live){var f=this.config.initialLiveManifestSize;if(o<f)return void g.b.warn("Can not start playback of a level, reason: not enough fragments "+o+" < "+f);if(null===(u=this._ensureFragmentAtLivePoint(r,d,s,l,i,n,o)))return}else d<s&&(u=n[0]);u||(u=this._findFragment(s,i,o,n,d,l,r)),u&&(u.encrypted?(g.b.log("Loading key for "+u.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+a),this._loadKey(u)):(g.b.log("Loading "+u.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+a+", currentTime:"+t.toFixed(3)+",bufferEnd:"+d.toFixed(3)),this._loadFragment(u)))}},e.prototype._ensureFragmentAtLivePoint=function(t,e,r,i,a,n,s){var l=this.hls.config,d=this.media,u=void 0,f=void 0!==l.liveMaxLatencyDuration?l.liveMaxLatencyDuration:l.liveMaxLatencyDurationCount*t.targetduration;if(e<Math.max(r-l.maxFragLookUpTolerance,i-f)){var c=this.liveSyncPosition=this.computeLivePosition(r,t);g.b.log("buffer end: "+e.toFixed(3)+" is located too far from the end of live sliding playlist, reset currentTime to : "+c.toFixed(3)),e=c,d&&d.readyState&&d.duration>c&&(d.currentTime=c),this.nextLoadPosition=c}if(t.PTSKnown&&e>i&&d&&d.readyState)return null;if(this.startFragRequested&&!t.PTSKnown){if(a)if(t.programDateTime)u=Object(b.b)(n,a.endPdt+1);else{var h=a.sn+1;if(h>=t.startSN&&h<=t.endSN){var p=n[h-t.startSN];a.cc===p.cc&&(u=p,g.b.log("live playlist, switching playlist, load frag with next SN: "+u.sn))}u||(u=o.a.search(n,function(t){return a.cc-t.cc}))&&g.b.log("live playlist, switching playlist, load frag with same CC: "+u.sn)}u||(u=n[Math.min(s-1,Math.round(s/2))],g.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,d=void 0;if(a<n?o.programDateTime?(d=Object(b.b)(i,Object(b.a)(t,a,o)))&&!Object(b.d)(a,s.maxFragLookUpTolerance,d)||(g.b.warn("Frag found by PDT search did not fit within tolerance; falling back to finding by SN"),d=function(){return Object(b.c)(e,i,a,n,s.maxFragLookUpTolerance)}()):d=Object(b.c)(e,i,a,n,s.maxFragLookUpTolerance):d=i[r-1],d){l=d;var u=l.sn-o.startSN,f=e&&l.level===e.level,c=i[u-1],h=i[u+1];if(e&&l.sn===e.sn)if(f&&!l.backtracked)if(l.sn<o.endSN){var p=e.deltaPTS;p&&p>s.maxBufferHole&&e.dropped&&u?(l=c,g.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")):(l=h,g.b.log("SN just loaded, load next one: "+l.sn))}else l=null;else l.backtracked&&(h&&h.backtracked?(g.b.warn("Already backtracked from fragment "+h.sn+", will not backtrack to fragment "+l.sn+". Loading fragment "+h.sn),l=h):(g.b.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),l.dropped=0,c?(l=c,l.backtracked=!0):u&&(l=null)))}return l},e.prototype._loadKey=function(t){this.state=T.KEY_LOADING,this.hls.trigger(d.a.KEY_LOADING,{frag:t})},e.prototype._loadFragment=function(t){var e=this.fragmentTracker.getState(t);this.fragCurrent=t,this.startFragRequested=!0,isNaN(t.sn)||t.bitrateTest||(this.nextLoadPosition=t.start+t.duration),t.backtracked||e===u.a.NOT_LOADED||e===u.a.PARTIAL?(t.autoLevel=this.hls.autoLevelEnabled,t.bitrateTest=this.bitrateTest,this.hls.trigger(d.a.FRAG_LOADING,{frag:t}),this.demuxer||(this.demuxer=new l.a(this.hls,"main")),this.state=T.FRAG_LOADING):e===u.a.APPENDING&&this._reduceMaxBufferLength(t.duration)&&this.fragmentTracker.removeFragment(t)},e.prototype.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,c.a.LevelType.MAIN)},e.prototype.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.endPTS+.5):null},e.prototype._checkFragmentChanged=function(){var t=void 0,e=void 0,r=this.media;if(r&&r.readyState&&!1===r.seeking&&(e=r.currentTime,e>this.lastCurrentTime&&(this.lastCurrentTime=e),s.a.isBuffered(r,e)?t=this.getBufferedFrag(e):s.a.isBuffered(r,e+.1)&&(t=this.getBufferedFrag(e+.1)),t)){var i=t;if(i!==this.fragPlaying){this.hls.trigger(d.a.FRAG_CHANGED,{frag:i});var a=i.level;this.fragPlaying&&this.fragPlaying.level===a||this.hls.trigger(d.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=i}}},e.prototype.immediateLevelSwitch=function(){if(g.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,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},e.prototype.immediateLevelSwitchEnd=function(){var t=this.media;t&&t.buffered.length&&(this.immediateSwitch=!1,s.a.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(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=T.BUFFER_FLUSHING;var r={startOffset:t,endOffset:e};this.altAudio&&(r.type="video"),this.hls.trigger(d.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&&(g.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.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)||g.b.log("media seeking to "+e.toFixed(3));var i=this.mediaBuffer?this.mediaBuffer:t,a=s.a.bufferInfo(i,e,this.config.maxBufferHole);if(this.state===T.FRAG_LOADING){var n=this.fragCurrent;if(0===a.len&&n){var o=r.maxFragLookUpTolerance,l=n.start-o,d=n.start+n.duration+o;e<l||e>d?(n.loader&&(g.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=T.IDLE):g.b.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===T.ENDED&&(0===a.len&&(this.fragPrevious=0),this.state=T.IDLE);t&&(this.lastCurrentTime=e),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)||g.b.log("media seeked to "+e.toFixed(3)),this.tick()},e.prototype.onMediaEnded=function(){g.b.log("media ended"),this.startPosition=this.lastCurrentTime=0},e.prototype.onManifestLoading=function(){g.b.log("trigger BUFFER_RESET"),this.hls.trigger(d.a.BUFFER_RESET),this.fragmentTracker.removeAllFragments(),this.stalled=!1,this.startPosition=this.lastCurrentTime=0},e.prototype.onManifestParsed=function(t){var e=!1,r=!1,i=void 0;t.levels.forEach(function(t){(i=t.audioCodec)&&(-1!==i.indexOf("mp4a.40.2")&&(e=!0),-1!==i.indexOf("mp4a.40.5")&&(r=!0))}),this.audioCodecSwitch=e&&r,this.audioCodecSwitch&&g.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(g.b.log("level "+r+" loaded ["+e.startSN+","+e.endSN+"],duration:"+n),e.live){var s=a.details;s&&e.fragments.length>0?(h.b(s,e),o=e.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(o,s),e.PTSKnown&&!isNaN(o)?g.b.log("live playlist sliding:"+o.toFixed(3)):(g.b.log("live playlist - outdated PTS, unknown sliding"),Object(m.a)(this.fragPrevious,i,e))):(g.b.log("live playlist - first load, unknown sliding"),e.PTSKnown=!1,Object(m.a)(this.fragPrevious,i,e))}else e.PTSKnown=!1;if(a.details=e,this.levelLastLoaded=r,this.hls.trigger(d.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),g.b.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(l<0&&(g.b.log("negative start time offset "+l+", count from end of last fragment"),l=o+n+l),g.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===T.WAITING_LEVEL&&(this.state=T.IDLE),this.tick()},e.prototype.onKeyLoaded=function(){this.state===T.KEY_LOADING&&(this.state=T.IDLE,this.tick())},e.prototype.onFragLoaded=function(t){var e=this.fragCurrent,r=t.frag;if(this.state===T.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(g.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=T.IDLE,this.startFragRequested=!1,i.tparsed=i.tbuffered=window.performance.now(),this.hls.trigger(d.a.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=T.IDLE,i.tparsed=i.tbuffered=window.performance.now(),n.initSegment.data=t.payload,this.hls.trigger(d.a.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.tick();else{this.state=T.PARSING;var o=n.totalduration,s=e.level,u=e.sn,f=this.config.defaultAudioCodec||a.audioCodec;this.audioCodecSwap&&(g.b.log("swapping playlist audio codec"),void 0===f&&(f=this.lastAudioCodec),f&&(f=-1!==f.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,g.b.log("Parsing "+u+" of ["+n.startSN+" ,"+n.endSN+"],level "+s+", cc "+e.cc);var c=this.demuxer;c||(c=this.demuxer=new l.a(this.hls,"main"));var h=this.media,p=h&&h.seeking,v=!p&&(n.PTSKnown||!n.live),m=n.initSegment?n.initSegment.data:[];c.push(t.payload,m,f,a.videoCodec,e,o,v,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===T.PARSING){var i=t.tracks,a=void 0,n=void 0;if(i.audio&&this.altAudio&&delete i.audio,n=i.audio){var o=this.levels[this.level].audioCodec,s=navigator.userAgent.toLowerCase();o&&this.audioCodecSwap&&(g.b.log("swapping playlist audio codec"),o=-1!==o.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==n.metadata.channelCount&&-1===s.indexOf("firefox")&&(o="mp4a.40.5"),-1!==s.indexOf("android")&&"audio/mpeg"!==n.container&&(o="mp4a.40.2",g.b.log("Android: force audio codec to "+o)),n.levelCodec=o,n.id=t.id}n=i.video,n&&(n.levelCodec=this.levels[this.level].videoCodec,n.id=t.id),this.hls.trigger(d.a.BUFFER_CODECS,i);for(a in i){n=i[a],g.b.log("main track:"+a+",container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var l=n.initSegment;l&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(d.a.BUFFER_APPENDING,{type:a,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===T.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),!0===t.hasAudio&&n.addElementaryStream(f.a.ElementaryStreamTypes.AUDIO),!0===t.hasVideo&&n.addElementaryStream(f.a.ElementaryStreamTypes.VIDEO),g.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)g.b.warn("Already backtracked on this fragment, appending with the gap",n.sn);else{var o=a.details;if(!o||n.sn!==o.startSN)return g.b.warn("missing video frame(s), backtracking fragment",n.sn),this.fragmentTracker.removeFragment(n),n.backtracked=!0,this.nextLoadPosition=t.startPTS,this.state=T.IDLE,this.fragPrevious=n,void this.tick();g.b.warn("missing video frame(s) on first frag, appending with gap",n.sn)}else n.backtracked=!1;var s=h.c(a.details,n,t.startPTS,t.endPTS,t.startDTS,t.endDTS),l=this.hls;l.trigger(d.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===T.PARSING&&(e.appended=!0,e.pendingBuffering=!0,l.trigger(d.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===T.PARSING&&(this.stats.tparsed=window.performance.now(),this.state=T.PARSED,this._checkAppendedParsed())},e.prototype.onAudioTrackSwitching=function(t){var e=!!t.url,r=t.id;if(!e){if(this.mediaBuffer!==this.media){g.b.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i.loader&&(g.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=T.IDLE}var a=this.hls;a.trigger(d.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),a.trigger(d.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&&(g.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?(g.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!==T.PARSING&&e!==T.PARSED||(this.pendingBuffering=t.pending>0,this._checkAppendedParsed())}},e.prototype._checkAppendedParsed=function(){if(!(this.state!==T.PARSED||this.appended&&this.pendingBuffering)){var t=this.fragCurrent;if(t){var e=this.mediaBuffer?this.mediaBuffer:this.media;g.b.log("main buffered : "+p.a.toString(e.buffered)),this.fragPrevious=t;var r=this.stats;r.tbuffered=window.performance.now(),this.fragLastKbps=Math.round(8*r.total/(r.tbuffered-r.tfirst)),this.hls.trigger(d.a.FRAG_BUFFERED,{stats:r,frag:t,id:"main"}),this.state=T.IDLE}this.tick()}},e.prototype.onError=function(t){var e=t.frag||this.fragCurrent;if(!e||"main"===e.type){var r=!!this.media&&s.a.isBuffered(this.media,this.media.currentTime)&&s.a.isBuffered(this.media,this.media.currentTime+.5);switch(t.details){case v.a.FRAG_LOAD_ERROR:case v.a.FRAG_LOAD_TIMEOUT:case v.a.KEY_LOAD_ERROR:case v.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);g.b.warn("mediaController: frag loading failed, retry in "+i+" ms"),this.retryDate=window.performance.now()+i,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=T.FRAG_LOADING_WAITING_RETRY}else g.b.error("mediaController: "+t.details+" reaches max retry, redispatch as fatal ..."),t.fatal=!0,this.state=T.ERROR;break;case v.a.LEVEL_LOAD_ERROR:case v.a.LEVEL_LOAD_TIMEOUT:this.state!==T.ERROR&&(t.fatal?(this.state=T.ERROR,g.b.warn("streamController: "+t.details+",switch to "+this.state+" state ...")):t.levelRetry||this.state!==T.WAITING_LEVEL||(this.state=T.IDLE));break;case v.a.BUFFER_FULL_ERROR:"main"!==t.parent||this.state!==T.PARSING&&this.state!==T.PARSED||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=T.IDLE):(g.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;return e.maxMaxBufferLength>=t&&(e.maxMaxBufferLength/=2,g.b.warn("main:reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},e.prototype._checkBuffer=function(){var t=this.config,e=this.media;if(e&&0!==e.readyState){var r=e.currentTime,i=this.mediaBuffer?this.mediaBuffer:e,a=i.buffered;if(!this.loadedmetadata&&a.length)this.loadedmetadata=!0,this._seekToStartPos();else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var n=!(e.paused&&e.readyState>1||e.ended||0===e.buffered.length),o=window.performance.now();if(r!==this.lastCurrentTime)this.stallReported&&(g.b.warn("playback not stuck anymore @"+r+", after "+Math.round(o-this.stalled)+"ms"),this.stallReported=!1),this.stalled=null,this.nudgeRetry=0;else if(n){var l=o-this.stalled,d=s.a.bufferInfo(e,r,t.maxBufferHole);if(!this.stalled)return void(this.stalled=o);l>=1e3&&this._reportStall(d.len),this._tryFixBufferStall(d,l)}}}},e.prototype.onFragLoadEmergencyAborted=function(){this.state=T.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},e.prototype.onBufferFlushed=function(){var t=this.mediaBuffer?this.mediaBuffer:this.media;t&&this.fragmentTracker.detectEvictedFragments(f.a.ElementaryStreamTypes.VIDEO,t.buffered),this.state=T.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)},e.prototype._tryFixBufferStall=function(t,e){var r=this.config,i=this.media,a=i.currentTime,n=this.fragmentTracker.getPartialFragment(a);n&&this._trySkipBufferHole(n),t.len>.5&&e>1e3*r.highBufferWatchdogPeriod&&(this.stalled=null,this._tryNudgeBuffer())},e.prototype._reportStall=function(t){var e=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,g.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer"),e.trigger(d.a.ERROR,{type:v.b.MEDIA_ERROR,details:v.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:t}))},e.prototype._trySkipBufferHole=function(t){for(var e=this.hls,r=this.media,i=r.currentTime,a=0,n=0;n<r.buffered.length;n++){var o=r.buffered.start(n);if(i>=a&&i<o)return r.currentTime=Math.max(o,r.currentTime+.1),g.b.warn("skipping hole, adjusting currentTime from "+i+" to "+r.currentTime),this.stalled=null,void e.trigger(d.a.ERROR,{type:v.b.MEDIA_ERROR,details:v.a.BUFFER_SEEK_OVER_HOLE,fatal:!1,reason:"fragment loaded with buffer holes, seeking from "+i+" to "+r.currentTime,frag:t});a=r.buffered.end(n)}},e.prototype._tryNudgeBuffer=function(){var t=this.config,e=this.hls,r=this.media,i=r.currentTime,a=(this.nudgeRetry||0)+1;if(this.nudgeRetry=a,a<t.nudgeMaxRetry){var n=i+a*t.nudgeOffset;g.b.log("adjust currentTime from "+i+" to "+n),r.currentTime=n,e.trigger(d.a.ERROR,{type:v.b.MEDIA_ERROR,details:v.a.BUFFER_NUDGE_ON_STALL,fatal:!1})}else g.b.error("still stuck in high buffer @"+i+" after "+t.nudgeMaxRetry+", raise fatal error"),e.trigger(d.a.ERROR,{type:v.b.MEDIA_ERROR,details:v.a.BUFFER_STALLED_ERROR,fatal:!0})},e.prototype._seekToStartPos=function(){var t=this.media,e=t.currentTime,r=t.seeking?e:this.startPosition;e!==r&&(g.b.log("target start position not buffered, seek to buffered.start(0) "+r+" from current time "+e+" "),t.currentTime=r)},E(e,[{key:"state",set:function(t){if(this.state!==t){var e=this.state;this._state=t,g.b.log("main stream:"+e+"->"+t),this.hls.trigger(d.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}(y.a);e.a=S},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(8),n=r.n(a),o=r(30),s=r.n(o),l=r(1),d=r(18),u=r(0),f=r(2),c=r(10),h=r(5),p=Object(h.a)(),v=Object(c.a)(),g=function(){function t(e,r){i(this,t),this.hls=e,this.id=r;var a=this.observer=new n.a,o=e.config;a.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];a.emit.apply(a,[t,t].concat(r))},a.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];a.removeListener.apply(a,[t].concat(r))};var c=function(t,r){r=r||{},r.frag=this.frag,r.id=this.id,e.trigger(t,r)}.bind(this);a.on(l.a.FRAG_DECRYPTED,c),a.on(l.a.FRAG_PARSING_INIT_SEGMENT,c),a.on(l.a.FRAG_PARSING_DATA,c),a.on(l.a.FRAG_PARSED,c),a.on(l.a.ERROR,c),a.on(l.a.FRAG_PARSING_METADATA,c),a.on(l.a.FRAG_PARSING_USERDATA,c),a.on(l.a.INIT_PTS_FOUND,c);var h={mp4:v.isTypeSupported("video/mp4"),mpeg:v.isTypeSupported("audio/mpeg"),mp3:v.isTypeSupported('audio/mp4; codecs="mp3"')},g=navigator.vendor;if(o.enableWorker&&"undefined"!=typeof Worker){u.b.log("demuxing in webworker");var m=void 0;try{m=this.w=s()(43),this.onwmsg=this.onWorkerMessage.bind(this),m.addEventListener("message",this.onwmsg),m.onerror=function(t){e.trigger(l.a.ERROR,{type:f.b.OTHER_ERROR,details:f.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",err:{message:t.message+" ("+t.filename+":"+t.lineno+")"}})},m.postMessage({cmd:"init",typeSupported:h,vendor:g,id:r,config:JSON.stringify(o)})}catch(t){u.b.error("error while initializing DemuxerWorker, fallback on DemuxerInline"),m&&p.URL.revokeObjectURL(m.objectURL),this.demuxer=new d.a(a,h,o,g),this.w=void 0}}else this.demuxer=new d.a(a,h,o,g)}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,d=isNaN(a.startDTS)?a.start:a.startDTS,f=a.decryptdata,c=this.frag,h=!(c&&a.cc===c.cc),p=!(c&&a.level===c.level),v=c&&a.sn===c.sn+1,g=!p&&v;if(h&&u.b.log(this.id+":discontinuity detected"),p&&u.b.log(this.id+":switch detected"),this.frag=a,l)l.postMessage({cmd:"demux",data:t,decryptdata:f,initSegment:e,audioCodec:r,videoCodec:i,timeOffset:d,discontinuity:h,trackSwitch:p,contiguous:g,duration:n,accurateTimeOffset:o,defaultInitPTS:s},t instanceof ArrayBuffer?[t]:[]);else{var m=this.demuxer;m&&m.push(t,f,e,r,i,d,h,p,g,n,o,s)}},t.prototype.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":p.URL.revokeObjectURL(this.w.objectURL);break;case l.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}();e.a=g},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,e,i){var n={};n[i]=[];var o=e.toString(),s=o.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!s)return n;for(var u,f=s[1],c=new RegExp("(\\\\n|\\W)"+a(f)+d,"g");u=c.exec(o);)"dll-reference"!==u[3]&&n[i].push(u[3]);for(c=new RegExp("\\("+a(f)+'\\("(dll-reference\\s('+l+'))"\\)\\)'+d,"g");u=c.exec(o);)t[u[2]]||(n[i].push(u[1]),t[u[2]]=r(u[1]).m),n[u[2]]=n[u[2]]||[],n[u[2]].push(u[4]);return n}function o(t){return Object.keys(t).reduce(function(e,r){return e||t[r].length>0},!1)}function s(t,e){for(var r={main:[e]},i={main:[]},a={main:{}};o(r);)for(var s=Object.keys(r),l=0;l<s.length;l++){var d=s[l],u=r[d],f=u.pop();if(a[d]=a[d]||{},!a[d][f]&&t[d][f]){a[d][f]=!0,i[d]=i[d]||[],i[d].push(f);for(var c=n(t,t[d][f],d),h=Object.keys(c),p=0;p<h.length;p++)r[h[p]]=r[h[p]]||[],r[h[p]]=r[h[p]].concat(c[h[p]])}}return i}var l="[\\.|\\-|\\+|\\w|/|@]+",d="\\((/\\*.*?\\*/)?s?.*?("+l+").*?\\)";t.exports=function(t,e){e=e||{};var a={main:r.m},n=e.all?{main:Object.keys(a)}:s(a,t),o="";Object.keys(n).filter(function(t){return"main"!==t}).forEach(function(t){for(var e=0;n[t][e];)e++;n[t].push(e),a[t][e]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",o=o+"var "+t+" = ("+i.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+n[t].map(function(e){return JSON.stringify(e)+": "+a[t][e].toString()}).join(",")+"});\n"}),o=o+"("+i.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+n.main.map(function(t){return JSON.stringify(t)+": "+a.main[t].toString()}).join(",")+"})(self);";var l=new window.Blob([o],{type:"text/javascript"});if(e.bare)return l;var d=window.URL||window.webkitURL||window.mozURL||window.msURL,u=d.createObjectURL(l),f=new window.Worker(u);return f.objectURL=u,f}},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=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}();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")}var a=function(){function t(e,r){i(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}();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){var e=t.byteLength,r=e&&new DataView(t).getUint8(e-1);return r?t.slice(0,e-r):t}var n=function(){function t(){i(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],d=s[1],u=s[2],f=s[3],c=new Uint32Array(256),h=0,p=0,v=0;for(v=0;v<256;v++)c[v]=v<128?v<<1:v<<1^283;for(v=0;v<256;v++){var g=p^p<<1^p<<2^p<<3^p<<4;g=g>>>8^255&g^99,t[h]=g,e[g]=h;var m=c[h],y=c[m],b=c[y],E=257*c[g]^16843008*g;i[h]=E<<24|E>>>8,a[h]=E<<16|E>>>16,n[h]=E<<8|E>>>24,o[h]=E,E=16843009*b^65537*y^257*m^16843008*h,l[g]=E<<24|E>>>8,d[g]=E<<16|E>>>16,u[g]=E<<8|E>>>24,f[g]=E,h?(h=m^c[c[c[b^m]]],p^=c[c[p]]):h=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),d=this.invKeySchedule=new Uint32Array(n),u=this.sBox,f=this.rcon,c=this.invSubMix,h=c[0],p=c[1],v=c[2],g=c[3],m=void 0,y=void 0;for(o=0;o<n;o++)o<a?m=l[o]=e[o]:(y=m,o%a==0?(y=y<<8|y>>>24,y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[255&y],y^=f[o/a|0]<<24):a>6&&o%a==4&&(y=u[y>>>24]<<24|u[y>>>16&255]<<16|u[y>>>8&255]<<8|u[255&y]),l[o]=m=(l[o-a]^y)>>>0);for(s=0;s<n;s++)o=n-s,y=3&s?l[o]:l[o-4],d[s]=s<4||o<=4?y:h[u[y>>>24]]^p[u[y>>>16&255]]^v[u[y>>>8&255]]^g[u[255&y]],d[s]=d[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,i){for(var n=this.keySize+6,o=this.invKeySchedule,s=this.invSBox,l=this.invSubMix,d=l[0],u=l[1],f=l[2],c=l[3],h=this.uint8ArrayToUint32Array_(r),p=h[0],v=h[1],g=h[2],m=h[3],y=new Int32Array(t),b=new Int32Array(y.length),E=void 0,T=void 0,S=void 0,A=void 0,_=void 0,R=void 0,L=void 0,w=void 0,D=void 0,O=void 0,I=void 0,x=void 0,k=void 0,P=void 0,C=this.networkToHostOrderSwap;e<y.length;){for(D=C(y[e]),O=C(y[e+1]),I=C(y[e+2]),x=C(y[e+3]),_=D^o[0],R=x^o[1],L=I^o[2],w=O^o[3],k=4,P=1;P<n;P++)E=d[_>>>24]^u[R>>16&255]^f[L>>8&255]^c[255&w]^o[k],T=d[R>>>24]^u[L>>16&255]^f[w>>8&255]^c[255&_]^o[k+1],S=d[L>>>24]^u[w>>16&255]^f[_>>8&255]^c[255&R]^o[k+2],A=d[w>>>24]^u[_>>16&255]^f[R>>8&255]^c[255&L]^o[k+3],_=E,R=T,L=S,w=A,k+=4;E=s[_>>>24]<<24^s[R>>16&255]<<16^s[L>>8&255]<<8^s[255&w]^o[k],T=s[R>>>24]<<24^s[L>>16&255]<<16^s[w>>8&255]<<8^s[255&_]^o[k+1],S=s[L>>>24]<<24^s[w>>16&255]<<16^s[_>>8&255]<<8^s[255&R]^o[k+2],A=s[w>>>24]<<24^s[_>>16&255]<<16^s[R>>8&255]<<8^s[255&L]^o[k+3],k+=3,b[e]=C(E^p),b[e+1]=C(A^v),b[e+2]=C(S^g),b[e+3]=C(T^m),p=D,v=O,g=I,m=x,e+=4}return i?a(b.buffer):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}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(20),n=r(0),o=r(9),s=function(){function t(e,r,a){i(this,t),this.observer=e,this.config=a,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=o.a.getID3Data(t,0)||[],r=e.length,i=t.length;r<i;r++)if(a.e(t,r))return n.b.log("ADTS sync word found !"),!0;return!1},t.prototype.append=function(t,e,r,i){for(var s=this._audioTrack,l=o.a.getID3Data(t,0)||[],d=o.a.getTimeStamp(l),u=d?90*d:9e4*e,f=0,c=u,h=t.length,p=l.length,v=[{pts:c,dts:c,data:l}];p<h-1;)if(a.d(t,p)&&p+5<h){a.c(s,this.observer,t,p,s.manifestCodec);var g=a.a(s,t,p,u,f);if(!g){n.b.log("Unable to parse AAC frame");break}p+=g.length,c=g.sample.pts,f++}else o.a.isHeader(t,p)?(l=o.a.getID3Data(t,p),v.push({pts:c,dts:c,data:l}),p+=l.length):p++;this.remuxer.remux(s,{samples:[]},{samples:v,inputTimeScale:9e4},{samples:[]},e,r,i)},t.prototype.destroy=function(){},t}();e.a=s},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(20),n=r(21),o=r(1),s=r(36),l=r(37),d=r(0),u=r(2),f={video:1,audio:2,id3:3,text:4},c=function(){function t(e,r,a,n){i(this,t),this.observer=e,this.config=a,this.typeSupported=n,this.remuxer=r,this.sampleAes=null}return t.prototype.setDecryptData=function(t){null!=t&&null!=t.key&&"SAMPLE-AES"===t.method?this.sampleAes=new l.a(this.observer,this.config,t,this.discardEPB):this.sampleAes=null},t.probe=function(e){var r=t._syncOffset(e);return!(r<0)&&(r&&d.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:f[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=void 0,s=e.length,l=void 0,f=void 0,c=void 0,h=void 0,p=!1;this.contiguous=i;var v=this.pmtParsed,g=this._avcTrack,m=this._audioTrack,y=this._id3Track,b=g.pid,E=m.pid,T=y.pid,S=this._pmtId,A=g.pesData,_=m.pesData,R=y.pesData,L=this._parsePAT,w=this._parsePMT,D=this._parsePES,O=this._parseAVCPES.bind(this),I=this._parseAACPES.bind(this),x=this._parseMPEGPES.bind(this),k=this._parseID3PES.bind(this),P=t._syncOffset(e);for(s-=(s+P)%188,n=P;n<s;n+=188)if(71===e[n]){if(l=!!(64&e[n+1]),f=((31&e[n+1])<<8)+e[n+2],(48&e[n+3])>>4>1){if((c=n+5+e[n+4])===n+188)continue}else c=n+4;switch(f){case b:l&&(A&&(h=D(A))&&void 0!==h.pts&&O(h,!1),A={data:[],size:0}),A&&(A.data.push(e.subarray(c,n+188)),A.size+=n+188-c);break;case E:l&&(_&&(h=D(_))&&void 0!==h.pts&&(m.isAAC?I(h):x(h)),_={data:[],size:0}),_&&(_.data.push(e.subarray(c,n+188)),_.size+=n+188-c);break;case T:l&&(R&&(h=D(R))&&void 0!==h.pts&&k(h),R={data:[],size:0}),R&&(R.data.push(e.subarray(c,n+188)),R.size+=n+188-c);break;case 0:l&&(c+=e[c]+1),S=this._pmtId=L(e,c);break;case S:l&&(c+=e[c]+1);var C=w(e,c,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);b=C.avc,b>0&&(g.pid=b),E=C.audio,E>0&&(m.pid=E,m.isAAC=C.isAAC),T=C.id3,T>0&&(y.pid=T),p&&!v&&(d.b.log("reparse from beginning"),p=!1,n=P-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=!0}}else this.observer.trigger(o.a.ERROR,{type:u.b.MEDIA_ERROR,details:u.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});A&&(h=D(A))&&void 0!==h.pts?(O(h,!0),g.pesData=null):g.pesData=A,_&&(h=D(_))&&void 0!==h.pts?(m.isAAC?I(h):x(h),m.pesData=null):(_&&_.size&&d.b.log("last AAC PES packet truncated,might overlap between fragments"),m.pesData=_),R&&(h=D(R))&&void 0!==h.pts?(k(h),y.pesData=null):y.pesData=R,null==this.sampleAes?this.remuxer.remux(m,g,y,this._txtTrack,r,i,a):this.decryptAndRemux(m,g,y,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=void 0,n=void 0,o=void 0,s=void 0,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){d.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){d.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):d.b.log("MPEG audio found, not supported in this browser for now");break;case 36:d.b.warn("HEVC stream type found, not supported for now");break;default:d.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=0,r=void 0,i=void 0,a=void 0,n=void 0,o=void 0,s=void 0,l=void 0,u=void 0,f=t.data;if(!t||0===t.size)return null;for(;f[0].length<19&&f.length>1;){var c=new Uint8Array(f[0].length+f[1].length);c.set(f[0]),c.set(f[1],f[0].length),f[0]=c,f.splice(1,1)}if(r=f[0],1===(r[0]<<16)+(r[1]<<8)+r[2]){if((a=(r[4]<<8)+r[5])&&a>t.size-6)return null;i=r[7],192&i&&(s=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,s>4294967295&&(s-=8589934592),64&i?(l=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2,l>4294967295&&(l-=8589934592),s-l>54e5&&(d.b.warn(Math.round((s-l)/9e4)+"s delta between PTS and DTS, align them"),s=l)):l=s),n=r[8],u=n+9,t.size-=u,o=new Uint8Array(t.size);for(var h=0,p=f.length;h<p;h++){r=f[h];var v=r.byteLength;if(u){if(u>v){u-=v;continue}r=r.subarray(u),v-=u,u=0}o.set(r,e),e+=v}return a&&(a-=n+3),{data:o,pts:s,dts:l,len:a}}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&&d.b.log(t.pts+"/"+t.dts+":"+t.debug)},t.prototype._parseAVCPES=function(t,e){var r=this,i=this._avcTrack,a=this._parseAVCNALu(t.data),n=void 0,o=this.avcSample,l=void 0,d=!1,u=void 0,f=this.pushAccesUnit.bind(this),c=function(t,e,r,i){return{key:t,pts:e,dts:r,units:[],debug:i}};t.data=null,o&&a.length&&!i.audFound&&(f(o,i),o=this.avcSample=c(!1,t.pts,t.dts,"")),a.forEach(function(e){switch(e.type){case 1:l=!0,o||(o=r.avcSample=c(!0,t.pts,t.dts,"")),o.frame=!0;var a=e.data;if(d&&a.length>4){var h=new s.a(a).readSliceType();2!==h&&4!==h&&7!==h&&9!==h||(o.key=!0)}break;case 5:l=!0,o||(o=r.avcSample=c(!0,t.pts,t.dts,"")),o.key=!0,o.frame=!0;break;case 6:l=!0,n=new s.a(r.discardEPB(e.data)),n.readUByte();for(var p=0,v=0,g=!1,m=0;!g&&n.bytesAvailable>1;){p=0;do{m=n.readUByte(),p+=m}while(255===m);v=0;do{m=n.readUByte(),v+=m}while(255===m);if(4===p&&0!==n.bytesAvailable){g=!0;if(181===n.readUByte()){if(49===n.readUShort()){if(1195456820===n.readUInt()){if(3===n.readUByte()){var y=n.readUByte(),b=n.readUByte(),E=31&y,T=[y,b];for(u=0;u<E;u++)T.push(n.readUByte()),T.push(n.readUByte()),T.push(n.readUByte());r._insertSampleInOrder(r._txtTrack.samples,{type:3,pts:t.pts,bytes:T})}}}}}else if(v<n.bytesAvailable)for(u=0;u<v;u++)n.readUByte()}break;case 7:if(l=!0,d=!0,!i.sps){n=new s.a(e.data);var S=n.readSPS();i.width=S.width,i.height=S.height,i.pixelRatio=S.pixelRatio,i.sps=[e.data],i.duration=r._duration;var A=e.data.subarray(1,4),_="avc1.";for(u=0;u<3;u++){var R=A[u].toString(16);R.length<2&&(R="0"+R),_+=R}i.codec=_}break;case 8:l=!0,i.pps||(i.pps=[e.data]);break;case 9:l=!1,i.audFound=!0,o&&f(o,i),o=r.avcSample=c(!1,t.pts,t.dts,"");break;case 12:l=!1;break;default:l=!1,o&&(o.debug+="unknown NAL "+e.type+" ")}if(o&&l){o.units.push(e)}}),e&&o&&(f(o,i),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=0,r=t.byteLength,i=void 0,a=void 0,n=this._avcTrack,o=n.naluState||0,s=o,l=[],d=void 0,u=void 0,f=-1,c=void 0;for(-1===o&&(f=0,c=31&t[0],o=0,e=1);e<r;)if(i=t[e++],o)if(1!==o)if(i)if(1===i){if(f>=0)d={data:t.subarray(f,e-o-1),type:c},l.push(d);else{var h=this._getLastNalUnit();if(h&&(s&&e<=4-s&&h.state&&(h.data=h.data.subarray(0,h.data.byteLength-s)),(a=e-o-1)>0)){var p=new Uint8Array(h.data.byteLength+a);p.set(h.data,0),p.set(t.subarray(0,a),h.data.byteLength),h.data=p}}e<r?(u=31&t[e],f=e,c=u,o=0):o=-1}else o=0;else o=3;else o=i?0:2;else o=i?0:1;if(f>=0&&o>=0&&(d={data:t.subarray(f,r),type:c,state:o},l.push(d)),0===l.length){var v=this._getLastNalUnit();if(v){var g=new Uint8Array(v.data.byteLength+t.byteLength);g.set(v.data,0),g.set(t,v.data.byteLength),v.data=g}}return n.naluState=o,l},t.prototype.discardEPB=function(t){for(var e=t.byteLength,r=[],i=1,a=void 0,n=void 0;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return t;a=e-r.length,n=new Uint8Array(a);var o=0;for(i=0;i<a;o++,i++)o===r[0]&&(o++,r.shift()),n[i]=t[o];return n},t.prototype._parseAACPES=function(t){var e=this._audioTrack,r=t.data,i=t.pts,n=this.aacOverFlow,s=this.aacLastPTS,l=void 0,f=void 0,c=void 0,h=void 0,p=void 0;if(n){var v=new Uint8Array(n.byteLength+r.byteLength);v.set(n,0),v.set(r,n.byteLength),r=v}for(c=0,p=r.length;c<p-1&&!a.d(r,c);c++);if(c){var g=void 0,m=void 0;if(c<p-1?(g="AAC PES did not start with ADTS header,offset:"+c,m=!1):(g="no ADTS header found in AAC PES",m=!0),d.b.warn("parsing error:"+g),this.observer.trigger(o.a.ERROR,{type:u.b.MEDIA_ERROR,details:u.a.FRAG_PARSING_ERROR,fatal:m,reason:g}),m)return}if(a.c(e,this.observer,r,c,this.audioCodec),f=0,l=a.b(e.samplerate),n&&s){var y=s+l;Math.abs(y-i)>1&&(d.b.log("AAC: align PTS for overlapping frames by "+Math.round((y-i)/90)),i=y)}for(;c<p;)if(a.d(r,c)&&c+5<p){var b=a.a(e,r,c,i,f);if(!b)break;c+=b.length,h=b.sample.pts,f++}else c++;n=c<p?r.subarray(c,p):null,this.aacOverFlow=n,this.aacLastPTS=h},t.prototype._parseMPEGPES=function(t){for(var e=t.data,r=e.length,i=0,a=0,o=t.pts;a<r;)if(n.a.isHeader(e,a)){var s=n.a.appendFrame(this._audioTrack,e,a,o,i);if(!s)break;a+=s.length,i++}else a++},t.prototype._parseID3PES=function(t){this._id3Track.samples.push(t)},t}();e.a=c},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(0),n=function(){function t(e){i(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=void 0;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&&a.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=void 0;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=8,r=8,i=void 0,a=void 0;for(i=0;i<t;i++)0!==r&&(a=this.readEG(),r=(e+a+256)%256),e=0===r?e:r},t.prototype.readSPS=function(){var t=0,e=0,r=0,i=0,a=void 0,n=void 0,o=void 0,s=void 0,l=void 0,d=void 0,u=void 0,f=this.readUByte.bind(this),c=this.readBits.bind(this),h=this.readUEG.bind(this),p=this.readBoolean.bind(this),v=this.skipBits.bind(this),g=this.skipEG.bind(this),m=this.skipUEG.bind(this),y=this.skipScalingList.bind(this);if(f(),a=f(),c(5),v(3),f(),m(),100===a||110===a||122===a||244===a||44===a||83===a||86===a||118===a||128===a){var b=h();if(3===b&&v(1),m(),m(),v(1),p())for(d=3!==b?8:12,u=0;u<d;u++)p()&&y(u<6?16:64)}m();var E=h();if(0===E)h();else if(1===E)for(v(1),g(),g(),n=h(),u=0;u<n;u++)g();m(),v(1),o=h(),s=h(),l=c(1),0===l&&v(1),v(1),p()&&(t=h(),e=h(),r=h(),i=h());var T=[1,1];if(p()&&p()){switch(f()){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=[f()<<8|f(),f()<<8|f()]}}return{width:Math.ceil(16*(o+1)-2*t-2*e),height:(2-l)*(s+1)*16-(l?2:4)*(r+i),pixelRatio:T}},t.prototype.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},t}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(19),n=function(){function t(e,r,n,o){i(this,t),this.decryptdata=n,this.discardEPB=o,this.decrypter=new a.a(e,r,{removePKCS7Padding:!1})}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}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(9),n=r(0),o=r(21),s=function(){function t(e,r,a){i(this,t),this.observer=e,this.config=a,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=void 0,r=void 0,i=a.a.getID3Data(t,0);if(i&&void 0!==a.a.getTimeStamp(i))for(e=i.length,r=Math.min(t.length-1,e+100);e<r;e++)if(o.a.probe(t,e))return n.b.log("MPEG Audio sync word found !"),!0;return!1},t.prototype.append=function(t,e,r,i){for(var n=a.a.getID3Data(t,0),s=a.a.getTimeStamp(n),l=s?90*s:9e4*e,d=n.length,u=t.length,f=0,c=0,h=this._audioTrack,p=[{pts:l,dts:l,data:n}];d<u;)if(o.a.isHeader(t,d)){var v=o.a.appendFrame(h,t,d,l,f);if(!v)break;d+=v.length,c=v.sample.pts,f++}else a.a.isHeader(t,d)?(n=a.a.getID3Data(t,d),p.push({pts:c,dts:c,data:n}),d+=n.length):d++;this.remuxer.remux(h,{samples:[]},{samples:p,inputTimeScale:9e4},{samples:[]},e,r,i)},t.prototype.destroy=function(){},t}();e.a=s},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(40),n=r(41),o=r(1),s=r(2),l=r(0),d=function(){function t(e,r,a,n){i(this,t),this.observer=e,this.config=r,this.typeSupported=a;var o=navigator.userAgent;this.isSafari=n&&n.indexOf("Apple")>-1&&o&&!o.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,s){if(this.ISGenerated||this.generateIS(t,e,a),this.ISGenerated){var d=t.samples.length,u=e.samples.length,f=a,c=a;if(d&&u){var h=(t.samples[0].dts-e.samples[0].dts)/e.inputTimeScale;f+=Math.max(0,h),c+=Math.max(0,-h)}if(d){t.timescale||(l.b.warn("regenerate InitSegment as audio detected"),this.generateIS(t,e,a));var p=this.remuxAudio(t,f,n,s);if(u){var v=void 0;p&&(v=p.endPTS-p.startPTS),e.timescale||(l.b.warn("regenerate InitSegment as video detected"),this.generateIS(t,e,a)),this.remuxVideo(e,c,n,v,s)}}else if(u){var g=this.remuxVideo(e,c,n,0,s);g&&t.codec&&this.remuxEmptyAudio(t,f,n,g)}}r.samples.length&&this.remuxID3(r,a),i.samples.length&&this.remuxText(i,a),this.observer.trigger(o.a.FRAG_PARSED)},t.prototype.generateIS=function(t,e,r){var i=this.observer,a=t.samples,d=e.samples,u=this.typeSupported,f="audio/mp4",c={},h={tracks:c},p=void 0===this._initPTS,v=void 0,g=void 0;if(p&&(v=g=1/0),t.config&&a.length&&(t.timescale=t.samplerate,l.b.log("audio sampling rate : "+t.samplerate),t.isAAC||(u.mpeg?(f="audio/mpeg",t.codec=""):u.mp3&&(t.codec="mp3")),c.audio={container:f,codec:t.codec,initSegment:!t.isAAC&&u.mpeg?new Uint8Array:n.a.initSegment([t]),metadata:{channelCount:t.channelCount}},p&&(v=g=a[0].pts-t.inputTimeScale*r)),e.sps&&e.pps&&d.length){var m=e.inputTimeScale;e.timescale=m,c.video={container:"video/mp4",codec:e.codec,initSegment:n.a.initSegment([e]),metadata:{width:e.width,height:e.height}},p&&(v=Math.min(v,d[0].pts-m*r),g=Math.min(g,d[0].dts-m*r),this.observer.trigger(o.a.INIT_PTS_FOUND,{initPTS:v}))}Object.keys(c).length?(i.trigger(o.a.FRAG_PARSING_INIT_SEGMENT,h),this.ISGenerated=!0,p&&(this._initPTS=v,this._initDTS=g)):i.trigger(o.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},t.prototype.remuxVideo=function(t,e,r,i,a){var d=8,u=t.timescale,f=void 0,c=void 0,h=void 0,p=void 0,v=void 0,g=void 0,m=void 0,y=t.samples,b=[],E=y.length,T=this._PTSNormalize,S=this._initDTS,A=this.nextAvcDts,_=this.isSafari;if(0!==E){_&&(r|=y.length&&A&&(a&&Math.abs(e-A/u)<.1||Math.abs(y[0].pts-A-S)<u/5)),r||(A=e*u),y.forEach(function(t){t.pts=T(t.pts-S,A),t.dts=T(t.dts-S,A)}),y.sort(function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i||t.id-e.id});var R=y.reduce(function(t,e){return Math.max(Math.min(t,e.pts-e.dts),-18e3)},0);if(R<0){l.b.warn("PTS < DTS detected in video samples, shifting DTS by "+Math.round(R/90)+" ms to overcome this issue");for(var L=0;L<y.length;L++)y[L].dts+=R}var w=y[0];v=Math.max(w.dts,0),p=Math.max(w.pts,0);var D=Math.round((v-A)/90);r&&D&&(D>1?l.b.log("AVC:"+D+" ms hole between fragments detected,filling it"):D<-1&&l.b.log("AVC:"+-D+" ms overlapping between fragments detected"),v=A,y[0].dts=v,p=Math.max(p-D,A),y[0].pts=p,l.b.log("Video/PTS/DTS adjusted: "+Math.round(p/90)+"/"+Math.round(v/90)+",delta:"+D+" ms")),v,w=y[y.length-1],m=Math.max(w.dts,0),g=Math.max(w.pts,0,m),_&&(f=Math.round((m-v)/(y.length-1)));for(var O=0,I=0,x=0;x<E;x++){for(var k=y[x],P=k.units,C=P.length,F=0,M=0;M<C;M++)F+=P[M].data.length;I+=F,O+=C,k.length=F,k.dts=_?v+x*f:Math.max(k.dts,v),k.pts=Math.max(k.pts,k.dts)}var N=I+4*O+8;try{c=new Uint8Array(N)}catch(t){return void this.observer.trigger(o.a.ERROR,{type:s.b.MUX_ERROR,details:s.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:N,reason:"fail allocating video mdat "+N})}var U=new DataView(c.buffer);U.setUint32(0,N),c.set(n.a.types.mdat,4);for(var B=0;B<E;B++){for(var G=y[B],j=G.units,K=0,H=void 0,V=0,W=j.length;V<W;V++){var Y=j[V],z=Y.data,X=Y.data.byteLength;U.setUint32(d,X),d+=4,c.set(z,d),d+=X,K+=4+X}if(_)H=Math.max(0,f*Math.round((G.pts-G.dts)/f));else{if(B<E-1)f=y[B+1].dts-G.dts;else{var q=this.config,Q=G.dts-y[B>0?B-1:B].dts;if(q.stretchShortVideoTrack){var Z=q.maxBufferHole,J=Math.floor(Z*u),$=(i?p+i*u:this.nextAudioPts)-G.pts;$>J?(f=$-Q,f<0&&(f=Q),l.b.log("It is approximately "+$/90+" ms to the next segment; using duration "+f/90+" ms for the last video frame.")):f=Q}else f=Q}H=Math.round(G.pts-G.dts)}b.push({size:K,duration:f,cts:H,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:G.key?2:1,isNonSync:G.key?0:1}})}this.nextAvcDts=m+f;var tt=t.dropped;if(t.len=0,t.nbNalu=0,t.dropped=0,b.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var et=b[0].flags;et.dependsOn=2,et.isNonSync=0}t.samples=b,h=n.a.moof(t.sequenceNumber++,v,t),t.samples=[];var rt={data1:h,data2:c,startPTS:p/u,endPTS:(g+f)/u,startDTS:v/u,endDTS:this.nextAvcDts/u,type:"video",hasAudio:!1,hasVideo:!0,nb:b.length,dropped:tt};return this.observer.trigger(o.a.FRAG_PARSING_DATA,rt),rt}},t.prototype.remuxAudio=function(t,e,r,i){var d=t.inputTimeScale,u=t.timescale,f=d/u,c=t.isAAC?1024:1152,h=c*f,p=this._PTSNormalize,v=this._initDTS,g=!t.isAAC&&this.typeSupported.mpeg,m=void 0,y=void 0,b=void 0,E=void 0,T=void 0,S=void 0,A=void 0,_=t.samples,R=[],L=this.nextAudioPts;if(r|=_.length&&L&&(i&&Math.abs(e-L/d)<.1||Math.abs(_[0].pts-L-v)<20*h),_.forEach(function(t){t.pts=t.dts=p(t.pts-v,e*d)}),_=_.filter(function(t){return t.pts>=0}),0!==_.length){if(r||(L=i?e*d:_[0].pts),t.isAAC)for(var w=this.config.maxAudioFramesDrift,D=0,O=L;D<_.length;){var I,x=_[D],k=x.pts;I=k-O;var P=Math.abs(1e3*I/d);if(I<=-w*h)l.b.warn("Dropping 1 audio frame @ "+(O/d).toFixed(3)+"s due to "+Math.round(P)+" ms overlap."),_.splice(D,1),t.len-=x.unit.length;else if(I>=w*h&&P<1e4&&O){var C=Math.round(I/h);l.b.warn("Injecting "+C+" audio frame @ "+(O/d).toFixed(3)+"s due to "+Math.round(1e3*I/d)+" ms gap.");for(var F=0;F<C;F++){var M=Math.max(O,0);b=a.a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),b||(l.b.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),b=x.unit.subarray()),_.splice(D,0,{unit:b,pts:M,dts:M}),t.len+=b.length,O+=h,D++}x.pts=x.dts=O,O+=h,D++}else Math.abs(I),x.pts=x.dts=O,O+=h,D++}for(var N=0,U=_.length;N<U;N++){var B=_[N],G=B.unit,j=B.pts;if(void 0!==A)y.duration=Math.round((j-A)/f);else{var K=Math.round(1e3*(j-L)/d),H=0;if(r&&t.isAAC&&K){if(K>0&&K<1e4)H=Math.round((j-L)/h),l.b.log(K+" ms hole between AAC samples detected,filling it"),H>0&&(b=a.a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),b||(b=G.subarray()),t.len+=H*b.length);else if(K<-12){l.b.log("drop overlapping AAC sample, expected/parsed/delta:"+(L/d).toFixed(3)+"s/"+(j/d).toFixed(3)+"s/"+-K+"ms"),t.len-=G.byteLength;continue}j=L}if(S=j,!(t.len>0))return;var V=g?t.len:t.len+8;m=g?0:8;try{E=new Uint8Array(V)}catch(t){return void this.observer.trigger(o.a.ERROR,{type:s.b.MUX_ERROR,details:s.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:V,reason:"fail allocating audio mdat "+V})}if(!g){new DataView(E.buffer).setUint32(0,V),E.set(n.a.types.mdat,4)}for(var W=0;W<H;W++)b=a.a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),b||(l.b.log("Unable to get silent frame for given audio codec; duplicating this frame instead."),b=G.subarray()),E.set(b,m),m+=b.byteLength,y={size:b.byteLength,cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},R.push(y)}E.set(G,m);var Y=G.byteLength;m+=Y,y={size:Y,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},R.push(y),A=j}var z=0,X=R.length;if(X>=2&&(z=R[X-2].duration,y.duration=z),X){this.nextAudioPts=L=A+f*z,t.len=0,t.samples=R,T=g?new Uint8Array:n.a.moof(t.sequenceNumber++,S/f,t),t.samples=[];var q=S/d,Q=L/d,Z={data1:T,data2:E,startPTS:q,endPTS:Q,startDTS:q,endDTS:Q,type:"audio",hasAudio:!0,hasVideo:!1,nb:X};return this.observer.trigger(o.a.FRAG_PARSING_DATA,Z),Z}return null}},t.prototype.remuxEmptyAudio=function(t,e,r,i){var n=t.inputTimeScale,o=t.samplerate?t.samplerate:n,s=n/o,d=this.nextAudioPts,u=(void 0!==d?d:i.startDTS*n)+this._initDTS,f=i.endDTS*n+this._initDTS,c=1024*s,h=Math.ceil((f-u)/c),p=a.a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(l.b.warn("remux empty Audio"),!p)return void l.b.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!");for(var v=[],g=0;g<h;g++){var m=u+g*c;v.push({unit:p,pts:m,dts:m}),t.len+=p.length}t.samples=v,this.remuxAudio(t,e,r)},t.prototype.remuxID3=function(t,e){var r=t.samples.length,i=void 0,a=t.inputTimeScale,n=this._initPTS,s=this._initDTS;if(r){for(var l=0;l<r;l++)i=t.samples[l],i.pts=(i.pts-n)/a,i.dts=(i.dts-s)/a;this.observer.trigger(o.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=t.samples.length,i=void 0,a=t.inputTimeScale,n=this._initPTS;if(r){for(var s=0;s<r;s++)i=t.samples[s],i.pts=(i.pts-n)/a;this.observer.trigger(o.a.FRAG_PARSING_USERDATA,{samples:t.samples})}t.samples=[],e=e},t.prototype._PTSNormalize=function(t,e){var r=void 0;if(void 0===e)return t;for(r=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=r;return t},t}();e.a=d},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=function(){function t(){i(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}();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")}var a=Math.pow(2,32)-1,n=function(){function t(){i(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=void 0;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=Array.prototype.slice.call(arguments,1),r=8,i=e.length,a=i,n=void 0;i--;)r+=e[i].byteLength;for(n=new Uint8Array(r),n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),i=0,r=8;i<a;i++)n.set(e[i],r),r+=e[i].byteLength;return n},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/(a+1)),n=Math.floor(r%(a+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,n>>24,n>>16&255,n>>8&255,255&n,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/(a+1)),n=Math.floor(r%(a+1)),o=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,n>>24,n>>16&255,n>>8&255,255&n,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,o)},t.sdtp=function(e){var r=e.samples||[],i=new Uint8Array(4+r.length),a=void 0,n=void 0;for(n=0;n<r.length;n++)a=r[n].flags,i[n+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return t.box(t.types.sdtp,i)},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=void 0,n=void 0,o=void 0;for(a=0;a<e.sps.length;a++)n=e.sps[a],o=n.byteLength,r.push(o>>>8&255),r.push(255&o),r=r.concat(Array.prototype.slice.call(n));for(a=0;a<e.pps.length;a++)n=e.pps[a],o=n.byteLength,i.push(o>>>8&255),i.push(255&o),i=i.concat(Array.prototype.slice.call(n));var s=t.box(t.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(i))),l=e.width,d=e.height,u=e.pixelRatio[0],f=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,d>>8&255,255&d,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([u>>24,u>>16&255,u>>8&255,255&u,f>>24,f>>16&255,f>>8&255,255&f])))},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,n=e.width,o=e.height,s=Math.floor(i/(a+1)),l=Math.floor(i%(a+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,s>>24,s>>16&255,s>>8&255,255&s,l>>24,l>>16&255,l>>8&255,255&l,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,n>>8&255,255&n,0,0,o>>8&255,255&o,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),n=e.id,o=Math.floor(r/(a+1)),s=Math.floor(r%(a+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,s>>24,s>>16&255,s>>8&255,255&s])),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=e.samples||[],a=i.length,n=12+16*a,o=new Uint8Array(n),s=void 0,l=void 0,d=void 0,u=void 0,f=void 0,c=void 0;for(r+=8+n,o.set([0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,255&a,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),s=0;s<a;s++)l=i[s],d=l.duration,u=l.size,f=l.flags,c=l.cts,o.set([d>>>24&255,d>>>16&255,d>>>8&255,255&d,u>>>24&255,u>>>16&255,u>>>8&255,255&u,f.isLeading<<2|f.dependsOn,f.isDependedOn<<6|f.hasRedundancy<<4|f.paddingValue<<1|f.isNonSync,61440&f.degradPrio,15&f.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*s);return t.box(t.types.trun,o)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=void 0;return i=new Uint8Array(t.FTYP.byteLength+r.byteLength),i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(1),n=function(){function t(e){i(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,n,o,s,l){var d=this.observer,u="";t&&(u+="audio"),e&&(u+="video"),d.trigger(a.a.FRAG_PARSING_DATA,{data1:l,startPTS:n,startDTS:n,type:u,hasAudio:!!t,hasVideo:!!e,nb:1,dropped:0}),d.trigger(a.a.FRAG_PARSED)},t}();e.a=n},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=r(18),a=r(1),n=r(0),o=r(8),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},function(t,e,r){"use strict";var i={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}};e.a=i},function(t,e,r){"use strict";function i(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,r){var i=!1;return e&&e.details&&r&&(r.endCC>r.startCC||t&&t.cc<r.startCC)&&(i=!0),i}function n(t,e){var r=t.fragments,a=e.fragments;if(!a.length||!r.length)return void l.b.log("No fragments to align");var n=i(r,a[0].cc);return!n||n&&!n.startPTS?void l.b.log("No frag in previous level to align on"):n}function o(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 s(t,e,r){if(a(t,e,r)){var i=n(e.details,r);i&&(l.b.log("Adjusting PTS using last level due to CC increase within current level"),o(i.start,r))}if(!1===r.PTSKnown&&e&&e.details&&e.details.fragments&&e.details.fragments.length){var s=e.details.programDateTime,d=r.programDateTime,u=(d-s)/1e3+e.details.fragments[0].start;isNaN(u)||(l.b.log("adjusting PTS using programDateTime delta, sliding:"+u.toFixed(3)),o(u,r))}}e.a=s;var l=(r(7),r(0))},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)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)}var o=r(3),s=function(t){function e(r){i(this,e);for(var n=arguments.length,o=Array(n>1?n-1:0),s=1;s<n;s++)o[s-1]=arguments[s];var l=a(this,t.call.apply(t,[this,r].concat(o)));return l._tickInterval=null,l._tickTimer=null,l._tickCallCount=0,l._boundTick=l.tick.bind(l),l}return n(e,t),e.prototype.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.prototype.hasInterval=function(){return!!this._tickInterval},e.prototype.hasNextTick=function(){return!!this._tickTimer},e.prototype.setInterval=function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(t){return!this._tickInterval&&(this._tickInterval=setInterval(this._boundTick,t),!0)}),e.prototype.clearInterval=function(t){function e(){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(){return!!this._tickInterval&&(clearInterval(this._tickInterval),this._tickInterval=null,!0)}),e.prototype.clearNextTick=function(){return!!this._tickTimer&&(clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.prototype.tick=function(){1===++this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&(this.clearNextTick(),this._tickTimer=setTimeout(this._boundTick,0)),this._tickCallCount=0)},e.prototype.doTick=function(){},e}(o.a);e.a=s},function(t,e,r){"use strict";function i(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments[2],i=0;if(r.programDateTime){var a=Date.parse(r.programDateTime);isNaN(a)||(i=1e3*e+a-1e3*t)}return i}function a(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(!Array.isArray(t)||!t.length||null===e)return null;if(e<t[0].pdt)return null;if(e>=t[t.length-1].endPdt)return null;for(var r=0;r<t.length;++r){var i=t[r];if(e<i.endPdt)return i}return null}function n(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,n=void 0,l=t?e[t.sn-e[0].sn+1]:null;return r<i&&(r>i-a&&(a=0),n=l&&!o(r,a,l)?l:s.a.search(e,o.bind(null,r,a))),n}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments[2],i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}e.a=i,e.b=a,e.c=n,e.d=o;var s=r(7)},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)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)}var o=r(1),s=r(3),l=r(0),d=r(2),u=r(15),f=r(22),c="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},h=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}}(),p=window,v=p.performance,g=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MANIFEST_LOADED,o.a.LEVEL_LOADED,o.a.AUDIO_TRACK_SWITCHED,o.a.FRAG_LOADED,o.a.ERROR));return n.canload=!1,n.currentLevelIndex=null,n.manualLevelIndex=-1,n.timer=null,n}return n(e,t),e.prototype.onHandlerDestroying=function(){this.clearTimer(),this.manualLevelIndex=-1},e.prototype.clearTimer=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)}),null!==this.timer&&this.loadLevel()},e.prototype.stopLoad=function(){this.canload=!1},e.prototype.onManifestLoaded=function(t){var e=[],r=void 0,i={},a=null,n=!1,s=!1,c=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),h=[];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),c&&t.audioCodec&&-1!==t.audioCodec.indexOf("mp4a.40.34")&&(t.audioCodec=void 0),a=i[t.bitrate],a?a.url.push(t.url):(t.url=[t.url],t.urlId=0,i[t.bitrate]=t,e.push(t)),t.attrs&&t.attrs.AUDIO&&Object(f.a)(a||t,"audio",t.attrs.AUDIO),t.attrs&&t.attrs.SUBTITLES&&Object(f.a)(a||t,"text",t.attrs.SUBTITLES)}),n&&s&&(e=e.filter(function(t){return!!t.videoCodec})),e=e.filter(function(t){var e=t.audioCodec,r=t.videoCodec;return(!e||Object(u.a)(e))&&(!r||Object(u.a)(r))}),t.audioTracks&&(h=t.audioTracks.filter(function(t){return!t.audioCodec||Object(u.a)(t.audioCodec,"audio")})),e.length>0){r=e[0].bitrate,e.sort(function(t,e){return t.bitrate-e.bitrate}),this._levels=e;for(var p=0;p<e.length;p++)if(e[p].bitrate===r){this._firstLevel=p,l.b.log("manifest loaded,"+e.length+" level(s) found, first bitrate:"+r);break}this.hls.trigger(o.a.MANIFEST_PARSED,{levels:e,audioTracks:h,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:n,altAudio:h.length>0&&n})}else this.hls.trigger(o.a.ERROR,{type:d.b.MEDIA_ERROR,details:d.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.clearTimer(),this.currentLevelIndex!==t){l.b.log("switching to level "+t),this.currentLevelIndex=t;var i=e[t];i.level=t,r.trigger(o.a.LEVEL_SWITCHING,i)}var a=e[t],n=a.details;if(!n||n.live){var s=a.urlId;r.trigger(o.a.LEVEL_LOADING,{url:a.url[s],level:t,id:s})}}else r.trigger(o.a.ERROR,{type:d.b.OTHER_ERROR,details:d.a.LEVEL_SWITCH_ERROR,level:t,fatal:!1,reason:"invalid level idx"})},e.prototype.onError=function(t){if(t.fatal)return void(t.type===d.b.NETWORK_ERROR&&this.clearTimer());var e=!1,r=!1,i=void 0;switch(t.details){case d.a.FRAG_LOAD_ERROR:case d.a.FRAG_LOAD_TIMEOUT:case d.a.KEY_LOAD_ERROR:case d.a.KEY_LOAD_TIMEOUT:i=t.frag.level,r=!0;break;case d.a.LEVEL_LOAD_ERROR:case d.a.LEVEL_LOAD_TIMEOUT:i=t.context.level,e=!0;break;case d.a.REMUX_ALLOC_ERROR:i=t.level,e=!0}void 0!==i&&this.recoverLevel(t,i,e,r)},e.prototype.recoverLevel=function(t,e,r,i){var a=this,n=this.hls.config,o=t.details,s=this._levels[e],d=void 0,u=void 0,f=void 0;if(s.loadError++,s.fragmentError=i,r){if(!(this.levelRetryCount+1<=n.levelLoadingMaxRetry))return l.b.error("level controller, cannot recover from "+o+" error"),this.currentLevelIndex=null,this.clearTimer(),void(t.fatal=!0);u=Math.min(Math.pow(2,this.levelRetryCount)*n.levelLoadingRetryDelay,n.levelLoadingMaxRetryTimeout),this.timer=setTimeout(function(){return a.loadLevel()},u),t.levelRetry=!0,this.levelRetryCount++,l.b.warn("level controller, "+o+", retry in "+u+" ms, current retry count is "+this.levelRetryCount)}(r||i)&&(d=s.url.length,d>1&&s.loadError<d?(s.urlId=(s.urlId+1)%d,s.details=void 0,l.b.warn("level controller, "+o+" for level "+e+": switching to redundant URL-id "+s.urlId)):-1===this.manualLevelIndex?(f=0===e?this._levels.length-1:e-1,l.b.warn("level controller, "+o+": switch to "+f),this.hls.nextAutoLevel=this.currentLevelIndex=f):i&&(l.b.warn("level controller, "+o+": reload a fragment"),this.currentLevelIndex=null))},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.currentLevelIndex){var i=this._levels[r];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=n,s=i.details;s&&a.endSN===s.endSN&&(o/=2,l.b.log("same live playlist, reload twice faster")),o-=v.now()-t.stats.trequest,o=Math.max(n/2,Math.round(o)),l.b.log("live playlist, reload in "+Math.round(o)+" ms"),this.timer=setTimeout(function(){return e.loadLevel()},o)}else this.clearTimer()}},e.prototype.onAudioTrackSwitched=function(t){var e=this.hls.audioTracks[t.id].groupId,r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){var i=r.audioGroupIds.findIndex(function(t){return t===e});i!==r.urlId&&(r.urlId=i,this.startLoad())}},e.prototype.loadLevel=function(){if(l.b.debug("call to loadLevel"),null!==this.currentLevelIndex&&this.canload){var t=this._levels[this.currentLevelIndex];if("object"===(void 0===t?"undefined":c(t))&&t.url.length>0){var e=this.currentLevelIndex,r=t.urlId,i=t.url[r];l.b.log("Attempt loading level index "+e+" with URL-id "+r),this.hls.trigger(o.a.LEVEL_LOADING,{url:i,level:e,id:r})}}},h(e,[{key:"levels",get:function(){return this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e=this._levels;e&&(t=Math.min(t,e.length-1),this.currentLevelIndex===t&&e[t].details||this.setLevelInternal(t))}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=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.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}]),e}(s.a);e.a=g},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)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)}var o=r(1),s=r(3),l=r(9),d=r(50),u=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MEDIA_ATTACHED,o.a.MEDIA_DETACHING,o.a.FRAG_PARSING_METADATA));return n.id3Track=void 0,n.media=void 0,n}return n(e,t),e.prototype.destroy=function(){s.a.prototype.destroy.call(this)},e.prototype.onMediaAttached=function(t){this.media=t.media,this.media},e.prototype.onMediaDetaching=function(){Object(d.a)(this.id3Track),this.id3Track=void 0,this.media=void 0},e.prototype.getID3Track=function(t){for(var e=0;e<t.length;e++){var r=t[e];if("metadata"===r.kind&&"id3"===r.label)return Object(d.b)(r,this.media),r}return this.media.addTextTrack("metadata","id3")},e.prototype.onFragParsingMetadata=function(t){var e=t.frag,r=t.samples;this.id3Track||(this.id3Track=this.getID3Track(this.media.textTracks),this.id3Track.mode="hidden");for(var i=window.WebKitDataCue||window.VTTCue||window.TextTrackCue,a=0;a<r.length;a++){var n=l.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 d=0;d<n.length;d++){var u=n[d];if(!l.a.isTimeStampFrame(u)){var f=new i(o,s,"");f.value=u,this.id3Track.addCue(f)}}}}},e}(s.a);e.a=u},function(t,e,r){"use strict";function i(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)}function a(t){if(t&&t.cues)for(;t.cues.length>0;)t.removeCue(t.cues[0])}e.b=i,e.a=a},function(t,e,r){"use strict";function i(){var t=Object(a.a)(),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}e.a=i;var a=r(10)},function(t,e,r){"use strict";r.d(e,"a",function(){return g});var i=r(53),a=r(56),n=r(57),o=r(58),s=r(59),l=r(4),d=(r.n(l),r(4)),u=(r.n(d),r(4)),f=(r.n(u),r(4)),c=(r.n(f),r(4)),h=(r.n(c),r(4)),p=(r.n(h),r(4)),v=(r.n(p),r(60)),g={autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,initialLiveManifestSize:1,maxBufferLength:30,maxBufferSize:6e7,maxBufferHole:.5,lowBufferWatchdogPeriod:.5,highBufferWatchdogPeriod:3,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,liveDurationInfinity:!1,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,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:s.a,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,abrController:i.a,bufferController:a.a,capLevelController:n.a,fpsController:o.a,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,emeEnabled:!1,widevineLicenseUrl:void 0,requestMediaKeySystemAccessFunc:v.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)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)}var o=r(1),s=r(3),l=r(17),d=r(2),u=r(0),f=r(54),c=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}}(),h=window,p=h.performance,v=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.FRAG_LOADING,o.a.FRAG_LOADED,o.a.FRAG_BUFFERED,o.a.ERROR));return n.lastLoadedFragLevel=0,n._nextAutoLevel=-1,n.hls=r,n.timer=null,n._bwEstimator=null,n.onCheck=n._abandonRulesCheck.bind(n),n}return n(e,t),e.prototype.destroy=function(){this.clearTimer(),s.a.prototype.destroy.call(this)},e.prototype.onFragLoading=function(t){var e=t.frag;if("main"===e.type&&(this.timer||(this.fragCurrent=e,this.timer=setInterval(this.onCheck,100)),!this._bwEstimator)){var r=this.hls,i=r.config,a=e.level,n=r.levels[a].details.live,o=void 0,s=void 0;n?(o=i.abrEwmaFastLive,s=i.abrEwmaSlowLive):(o=i.abrEwmaFastVoD,s=i.abrEwmaSlowVoD),this._bwEstimator=new f.a(r,s,o,i.abrEwmaDefaultEstimate)}},e.prototype._abandonRulesCheck=function(){var t=this.hls,e=t.media,r=this.fragCurrent;if(r){var i=r.loader,a=t.minAutoLevel;if(!i||i.stats&&i.stats.aborted)return u.b.warn("frag loader destroy or aborted, disarm abandonRules"),this.clearTimer(),void(this._nextAutoLevel=-1);var n=i.stats;if(e&&n&&(!e.paused&&0!==e.playbackRate||!e.readyState)&&r.autoLevel&&r.level){var s=p.now()-n.trequest,d=Math.abs(e.playbackRate);if(s>500*r.duration/d){var f=t.levels,c=Math.max(1,n.bw?n.bw/8:1e3*n.loaded/s),h=f[r.level],v=h.realBitrate?Math.max(h.realBitrate,h.bitrate):h.bitrate,g=n.total?n.total:Math.max(n.loaded,Math.round(r.duration*v/8)),m=e.currentTime,y=(g-n.loaded)/c,b=(l.a.bufferInfo(e,m,t.config.maxBufferHole).end-m)/d;if(b<2*r.duration/d&&y>b){var E=void 0,T=void 0;for(T=r.level-1;T>a;T--){var S=f[T].realBitrate?Math.max(f[T].realBitrate,f[T].bitrate):f[T].bitrate;if((E=r.duration*S/(6.4*c))<b)break}E<y&&(u.b.warn("loading too slow, abort fragment loading and switch to level "+T+":fragLoadedDelay["+T+"]<fragLoadedDelay["+(r.level-1)+"];bufferStarvationDelay:"+E.toFixed(1)+"<"+y.toFixed(1)+":"+b.toFixed(1)),t.nextLoadLevel=T,this._bwEstimator.sample(s,n.loaded),i.abort(),this.clearTimer(),t.trigger(o.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||"main"!==r.type||isNaN(r.sn)||r.bitrateTest&&e.tload!==e.tbuffered)){var i=e.tparsed-e.trequest;u.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 d.a.FRAG_LOAD_ERROR:case d.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 d=a;d>=i;d--){var f=l[d],c=f.details,h=c?c.totalduration/c.fragments.length:e,p=!!c&&c.live,v=void 0;v=d<=t?o*r:s*r;var g=l[d].realBitrate?Math.max(l[d].realBitrate,l[d].bitrate):l[d].bitrate,m=g*h/v;if(u.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+d+"/"+Math.round(v)+"/"+g+"/"+h+"/"+n+"/"+m),v>g&&(!m||p&&!this.bitrateTestDelay||m<n))return d}return-1},c(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,d=n?n.currentTime:0,f=n&&0!==n.playbackRate?Math.abs(n.playbackRate):1,c=this._bwEstimator?this._bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,h=(l.a.bufferInfo(n,d,i.maxBufferHole).end-d)/f,p=this._findBestLevel(o,s,c,a,e,h,i.abrBandWidthFactor,i.abrBandWidthUpFactor,r);if(p>=0)return p;u.b.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var v=s?Math.min(s,i.maxStarvationDelay):i.maxStarvationDelay,g=i.abrBandWidthFactor,m=i.abrBandWidthUpFactor;if(0===h){var y=this.bitrateTestDelay;if(y){v=(s?Math.min(s,i.maxLoadingDelay):i.maxLoadingDelay)-y,u.b.trace("bitrate test took "+Math.round(1e3*y)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*v)+" ms"),g=m=1}}return p=this._findBestLevel(o,s,c,a,e,h+v,g,m,r),Math.max(p,0)}}]),e}(s.a);e.a=v},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(55),n=function(){function t(e,r,n,o){i(this,t),this.hls=e,this.defaultEstimate_=o,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new a.a(r),this.fast_=new a.a(n)}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}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=function(){function t(e){i(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.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)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)}var o=r(1),s=r(3),l=r(0),d=r(2),u=r(10),f=Object(u.a)(),c=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MEDIA_ATTACHING,o.a.MEDIA_DETACHING,o.a.MANIFEST_PARSED,o.a.BUFFER_RESET,o.a.BUFFER_APPENDING,o.a.BUFFER_CODECS,o.a.BUFFER_EOS,o.a.BUFFER_FLUSHING,o.a.LEVEL_PTS_UPDATED,o.a.LEVEL_UPDATED));return n._msDuration=null,n._levelDuration=null,n._live=null,n._objectUrl=null,n.onsbue=n.onSBUpdateEnd.bind(n),n.onsbe=n.onSBUpdateError.bind(n),n.pendingTracks={},n.tracks={},n}return n(e,t),e.prototype.destroy=function(){s.a.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,l.b.warn("can not abort audio buffer: "+t)}a?this.audioTimestampOffset=t.start:(l.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.altAudio,i=0;t.altAudio&&(e||r)&&(i=(e?1:0)+(r?1:0),l.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 f;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=window.URL.createObjectURL(r),this._objectUrl=e.src}},e.prototype.onMediaDetaching=function(){l.b.log("media source detaching");var t=this.mediaSource;if(t){if("open"===t.readyState)try{t.endOfStream()}catch(t){l.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&&(window.URL.revokeObjectURL(this._objectUrl),this.media.src===this._objectUrl?(this.media.removeAttribute("src"),this.media.load()):l.b.warn("media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(o.a.MEDIA_DETACHED)},e.prototype.onMediaSourceOpen=function(){l.b.log("media source opened"),this.hls.trigger(o.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(){l.b.log("media source closed")},e.prototype.onMediaSourceEnded=function(){l.b.log("media source ended")},e.prototype.onSBUpdateEnd=function(){if(this.audioTimestampOffset){var t=this.sourceBuffer.audio;l.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),i={},a=this.sourceBuffer;for(var n in a)i[n]=a[n].buffered;this.hls.trigger(o.a.BUFFER_APPENDED,{parent:e,pending:r,timeRanges:i}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()},e.prototype.onSBUpdateError=function(t){l.b.error("sourceBuffer error:",t),this.hls.trigger(o.a.ERROR,{type:d.b.MEDIA_ERROR,details:d.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,s=a.container+";codecs="+n;l.b.log("creating sourceBuffer("+s+")");try{var u=e[i]=r.addSourceBuffer(s);u.addEventListener("updateend",this.onsbue),u.addEventListener("error",this.onsbe),this.tracks[i]={codec:n,container:a.container},a.buffer=u}catch(t){l.b.error("error while trying to add sourceBuffer:"+t.message),this.hls.trigger(o.a.ERROR,{type:d.b.MEDIA_ERROR,details:d.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:t,mimeType:s})}}this.hls.trigger(o.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){l.b.error("sourceBuffer error:",t.event),this.hls.trigger(o.a.ERROR,{type:d.b.MEDIA_ERROR,details:d.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,l.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)}l.b.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{e.endOfStream()}catch(t){l.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;e.fragments.length>0&&(this._levelDuration=e.totalduration+e.fragments[0].start,this._live=e.live,this.updateMediaElementDuration())},e.prototype.updateMediaElementDuration=function(){var t=this.hls.config,e=void 0;if(null!==this._levelDuration&&this.media&&this.mediaSource&&this.sourceBuffer&&0!==this.media.readyState&&"open"===this.mediaSource.readyState){for(var r in this.sourceBuffer)if(!0===this.sourceBuffer[r].updating)return;e=this.media.duration,null===this._msDuration&&(this._msDuration=this.mediaSource.duration),!0===this._live&&!0===t.liveDurationInfinity?(l.b.log("Media Source duration is set to Infinity"),this._msDuration=this.mediaSource.duration=1/0):(this._levelDuration>this._msDuration&&this._levelDuration>e||e===1/0||isNaN(e))&&(l.b.log("Updating Media Source duration to "+this._levelDuration.toFixed(3)),this._msDuration=this.mediaSource.duration=this._levelDuration)}},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){l.b.error("error while accessing sourceBuffer.buffered")}this.appended=e,this.hls.trigger(o.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 l.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){l.b.error("error while trying to append buffer:"+e.message),r.unshift(i);var s={type:d.b.MEDIA_ERROR,parent:i.parent};22!==e.code?(this.appendError?this.appendError++:this.appendError=1,s.details=d.a.BUFFER_APPEND_ERROR,this.appendError>t.config.appendErrorMaxRetry?(l.b.log("fail "+t.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],s.fatal=!0,t.trigger(o.a.ERROR,s)):(s.fatal=!1,t.trigger(o.a.ERROR,s))):(this.segments=[],s.details=d.a.BUFFER_FULL_ERROR,s.fatal=!1,t.trigger(o.a.ERROR,s))}}}},e.prototype.flushBuffer=function(t,e,r){var i=void 0,a=void 0,n=void 0,o=void 0,s=void 0,d=void 0,u=this.sourceBuffer;if(Object.keys(u).length){if(l.b.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+t+"/"+e),this.flushBufferCounter<this.appended){for(var f in u)if(!r||f===r){if(i=u[f],i.ended=!1,i.updating)return l.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,d=e):(s=Math.max(n,t),d=Math.min(o,e)),Math.min(d,o)-s>.5)return this.flushBufferCounter++,l.b.log("flush "+f+" ["+s+","+d+"], of ["+n+","+o+"], pos:"+this.media.currentTime),i.remove(s,d),!1}catch(t){l.b.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else l.b.warn("abort flushing too many retries");l.b.log("buffer flushed")}return!0},e}(s.a);e.a=c},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)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)}var o=r(1),s=r(3),l=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}}(),d=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.FPS_DROP_LEVEL_CAPPING,o.a.MEDIA_ATTACHING,o.a.MANIFEST_PARSED,o.a.BUFFER_CODECS));return n.autoLevelCapping=Number.POSITIVE_INFINITY,n.firstLevel=null,n.levels=[],n.media=null,n.restrictedLevels=[],n.timer=null,n}return n(e,t),e.prototype.destroy=function(){this.hls.config.capLevelToPlayerSize&&(this.media=null,this._stopCapping())},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 window.HTMLVideoElement?t.media:null},e.prototype.onManifestParsed=function(t){var e=this.hls;this.restrictedLevels=[],this.levels=t.levels,this.firstLevel=t.firstLevel,e.config.capLevelToPlayerSize&&(t.video||t.levels.length&&t.altAudio)&&this._startCapping()},e.prototype.onBufferCodecs=function(t){this.hls.config.capLevelToPlayerSize&&t.video&&this._startCapping()},e.prototype.onLevelsUpdated=function(t){this.levels=t.levels},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.prototype._startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),clearInterval(this.timer),this.timer=setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},e.prototype._stopCapping=function(){this.restrictedLevels=[],this.firstLevel=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer),this.timer=null)},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},l(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}(s.a);e.a=d},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)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)}var o=r(1),s=r(3),l=r(0),d=window,u=d.performance,f=function(t){function e(r){return i(this,e),a(this,t.call(this,r,o.a.MEDIA_ATTACHING))}return n(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 window.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=u.now();if(e){if(this.lastTime){var a=i-this.lastTime,n=r-this.lastDroppedFrames,s=e-this.lastDecodedFrames,d=1e3*n/a,f=this.hls;if(f.trigger(o.a.FPS_DROP,{currentDropped:n,currentDecoded:s,totalDroppedFrames:r}),d>0&&n>f.config.fpsDroppedMonitoringThreshold*s){var c=f.currentLevel;l.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(-1===f.autoLevelCapping||f.autoLevelCapping>=c)&&(c-=1,f.trigger(o.a.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:f.currentLevel}),f.autoLevelCapping=c,f.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}(s.a);e.a=f},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(0),n=window,o=n.performance,s=n.XMLHttpRequest,l=function(){function t(e){i(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:o.now(),retry:0},this.retryDelay=e.retryDelay,this.loadInternal()},t.prototype.loadInternal=function(){var t=void 0,e=this.context;t=this.loader=new s;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,n=this.context,s=this.config;if(!i.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(o.now(),i.trequest)),4===r){var l=e.status;if(l>=200&&l<300){i.tload=Math.max(i.tfirst,o.now());var d=void 0,u=void 0;"arraybuffer"===n.responseType?(d=e.response,u=d.byteLength):(d=e.responseText,u=d.length),i.loaded=i.total=u;var f={url:e.responseURL,data:d};this.callbacks.onSuccess(f,i,n,e)}else i.retry>=s.maxRetry||l>=400&&l<499?(a.b.error(l+" while loading "+n.url),this.callbacks.onError({code:l,text:e.statusText},n,e)):(a.b.warn(l+" while loading "+n.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,s.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),s.timeout)},t.prototype.loadtimeout=function(){a.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}();e.a=l},function(t,e,r){"use strict";r.d(e,"a",function(){return i});var i=function(){return"undefined"!=typeof window&&window.navigator&&window.navigator.requestMediaKeySystemAccess?window.navigator.requestMediaKeySystemAccess.bind(window.navigator):null}()},function(t,e){/*! http://mths.be/endswith v0.2.0 by @mathias */ +String.prototype.endsWith||function(){"use strict";var t=function(){try{var t={},e=Object.defineProperty,r=e(t,t,t)&&e}catch(t){}return r}(),e={}.toString,r=function(t){if(null==this)throw TypeError();var r=String(this);if(t&&"[object RegExp]"==e.call(t))throw TypeError();var i=r.length,a=String(t),n=a.length,o=i;if(arguments.length>1){var s=arguments[1];void 0!==s&&(o=s?Number(s):0)!=o&&(o=0)}var l=Math.min(Math.max(o,0),i),d=l-n;if(d<0)return!1;for(var u=-1;++u<n;)if(r.charCodeAt(d+u)!=a.charCodeAt(u))return!1;return!0};t?t(String.prototype,"endsWith",{value:r,configurable:!0,writable:!0}):String.prototype.endsWith=r}()}]).default}); +//# sourceMappingURL=hls.light.min.js.map \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls.light.min.js.map b/grails-app/assets/bower/hls.js/dist/hls.light.min.js.map new file mode 100644 index 000000000..54f43eb32 --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls.light.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///hls.light.min.js","webpack:///webpack/bootstrap e41fd7e1af865b2c2322","webpack:///./src/utils/logger.js","webpack:///./src/events.js","webpack:///./src/errors.js","webpack:///./src/event-handler.js","webpack:///./src/empty.js","webpack:///./src/utils/get-self-scope.js","webpack:///./node_modules/url-toolkit/src/url-toolkit.js","webpack:///./src/utils/binary-search.js","webpack:///./node_modules/events/events.js","webpack:///./src/demux/id3.js","webpack:///./src/utils/mediasource-helper.js","webpack:///./src/loader/playlist-loader.js","webpack:///./src/demux/mp4demuxer.js","webpack:///./src/loader/fragment.js","webpack:///./src/loader/level-key.js","webpack:///./src/utils/codecs.js","webpack:///./src/controller/fragment-tracker.js","webpack:///./src/utils/buffer-helper.js","webpack:///./src/demux/demuxer-inline.js","webpack:///./src/crypt/decrypter.js","webpack:///./src/demux/adts.js","webpack:///./src/demux/mpegaudio.js","webpack:///./src/controller/level-helper.js","webpack:///./src/hls.js","webpack:///./src/loader/m3u8-parser.js","webpack:///./src/utils/attr-list.js","webpack:///./src/loader/fragment-loader.js","webpack:///./src/loader/key-loader.js","webpack:///./src/controller/stream-controller.js","webpack:///./src/demux/demuxer.js","webpack:///./node_modules/webworkify-webpack/index.js","webpack:///./src/crypt/aes-crypto.js","webpack:///./src/crypt/fast-aes-key.js","webpack:///./src/crypt/aes-decryptor.js","webpack:///./src/demux/aacdemuxer.js","webpack:///./src/demux/tsdemuxer.js","webpack:///./src/demux/exp-golomb.js","webpack:///./src/demux/sample-aes.js","webpack:///./src/demux/mp3demuxer.js","webpack:///./src/remux/mp4-remuxer.js","webpack:///./src/remux/aac-helper.js","webpack:///./src/remux/mp4-generator.js","webpack:///./src/remux/passthrough-remuxer.js","webpack:///./src/demux/demuxer-worker.js","webpack:///./src/utils/time-ranges.js","webpack:///./src/utils/discontinuities.js","webpack:///./src/task-loop.js","webpack:///./src/controller/fragment-finders.js","webpack:///./src/controller/level-controller.js","webpack:///./src/controller/id3-track-controller.js","webpack:///./src/utils/texttrack-utils.js","webpack:///./src/is-supported.js","webpack:///./src/config.js","webpack:///./src/controller/abr-controller.js","webpack:///./src/utils/ewma-bandwidth-estimator.js","webpack:///./src/utils/ewma.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/utils/mediakeys-helper.js","webpack:///./node_modules/string.prototype.endswith/endswith.js"],"names":["root","factory","exports","module","define","amd","this","modules","__webpack_require__","moduleId","installedModules","i","l","call","m","c","d","name","getter","o","Object","defineProperty","configurable","enumerable","get","n","__esModule","object","property","prototype","hasOwnProperty","p","s","__webpack_exports__","noop","formatMsg","type","msg","consolePrintFn","func","global","console","_len","arguments","length","args","Array","_key","apply","exportLoggerFunctions","debugConfig","_len2","functions","_key2","forEach","exportedLogger","bind","enableLogs","logger","__WEBPACK_IMPORTED_MODULE_0__get_self_scope__","_typeof","Symbol","iterator","obj","constructor","fakeLogger","trace","debug","log","warn","info","error","e","HlsEvents","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_SWITCHING","LEVEL_SWITCHED","LEVEL_LOADING","LEVEL_LOADED","LEVEL_UPDATED","LEVEL_PTS_UPDATED","AUDIO_TRACKS_UPDATED","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","ErrorDetails","NETWORK_ERROR","MEDIA_ERROR","KEY_SYSTEM_ERROR","MUX_ERROR","OTHER_ERROR","KEY_SYSTEM_NO_KEYS","KEY_SYSTEM_NO_ACCESS","KEY_SYSTEM_NO_SESSION","KEY_SYSTEM_LICENSE_REQUEST_FAILED","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_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","_classCallCheck","instance","Constructor","TypeError","__WEBPACK_IMPORTED_MODULE_0__utils_logger__","__WEBPACK_IMPORTED_MODULE_1__errors__","__WEBPACK_IMPORTED_MODULE_2__events__","FORBIDDEN_EVENT_NAMES","Set","EventHandler","hls","onEvent","events","handledEvents","useGenericHandler","registerListeners","destroy","onHandlerDestroying","unregisterListeners","onHandlerDestroyed","isEventHandler","event","has","Error","on","off","data","onEventGeneric","eventToFunction","funcName","replace","err","message","trigger","details","fatal","getSelfScope","window","self","URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","baseParts","path","normalizePath","buildURLFromParts","relativeParts","scheme","netLoc","pathParts","exec","builtParts","params","query","fragment","baseURLPath","newPath","substring","lastIndexOf","url","parts","split","reverse","join","BinarySearch","search","list","comparisonFunction","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","EventEmitter","_events","_maxListeners","undefined","isFunction","arg","isNumber","isObject","isUndefined","defaultMaxListeners","setMaxListeners","isNaN","emit","er","handler","len","listeners","context","slice","addListener","listener","newListener","push","warned","once","g","removeListener","fired","position","splice","removeAllListeners","key","listenerCount","evlistener","emitter","ID3","isHeader","offset","isFooter","getID3Data","front","_readSize","subarray","size","getTimeStamp","frames","getID3Frames","frame","isTimeStampFrame","_readTimeStamp","_getFrameData","String","fromCharCode","id3Data","end","frameData","_decodeFrame","_decodePrivFrame","_decodeTextFrame","_decodeURLFrame","timeStampFrame","byteLength","Uint8Array","pts33Bit","timestamp","Math","round","owner","_utf8ArrayToStr","privateData","buffer","index","description","value","text","array","exitOnNull","char2","char3","out","getMediaSource","MediaSource","WebKitMediaSource","_possibleConstructorReturn","ReferenceError","_inherits","subClass","superClass","create","writable","setPrototypeOf","__proto__","__WEBPACK_IMPORTED_MODULE_0__events__","__WEBPACK_IMPORTED_MODULE_1__event_handler__","__WEBPACK_IMPORTED_MODULE_2__errors__","__WEBPACK_IMPORTED_MODULE_3__utils_logger__","__WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__","__WEBPACK_IMPORTED_MODULE_5__m3u8_parser__","_createClass","defineProperties","target","props","descriptor","protoProps","staticProps","_window","performance","ContextType","MANIFEST","LEVEL","AUDIO_TRACK","SUBTITLE_TRACK","LevelType","MAIN","AUDIO","SUBTITLE","PlaylistLoader","_EventHandler","_this","loaders","canHaveQualityLevels","mapContextToLevelType","getResponseUrl","response","indexOf","createInternalLoader","config","PLoader","pLoader","Loader","loader","InternalLoader","getInternalLoader","resetInternalLoader","contextType","destroyInternalLoaders","onManifestLoading","load","level","id","onLevelLoading","onAudioTrackLoading","onSubtitleTrackLoading","loaderContext","abort","maxRetry","timeout","retryDelay","maxRetryDelay","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","responseType","loaderConfig","loaderCallbacks","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","stats","networkDetails","isSidxRequest","_handleSidxRequest","_handlePlaylistLoaded","string","tload","now","_handleManifestParsingError","_handleTrackOrLevelPlaylist","_handleMasterPlaylist","_handleNetworkError","levels","parseMasterPlaylist","audioGroups","map","attrs","codec","audioCodec","audioTracks","parseMasterPlaylistMedia","subtitles","embeddedAudioFound","audioTrack","unshift","levelUrlId","levelId","levelType","levelDetails","parseLevelPlaylist","singleLevel","tparsed","needSidxRanges","sidxUrl","initSegment","rangeStart","rangeEnd","sidxInfo","parseSegmentIndex","references","segmentRef","segRefInfo","frag","fragments","byteRange","rawByteRange","start","moovEndOffset","reason","targetduration","__WEBPACK_IMPORTED_MODULE_1__events__","UINT32_MAX","pow","MP4Demuxer","observer","remuxer","resetTimeStamp","initPTS","resetInitSegment","videoCodec","duration","initData","parseInitSegment","tracks","audio","video","audiovideo","container","probe","findBox","min","bin2str","readUint16","val","readUint32","writeUint32","results","subresults","endbox","concat","moov","sidx","version","timescale","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","earliestPresentationTime","result","trak","tkhd","trackId","mdhd","hdlr","hdlrType","soun","vide","codecBox","codecType","getStartDTS","trafs","baseTimes","traf","tfhd","scale","tfdt","isFinite","offsetStartDTS","timeOffset","baseMediaDecodeTime","max","upper","floor","lower","append","contiguous","accurateTimeOffset","startDTS","remux","__WEBPACK_IMPORTED_MODULE_0_url_toolkit__","__WEBPACK_IMPORTED_MODULE_0_url_toolkit___default","__WEBPACK_IMPORTED_MODULE_1__level_key__","Fragment","_elementaryStreams","_url","_byteRange","_decryptdata","tagList","ElementaryStreamTypes","VIDEO","addElementaryStream","hasElementaryStream","createInitializationVector","segmentNumber","uint8View","fragmentDecryptdataFromLevelkey","levelkey","decryptdata","method","uri","iv","baseuri","reluri","relurl","a","baseurl","set","_programDateTime","rawProgramDateTime","Date","parse","lastByteRangeEndOffset","parseInt","sn","LevelKey","_uri","isCodecType","typeCodes","sampleEntryCodesISO","isCodecSupportedInMp4","isTypeSupported","a3ds","ac-3","ac-4","alac","alaw","dra1","dts+","dts-","dtsc","dtse","dtsh","ec-3","enca","g719","g726","m4ae","mha1","mha2","mhm1","mhm2","mlpa","mp4a","raw ","Opus","samr","sawb","sawp","sevc","sqcp","ssmv","twos","ulaw","avc1","avc2","avc3","avc4","avcp","drac","dvav","dvhe","encv","hev1","hvc1","mjp2","mp4v","mvc1","mvc2","mvc3","mvc4","resv","rv60","s263","svc1","svc2","vc-1","vp08","vp09","FragmentState","FragmentTracker","__WEBPACK_IMPORTED_MODULE_0__event_handler__","NOT_LOADED","APPENDING","PARTIAL","OK","bufferPadding","timeRanges","getBufferedFrag","bufferedFrags","keys","filter","fragmentEntity","body","buffered","startPTS","endPTS","bufferedFragKey","pop","detectEvictedFragments","elementaryStream","timeRange","_this2","fragmentTimes","time","esData","range","isTimeBuffered","removeFragment","detectPartialFragments","_this3","fragKey","getFragmentKey","getBufferedTimes","startTime","endTime","fragmentPartial","partial","urlId","getPartialFragment","_this4","timePadding","bestFragment","bestOverlap","isPartial","getState","state","onFragLoaded","bitrateTest","onBufferAppended","_this5","onFragBuffered","hasFragment","removeAllFragments","BufferHelper","isBuffered","media","bufferInfo","pos","maxHoleDuration","vbuffered","bufferedInfo","nextStart","buffered2","bufferLen","bufferStart","bufferEnd","bufferStartNext","sort","b","diff","buf2len","buf2end","__WEBPACK_IMPORTED_MODULE_2__crypt_decrypter__","__WEBPACK_IMPORTED_MODULE_3__demux_aacdemuxer__","__WEBPACK_IMPORTED_MODULE_5__demux_tsdemuxer__","__WEBPACK_IMPORTED_MODULE_6__demux_mp3demuxer__","__WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__","__WEBPACK_IMPORTED_MODULE_8__remux_passthrough_remuxer__","__WEBPACK_IMPORTED_MODULE_9__utils_get_self_scope__","DemuxerInline","typeSupported","vendor","demuxer","discontinuity","trackSwitch","defaultInitPTS","decrypter","localthis","decrypt","decryptedData","tstart","tdecrypt","pushDecrypted","muxConfig","demux","mux","setDecryptData","__WEBPACK_IMPORTED_MODULE_0__aes_crypto__","__WEBPACK_IMPORTED_MODULE_1__fast_aes_key__","__WEBPACK_IMPORTED_MODULE_2__aes_decryptor__","__WEBPACK_IMPORTED_MODULE_3__errors__","__WEBPACK_IMPORTED_MODULE_4__utils_logger__","__WEBPACK_IMPORTED_MODULE_5__events__","__WEBPACK_IMPORTED_MODULE_6__utils_get_self_scope__","Decrypter","_ref","_ref$removePKCS7Paddi","removePKCS7Padding","logEnabled","browserCrypto","crypto","subtle","webkitSubtle","disableWebCrypto","isSync","enableSoftwareAES","callback","decryptor","expandKey","fastAesKey","then","aesKey","catch","onWebCryptoError","getAudioConfig","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","navigator","toLowerCase","manifestCodec","adtsSampleingRates","test","samplerate","channelCount","isHeaderPattern","getHeaderLength","getFullFrameLength","headerLength","frameLength","newOffset","initTrackConfig","track","getFrameDuration","parseFrameHeader","pts","frameIndex","frameDuration","stamp","appendFrame","header","aacSample","unit","dts","samples","sample","MpegAudio","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","addGroupId","audioGroupIds","textGroupIds","updatePTS","fromIdx","toIdx","fragFrom","fragTo","fragToPTS","updateFragPTSDTS","endDTS","maxStartPTS","deltaPTS","abs","drift","startSN","endSN","fragIdx","PTSKnown","mergeDetails","oldDetails","newDetails","delta","oldfragments","newfragments","ccOffset","PTSFrag","oldFrag","newFrag","cc","backtracked","dropped","sliding","__WEBPACK_IMPORTED_MODULE_2__loader_playlist_loader__","__WEBPACK_IMPORTED_MODULE_3__loader_fragment_loader__","__WEBPACK_IMPORTED_MODULE_4__loader_key_loader__","__WEBPACK_IMPORTED_MODULE_5__controller_fragment_tracker__","__WEBPACK_IMPORTED_MODULE_6__controller_stream_controller__","__WEBPACK_IMPORTED_MODULE_7__controller_level_controller__","__WEBPACK_IMPORTED_MODULE_8__controller_id3_track_controller__","__WEBPACK_IMPORTED_MODULE_9__is_supported__","__WEBPACK_IMPORTED_MODULE_10__utils_logger__","__WEBPACK_IMPORTED_MODULE_11__config__","__WEBPACK_IMPORTED_MODULE_12__events__","__WEBPACK_IMPORTED_MODULE_13_events__","__WEBPACK_IMPORTED_MODULE_13_events___default","Hls","defaultConfig","DefaultConfig","liveSyncDurationCount","liveMaxLatencyDurationCount","liveSyncDuration","liveMaxLatencyDuration","prop","_autoLevelCapping","abrController","bufferController","capLevelController","fpsController","playListLoader","fragmentLoader","keyLoader","id3TrackController","levelController","fragmentTracker","streamController","networkControllers","Controller","audioStreamController","coreComponents","audioTrackController","subtitleTrackController","emeController","subtitleStreamController","timelineController","isSupported","detachMedia","component","attachMedia","loadSource","location","href","startLoad","startPosition","controller","stopLoad","swapAudioCodec","recoverMediaError","currentLevel","newLevel","loadLevel","immediateLevelSwitch","nextLevel","manualLevel","nextLevelSwitch","nextLoadLevel","firstLevel","minAutoLevel","startLevel","minAutoBitrate","realBitrate","bitrate","autoLevelCapping","nextAutoLevel","maxAutoLevel","audioTrackId","liveSyncPosition","subtitleTracks","subtitleTrack","subtitleTrackId","subtitleDisplay","__WEBPACK_IMPORTED_MODULE_1__fragment__","__WEBPACK_IMPORTED_MODULE_2__level_key__","__WEBPACK_IMPORTED_MODULE_3__utils_attr_list__","__WEBPACK_IMPORTED_MODULE_5__utils_codecs__","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","LEVEL_PLAYLIST_REGEX_FAST","RegExp","source","LEVEL_PLAYLIST_REGEX_SLOW","MP4_REGEX_SUFFIX","M3U8Parser","findGroup","groups","mediaGroupId","matchingGroup","group","convertAVC1ToAVCOTI","avcdata","shift","toString","substr","resolve","baseUrl","lastIndex","resolution","decimalResolution","width","height","decimalInteger","NAME","codecs","filtered","preferred","unknownCodecs","CODECS","medias","TYPE","groupId","default","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","URI","lang","LANGUAGE","groupCodec","currentSN","totalduration","live","prevFrag","parseFloat","title","programDateTime","pdt","endPdt","byteRangeEndOffset","match","value1","value2","toUpperCase","decryptparams","keyAttrs","decryptmethod","enumeratedString","decrypturi","decryptiv","hexadecimalInteger","startParams","startAttrs","startTimeOffset","decimalFloatingPoint","mapAttrs","BYTERANGE","averagetargetduration","startCC","endCC","every","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","parseAttrList","attr","attrName","intValue","Number","MAX_SAFE_INTEGER","Infinity","stringValue","hexadecimalIntegerAsNumber","res","input","FragmentLoader","loaderName","onFragLoading","FragmentILoader","fLoader","DefaultILoader","loaded","progressData","byteRangeStartOffset","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","payload","KeyLoader","decryptkey","decrypturl","onKeyLoading","fragLoadingMaxRetry","fragLoadingRetryDelay","__WEBPACK_IMPORTED_MODULE_0__utils_binary_search__","__WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__","__WEBPACK_IMPORTED_MODULE_2__demux_demuxer__","__WEBPACK_IMPORTED_MODULE_3__events__","__WEBPACK_IMPORTED_MODULE_4__fragment_tracker__","__WEBPACK_IMPORTED_MODULE_5__loader_fragment__","__WEBPACK_IMPORTED_MODULE_6__loader_playlist_loader__","__WEBPACK_IMPORTED_MODULE_7__level_helper__","__WEBPACK_IMPORTED_MODULE_8__utils_time_ranges__","__WEBPACK_IMPORTED_MODULE_9__errors__","__WEBPACK_IMPORTED_MODULE_11__utils_discontinuities__","__WEBPACK_IMPORTED_MODULE_12__task_loop__","__WEBPACK_IMPORTED_MODULE_13__fragment_finders__","State","STOPPED","IDLE","FRAG_LOADING_WAITING_RETRY","WAITING_LEVEL","PARSING","PARSED","ENDED","StreamController","_TaskLoop","audioCodecSwap","_state","stallReported","lastCurrentTime","setInterval","fragLoadError","startFragRequested","loadedmetadata","toFixed","nextLoadPosition","tick","forceStartLoad","fragCurrent","fragPrevious","clearInterval","doTick","_doTickIdle","retryDate","seeking","_checkBuffer","_checkFragmentChanged","levelLastLoaded","startFragPrefetch","currentTime","levelInfo","levelBitrate","maxBufLen","maxBufferSize","maxBufferLength","maxMaxBufferLength","mediaBuffer","maxBufferHole","altAudio","_fetchPayloadOrEos","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","encrypted","_loadKey","_loadFragment","maxLatency","maxFragLookUpTolerance","computeLivePosition","readyState","targetSN","fragNext","foundFrag","curSNIdx","sameLevel","nextFrag","fragState","autoLevel","autoLevelEnabled","_reduceMaxBufferLength","followingBufferedFrag","fragPlayingCurrent","fragPlaying","fragPlayingLevel","immediateSwitch","previouslyPaused","paused","pause","flushMainBuffer","POSITIVE_INFINITY","immediateLevelSwitchEnd","play","fetchdelay","nextBufferedFrag","nextLevelId","fragLastKbps","startOffset","endOffset","flushScope","onMediaAttached","onvseeking","onMediaSeeking","onvseeked","onMediaSeeked","onvended","onMediaEnded","addEventListener","autoStartLoad","onMediaDetaching","ended","removeEventListener","tolerance","fragStartOffset","fragEndOffset","stalled","onManifestParsed","aac","heaac","audioCodecSwitch","onLevelLoaded","newLevelId","lastLevel","curLevel","curDetails","onKeyLoaded","fragLoaded","tbuffered","defaultAudioCodec","lastAudioCodec","pendingBuffering","appended","mediaSeeking","initSegmentData","onFragParsingInitSegment","fragNew","trackName","ua","metadata","levelCodec","parent","content","onFragParsingData","hasAudio","hasVideo","nb","data1","data2","onFragParsed","_checkAppendedParsed","onAudioTrackSwitching","onAudioTrackSwitched","videoBuffer","onBufferCreated","mediaTrack","alternate","pending","total","tfirst","mediaBuffered","delay","levelRetry","minLength","_seekToStartPos","expectedPlaying","tnow","nudgeRetry","stalledDuration","_reportStall","_tryFixBufferStall","onFragLoadEmergencyAborted","onBufferFlushed","targetLatency","_trySkipBufferHole","highBufferWatchdogPeriod","_tryNudgeBuffer","lastEndTime","nudgeMaxRetry","targetTime","nudgeOffset","nextState","previousState","_liveSyncPosition","__WEBPACK_IMPORTED_MODULE_0_events__","__WEBPACK_IMPORTED_MODULE_0_events___default","__WEBPACK_IMPORTED_MODULE_1_webworkify_webpack__","__WEBPACK_IMPORTED_MODULE_1_webworkify_webpack___default","__WEBPACK_IMPORTED_MODULE_3__demux_demuxer_inline__","__WEBPACK_IMPORTED_MODULE_5__errors__","__WEBPACK_IMPORTED_MODULE_6__utils_mediasource_helper__","__WEBPACK_IMPORTED_MODULE_7__utils_get_self_scope__","Demuxer","forwardMessage","ev","mp4","mpeg","mp3","enableWorker","Worker","w","onwmsg","onWorkerMessage","onerror","filename","lineno","postMessage","cmd","JSON","stringify","URL","revokeObjectURL","objectURL","terminate","lastFrag","nextSN","ArrayBuffer","webpackBootstrapFunc","oe","f","ENTRY_MODULE","quoteRegExp","str","getModuleDependencies","sources","queueName","retval","fnString","wrapperSignature","webpackRequireName","re","dependencyRegExp","moduleNameReqExp","hasValuesInQueues","queues","reduce","hasValues","getRequiredModules","modulesQueue","main","requiredModules","seenModules","queue","moduleToCheck","newModules","newModulesKeys","j","options","all","src","entryModule","blob","Blob","bare","webkitURL","mozURL","msURL","workerUrl","createObjectURL","worker","AESCrypto","aesIV","FastAESKey","importKey","removePadding","outputBytes","paddingBytes","DataView","getUint8","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","x","xi","sx","x2","x4","x8","t","keyBuffer","sameKey","keySize","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","__WEBPACK_IMPORTED_MODULE_0__adts__","__WEBPACK_IMPORTED_MODULE_1__utils_logger__","__WEBPACK_IMPORTED_MODULE_2__demux_id3__","AACDemuxer","_audioTrack","sequenceNumber","isAAC","inputTimeScale","id3Samples","__WEBPACK_IMPORTED_MODULE_1__mpegaudio__","__WEBPACK_IMPORTED_MODULE_3__exp_golomb__","__WEBPACK_IMPORTED_MODULE_4__sample_aes__","__WEBPACK_IMPORTED_MODULE_5__utils_logger__","__WEBPACK_IMPORTED_MODULE_6__errors__","RemuxerTrackIdConfig","id3","TSDemuxer","sampleAes","discardEPB","syncOffset","_syncOffset","scanwindow","createTrack","pid","pmtParsed","_pmtId","_avcTrack","_id3Track","_txtTrack","aacOverFlow","aacLastPTS","avcSample","_duration","stt","pes","unknownPIDs","avcTrack","id3Track","avcId","audioId","id3Id","pmtId","avcData","pesData","audioData","parsePAT","_parsePAT","parsePMT","_parsePMT","parsePES","_parsePES","parseAVCPES","_parseAVCPES","parseAACPES","_parseAACPES","parseMPEGPES","_parseMPEGPES","parseID3PES","_parseID3PES","parsedPIDs","avc","decryptAndRemux","videoTrack","textTrack","decryptAacSamples","decryptAndRemuxAvc","decryptAvcSamples","_initPTS","_initDTS","mpegSupported","isSampleAes","sectionLength","tableEnd","programInfoLength","stream","pesFlags","pesLen","pesHdrLen","pesPts","pesDts","payloadStartOffset","newData","dataLen","pushAccesUnit","units","nbSamples","forceKeyFrameOnDiscontinuity","sps","last","_parseAVCNALu","expGolombDecoder","spsfound","createAVCSample","audFound","sliceType","readSliceType","readUByte","payloadType","payloadSize","endOfCaptions","bytesAvailable","readUShort","readUInt","firstByte","secondByte","totalCCs","byteArray","_insertSampleInOrder","bytes","readSPS","pixelRatio","codecarray","codecstring","h","pps","arr","_getLastNalUnit","lastUnit","overflow","naluState","lastState","unitType","lastUnitStart","lastUnitType","tmp","EPBPositions","newLength","sourceIndex","newPTS","ExpGolomb","bitsAvailable","loadWord","workingBytes","availableBytes","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","skipScalingList","lastScale","nextScale","deltaScale","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","profileIdc","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","scalingListCount","chromaFormatIdc","picOrderCntType","ceil","__WEBPACK_IMPORTED_MODULE_0__crypt_decrypter__","SampleAesDecrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","sync","curUnit","encryptedBuffer","byteOffset","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","decryptAvcSample","unitIndex","curUnits","__WEBPACK_IMPORTED_MODULE_0__demux_id3__","__WEBPACK_IMPORTED_MODULE_2__mpegaudio__","MP3Demuxer","__WEBPACK_IMPORTED_MODULE_0__aac_helper__","__WEBPACK_IMPORTED_MODULE_1__mp4_generator__","MP4Remuxer","isSafari","ISGenerated","defaultTimeStamp","generateIS","nbAudioSamples","nbVideoSamples","audioTimeOffset","videoTimeOffset","audiovideoDeltaDts","remuxAudio","audioTrackLength","remuxVideo","videoData","remuxEmptyAudio","remuxID3","remuxText","audioSamples","videoSamples","computePTSDTS","initDTS","timeScale","mp4SampleDuration","mdat","moof","firstPTS","firstDTS","lastPTS","lastDTS","inputSamples","outputSamples","ptsNormalize","_PTSNormalize","nextAvcDts","deltadts","deltapts","PTSDTSshift","curr","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","setUint32","types","avcSampleUnits","mp4SampleLength","compositionTimeOffset","unitData","unitDataLen","lastFrameDuration","stretchShortVideoTrack","gapTolerance","deltaToFrameEnd","nextAudioPts","cts","flags","isLeading","isDependedOn","hasRedundancy","degradPrio","dependsOn","isNonSync","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","mp4Sample","fillFrame","maxAudioFramesDrift","nextPts","missing","newStamp","getSilentFrame","audioSample","numMissingFrames","unitLen","lastSampleDuration","silentFrame","reference","AAC","MP4","init","avcC","btrt","dinf","dref","esds","ftyp","mdia","mfhd","minf",".mp3","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsd","stsz","stts","trun","trex","vmhd","smhd","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","upperWordDuration","lowerWordDuration","boxes","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","arraylen","paddingValue","movie","PassThroughRemuxer","rawData","streamType","__WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__","__WEBPACK_IMPORTED_MODULE_2__utils_logger__","__WEBPACK_IMPORTED_MODULE_3_events__","__WEBPACK_IMPORTED_MODULE_3_events___default","DemuxerWorker","transferable","TimeRanges","r","findFirstFragWithCC","firstFrag","currentFrag","shouldAlignOnDiscontinuities","shouldAlign","findDiscontinuousReferenceFrag","prevDetails","prevFrags","curFrags","prevStartFrag","adjustPts","alignDiscontinuities","referenceFrag","lastPDT","newPDT","TaskLoop","_tickInterval","_tickTimer","_tickCallCount","_boundTick","clearNextTick","hasInterval","hasNextTick","_setInterval","_x","millis","_clearInterval","clearTimeout","setTimeout","calculateNextPDT","parsedDateInt","findFragmentByPDT","PDTValue","isArray","seg","findFragmentBySN","fragmentWithinToleranceTest","candidate","candidateLookupTolerance","__WEBPACK_IMPORTED_MODULE_4__utils_codecs__","__WEBPACK_IMPORTED_MODULE_5__level_helper__","LevelController","canload","currentLevelIndex","manualLevelIndex","timer","clearTimer","_levels","levelRetryCount","loadError","onManifestLoaded","bitrateStart","levelSet","levelFromSet","videoCodecFound","audioCodecFound","chromeOrFirefox","fragmentError","SUBTITLES","_ref2","_firstLevel","setLevelInternal","levelProperties","levelError","levelIndex","recoverLevel","errorEvent","errorDetails","redundantLevels","_ref3","targetdurationMs","reloadInterval","trequest","audioGroupId","findIndex","levelObject","_startLevel","configStartLevel","__WEBPACK_IMPORTED_MODULE_3__utils_texttrack_utils__","ID3TrackController","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","mode","Cue","WebKitDataCue","VTTCue","TextTrackCue","cue","addCue","sendAddTrackEvent","videoEl","Event","document","createEvent","initEvent","dispatchEvent","clearCurrentCues","cues","removeCue","mediaSource","__WEBPACK_IMPORTED_MODULE_0__utils_mediasource_helper__","sourceBuffer","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","appendBuffer","remove","hlsDefaultConfig","__WEBPACK_IMPORTED_MODULE_0__controller_abr_controller__","__WEBPACK_IMPORTED_MODULE_1__controller_buffer_controller__","__WEBPACK_IMPORTED_MODULE_2__controller_cap_level_controller__","__WEBPACK_IMPORTED_MODULE_3__controller_fps_controller__","__WEBPACK_IMPORTED_MODULE_4__utils_xhr_loader__","__WEBPACK_IMPORTED_MODULE_5__controller_audio_track_controller__","__WEBPACK_IMPORTED_MODULE_6__controller_audio_stream_controller__","__WEBPACK_IMPORTED_MODULE_7__utils_cues__","__WEBPACK_IMPORTED_MODULE_8__controller_timeline_controller__","__WEBPACK_IMPORTED_MODULE_9__controller_subtitle_track_controller__","__WEBPACK_IMPORTED_MODULE_10__controller_subtitle_stream_controller__","__WEBPACK_IMPORTED_MODULE_11__controller_eme_controller__","__WEBPACK_IMPORTED_MODULE_12__utils_mediakeys_helper__","capLevelOnFPSDrop","capLevelToPlayerSize","lowBufferWatchdogPeriod","liveDurationInfinity","fpsDroppedMonitoringPeriod","fpsDroppedMonitoringThreshold","appendErrorMaxRetry","xhrSetup","licenseXhrSetup","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","abrBandWidthFactor","abrBandWidthUpFactor","abrMaxWithRealBitrate","maxStarvationDelay","maxLoadingDelay","emeEnabled","widevineLicenseUrl","requestMediaKeySystemAccessFunc","__WEBPACK_IMPORTED_MODULE_2__utils_buffer_helper__","__WEBPACK_IMPORTED_MODULE_5__utils_ewma_bandwidth_estimator__","AbrController","lastLoadedFragLevel","_nextAutoLevel","_bwEstimator","onCheck","_abandonRulesCheck","isLive","ewmaFast","ewmaSlow","aborted","playbackRate","requestDelay","loadRate","bw","expectedLen","fragLoadedDelay","bufferStarvationDelay","fragLevelNextLoadedDelay","levelNextBitrate","loadedBytes","loadedDuration","fragLoadingProcessingMs","bwEstimate","getEstimate","bitrateTestDelay","_findBestLevel","currentFragDuration","currentBw","maxFetchDuration","bwFactor","bwUpFactor","avgDuration","adjustedbw","fetchDuration","forcedAutoLevel","bwEstimator","canEstimate","nextABRAutoLevel","_nextABRAutoLevel","avgbw","bestLevel","__WEBPACK_IMPORTED_MODULE_0__utils_ewma__","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","durationMs","numBytes","bandwidth","weight","getTotalWeight","EWMA","halfLife","alpha_","exp","estimate_","totalWeight_","adjAlpha","zeroFactor","__WEBPACK_IMPORTED_MODULE_4__utils_mediasource_helper__","BufferController","_msDuration","_levelDuration","_live","_objectUrl","onsbue","onSBUpdateEnd","onsbe","onSBUpdateError","pendingTracks","onLevelPtsUpdated","audioBuffer","timestampOffset","updating","audioTimestampOffset","audioExpected","videoExpected","sourceBufferNb","onMediaAttaching","ms","onmso","onMediaSourceOpen","onmse","onMediaSourceEnded","onmsc","onMediaSourceClose","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","flushBuffer","appendError","code","typeIn","bufStart","bufEnd","flushStart","flushEnd","CapLevelController","restrictedLevels","_stopCapping","onFpsDropLevelCapping","isLevelAllowed","droppedLevel","HTMLVideoElement","_startCapping","onLevelsUpdated","detectPlayerSize","levelsLength","getMaxLevel","capLevelIndex","validLevels","getMaxLevelByMediaSize","mediaWidth","mediaHeight","maxLevelIndex","clientWidth","offsetWidth","contentScaleFactor","clientHeight","offsetHeight","devicePixelRatio","FPSController","isVideoPlaybackQualityAvailable","getVideoPlaybackQuality","checkFPSInterval","checkFPS","decodedFrames","droppedFrames","lastTime","currentPeriod","currentDropped","lastDroppedFrames","currentDecoded","lastDecodedFrames","droppedFPS","totalDroppedFrames","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","XMLHttpRequest","XhrLoader","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","requestMediaKeySystemAccess","endsWith","$defineProperty","stringLength","searchString","searchLength"],"mappings":"CAAA,SAAAA,EAAAC,GACA,gBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,IACA,kBAAAG,gBAAAC,IACAD,UAAAH,GACA,gBAAAC,SACAA,QAAA,IAAAD,IAEAD,EAAA,IAAAC,KACCK,KAAA,WACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAP,OAGA,IAAAC,GAAAO,EAAAD,IACAE,EAAAF,EACAG,GAAA,EACAV,WAUA,OANAK,GAAAE,GAAAI,KAAAV,EAAAD,QAAAC,IAAAD,QAAAM,GAGAL,EAAAS,GAAA,EAGAT,EAAAD,QAvBA,GAAAQ,KA4DA,OAhCAF,GAAAM,EAAAP,EAGAC,EAAAO,EAAAL,EAGAF,EAAAQ,EA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hls.light.min.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","(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 /******/ (function(modules) { // webpackBootstrap\n/******/ \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 = 23);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return enableLogs; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return logger; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__get_self_scope__ = __webpack_require__(5);\nvar _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; };\n\n\n\nfunction noop() {}\n\nvar fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nvar exportedLogger = fakeLogger;\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\nvar global = Object(__WEBPACK_IMPORTED_MODULE_0__get_self_scope__[\"a\" /* getSelfScope */])();\n\nfunction consolePrintFn(type) {\n var func = global.console[type];\n if (func) {\n return function () {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n\n func.apply(global.console, args);\n };\n }\n return noop;\n}\n\nfunction exportLoggerFunctions(debugConfig) {\n for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n functions[_key2 - 1] = arguments[_key2];\n }\n\n functions.forEach(function (type) {\n exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);\n });\n}\n\nvar enableLogs = function enableLogs(debugConfig) {\n if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {\n exportLoggerFunctions(debugConfig,\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug', 'log', 'info', 'warn', 'error');\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 } else {\n exportedLogger = fakeLogger;\n }\n};\n\nvar logger = exportedLogger;\n\n/***/ }),\n/* 1 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/**\n * @readonly\n * @enum {string}\n */\nvar HlsEvents = {\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 }\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 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/* harmony default export */ __webpack_exports__[\"a\"] = (HlsEvents);\n\n/***/ }),\n/* 2 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return ErrorTypes; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return ErrorDetails; });\nvar 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 // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR: 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nvar ErrorDetails = {\n KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',\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 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/* 3 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\nvar _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; };\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/*\n*\n* All objects in the event handling chain should inherit from this class\n*\n*/\n\n\n\n\n\nvar FORBIDDEN_EVENT_NAMES = new Set(['hlsEventGeneric', 'hlsHandlerDestroying', 'hlsHandlerDestroyed']);\n\nvar EventHandler = function () {\n function EventHandler(hls) {\n _classCallCheck(this, EventHandler);\n\n this.hls = hls;\n this.onEvent = this.onEvent.bind(this);\n\n for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n events[_key - 1] = arguments[_key];\n }\n\n this.handledEvents = events;\n this.useGenericHandler = true;\n\n this.registerListeners();\n }\n\n EventHandler.prototype.destroy = function destroy() {\n this.onHandlerDestroying();\n this.unregisterListeners();\n this.onHandlerDestroyed();\n };\n\n EventHandler.prototype.onHandlerDestroying = function onHandlerDestroying() {};\n\n EventHandler.prototype.onHandlerDestroyed = function onHandlerDestroyed() {};\n\n EventHandler.prototype.isEventHandler = function isEventHandler() {\n return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';\n };\n\n EventHandler.prototype.registerListeners = function registerListeners() {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function (event) {\n if (FORBIDDEN_EVENT_NAMES.has(event)) {\n throw new Error('Forbidden event-name: ' + event);\n }\n\n this.hls.on(event, this.onEvent);\n }, this);\n }\n };\n\n EventHandler.prototype.unregisterListeners = function 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\n\n EventHandler.prototype.onEvent = function onEvent(event, data) {\n this.onEventGeneric(event, data);\n };\n\n EventHandler.prototype.onEventGeneric = function onEventGeneric(event, data) {\n var eventToFunction = function eventToFunction(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\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].error('An internal error happened while handling event ' + event + '. Error message: \"' + err.message + '\". Here is a stacktrace:', err);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_1__errors__[\"b\" /* ErrorTypes */].OTHER_ERROR, details: __WEBPACK_IMPORTED_MODULE_1__errors__[\"a\" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: false, event: event, err: err });\n }\n };\n\n return EventHandler;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (EventHandler);\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n// This file is inserted as a shim for modules which we do not want to include into the distro.\n// This replacement is done in the \"resolve\" section of the webpack config.\nmodule.exports = void 0;\n\n/***/ }),\n/* 5 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = getSelfScope;\nfunction getSelfScope() {\n // see https://stackoverflow.com/a/11237259/589493\n if (typeof window === 'undefined') {\n /* eslint-disable-next-line no-undef */\n return self;\n } else {\n return window;\n }\n}\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n// see https://tools.ietf.org/html/rfc1808\r\n\r\n/* jshint ignore:start */\r\n(function(root) { \r\n/* jshint ignore:end */\r\n\r\n var URL_REGEX = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\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 (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(true)\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/* 7 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nvar 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 search(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 } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n\n return null;\n }\n};\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (BinarySearch);\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n// 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/* 9 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export utf8ArrayToStr */\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * ID3 parser\n */\nvar ID3 = function () {\n function ID3() {\n _classCallCheck(this, ID3);\n }\n\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 ID3.isHeader = function 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\n\n ID3.isFooter = function 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\n\n ID3.getID3Data = function getID3Data(data, offset) {\n var front = offset;\n var length = 0;\n\n while (ID3.isHeader(data, offset)) {\n // ID3 header is 10 bytes\n length += 10;\n\n var 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 ID3._readSize = function _readSize(data, offset) {\n var 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\n\n ID3.getTimeStamp = function getTimeStamp(data) {\n var frames = ID3.getID3Frames(data);\n for (var i = 0; i < frames.length; i++) {\n var 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\n\n ID3.isTimeStampFrame = function isTimeStampFrame(frame) {\n return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';\n };\n\n ID3._getFrameData = function _getFrameData(data) {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n var type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n var size = ID3._readSize(data, 4);\n\n // skip frame id, size, and flags\n var offset = 10;\n\n return { type: type, size: 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\n\n ID3.getID3Frames = function getID3Frames(id3Data) {\n var offset = 0;\n var frames = [];\n\n while (ID3.isHeader(id3Data, offset)) {\n var size = ID3._readSize(id3Data, offset + 6);\n // skip past ID3 header\n offset += 10;\n var end = offset + size;\n // loop through frames in the ID3 tag\n while (offset + 8 < end) {\n var frameData = ID3._getFrameData(id3Data.subarray(offset));\n var frame = ID3._decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\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 ID3._decodeFrame = function _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 ID3._readTimeStamp = function _readTimeStamp(timeStampFrame) {\n if (timeStampFrame.data.byteLength === 8) {\n var 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 var pts33Bit = data[3] & 0x1;\n var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];\n timestamp /= 45;\n\n if (pts33Bit) {\n timestamp += 47721858.84;\n } // 2^32 / 90\n\n return Math.round(timestamp);\n }\n\n return undefined;\n };\n\n ID3._decodePrivFrame = function _decodePrivFrame(frame) {\n /*\n Format: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n var owner = ID3._utf8ArrayToStr(frame.data, true);\n var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n };\n\n ID3._decodeTextFrame = function _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 var index = 1;\n var description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n var 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 var text = ID3._utf8ArrayToStr(frame.data.subarray(1));\n return { key: frame.type, data: text };\n }\n };\n\n ID3._decodeURLFrame = function _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 var index = 1;\n var description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n var 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 var 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\n\n ID3._utf8ArrayToStr = function _utf8ArrayToStr(array) {\n var exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var len = array.length;\n var c = void 0;\n var char2 = void 0;\n var char3 = void 0;\n var out = '';\n var i = 0;\n while (i < len) {\n c = array[i++];\n if (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\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 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);\n break;\n default:\n }\n }\n return out;\n };\n\n return ID3;\n}();\n\nvar utf8ArrayToStr = ID3._utf8ArrayToStr;\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (ID3);\n\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = getMediaSource;\n/**\n * MediaSource helper\n */\n\nfunction getMediaSource() {\n if (typeof window !== 'undefined') {\n return window.MediaSource || window.WebKitMediaSource;\n }\n}\n\n/***/ }),\n/* 11 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__ = __webpack_require__(12);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__ = __webpack_require__(24);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\n\n\n\n\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\n\nvar ContextType = {\n MANIFEST: 'manifest',\n LEVEL: 'level',\n AUDIO_TRACK: 'audioTrack',\n SUBTITLE_TRACK: 'subtitleTrack'\n};\n\n/**\n * @enum {string}\n */\nvar LevelType = {\n MAIN: 'main',\n AUDIO: 'audio',\n SUBTITLE: 'subtitle'\n};\n\n/**\n * @constructor\n */\n\nvar PlaylistLoader = function (_EventHandler) {\n _inherits(PlaylistLoader, _EventHandler);\n\n /**\n * @constructs\n * @param {Hls} hls\n */\n function PlaylistLoader(hls) {\n _classCallCheck(this, PlaylistLoader);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_LOADING));\n\n _this.loaders = {};\n return _this;\n }\n\n /**\n * @param {ContextType} type\n * @returns {boolean}\n */\n PlaylistLoader.canHaveQualityLevels = function canHaveQualityLevels(type) {\n return type !== ContextType.AUDIO_TRACK && type !== ContextType.SUBTITLE_TRACK;\n };\n\n /**\n * Map context.type to LevelType\n * @param {{type: ContextType}} context\n * @returns {LevelType}\n */\n\n\n PlaylistLoader.mapContextToLevelType = function mapContextToLevelType(context) {\n var type = context.type;\n\n\n switch (type) {\n case ContextType.AUDIO_TRACK:\n return LevelType.AUDIO;\n case ContextType.SUBTITLE_TRACK:\n return LevelType.SUBTITLE;\n default:\n return LevelType.MAIN;\n }\n };\n\n PlaylistLoader.getResponseUrl = function getResponseUrl(response, context) {\n var url = response.url;\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 return url;\n };\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {object} context\n * @returns {XHRLoader} or other compatible configured overload\n */\n\n\n PlaylistLoader.prototype.createInternalLoader = function createInternalLoader(context) {\n var config = this.hls.config;\n var PLoader = config.pLoader;\n var Loader = config.loader;\n var InternalLoader = PLoader || Loader;\n\n var loader = new InternalLoader(config);\n\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n };\n\n PlaylistLoader.prototype.getInternalLoader = function getInternalLoader(context) {\n return this.loaders[context.type];\n };\n\n PlaylistLoader.prototype.resetInternalLoader = function resetInternalLoader(contextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n };\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n\n\n PlaylistLoader.prototype.destroyInternalLoaders = function destroyInternalLoaders() {\n for (var contextType in this.loaders) {\n var loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n };\n\n PlaylistLoader.prototype.destroy = function destroy() {\n this.destroyInternalLoaders();\n\n _EventHandler.prototype.destroy.call(this);\n };\n\n PlaylistLoader.prototype.onManifestLoading = function onManifestLoading(data) {\n this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });\n };\n\n PlaylistLoader.prototype.onLevelLoading = function onLevelLoading(data) {\n this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });\n };\n\n PlaylistLoader.prototype.onAudioTrackLoading = function onAudioTrackLoading(data) {\n this.load(data.url, { type: ContextType.AUDIO_TRACK, level: 0, id: data.id });\n };\n\n PlaylistLoader.prototype.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) {\n this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: 0, id: data.id });\n };\n\n PlaylistLoader.prototype.load = function load(url, context) {\n var config = this.hls.config;\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].debug('Loading playlist of type ' + context.type + ', level: ' + context.level + ', id: ' + context.id);\n\n // Check if a loader for this context already exists\n var loader = this.getInternalLoader(context);\n if (loader) {\n var loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) {\n // same URL can't overlap\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].trace('playlist request ongoing');\n return false;\n } else {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].warn('aborting previous loader for type: ' + context.type);\n loader.abort();\n }\n }\n\n var maxRetry = void 0,\n timeout = void 0,\n retryDelay = void 0,\n maxRetryDelay = void 0;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case ContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case ContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n context.url = url;\n context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)\n\n var loaderConfig = {\n timeout: timeout,\n maxRetry: maxRetry,\n retryDelay: retryDelay,\n maxRetryDelay: maxRetryDelay\n };\n\n var loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].debug('Calling internal loader delegate for URL: ' + url);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n };\n\n PlaylistLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {\n var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n\n var string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n };\n\n PlaylistLoader.prototype.loaderror = function loaderror(response, context) {\n var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n this._handleNetworkError(context, networkDetails);\n };\n\n PlaylistLoader.prototype.loadtimeout = function loadtimeout(stats, context) {\n var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n this._handleNetworkError(context, networkDetails, true);\n };\n\n PlaylistLoader.prototype._handleMasterPlaylist = function _handleMasterPlaylist(response, stats, context, networkDetails) {\n var hls = this.hls;\n var string = response.data;\n\n var url = PlaylistLoader.getResponseUrl(response, context);\n\n var levels = __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__[\"a\" /* default */].parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n\n var audioGroups = levels.map(function (level) {\n return {\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n };\n });\n\n var audioTracks = __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__[\"a\" /* default */].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n var subtitles = __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__[\"a\" /* default */].parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n var embeddedAudioFound = false;\n audioTracks.forEach(function (audioTrack) {\n if (!audioTrack.url) {\n embeddedAudioFound = true;\n }\n });\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('audio codec signaled in quality level, but no embedded audio track signaled, create one');\n audioTracks.unshift({\n type: 'main',\n name: 'main'\n });\n }\n }\n\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADED, {\n levels: levels,\n audioTracks: audioTracks,\n subtitles: subtitles,\n url: url,\n stats: stats,\n networkDetails: networkDetails\n });\n };\n\n PlaylistLoader.prototype._handleTrackOrLevelPlaylist = function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {\n var hls = this.hls;\n\n var id = context.id,\n level = context.level,\n type = context.type;\n\n\n var url = PlaylistLoader.getResponseUrl(response, context);\n\n var levelUrlId = isNaN(id) ? 0 : id;\n var levelId = isNaN(level) ? levelUrlId : level; // level -> id -> 0\n var levelType = PlaylistLoader.mapContextToLevelType(context);\n\n var levelDetails = __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__[\"a\" /* default */].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n levelDetails.tload = stats.tload;\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === ContextType.MANIFEST) {\n var singleLevel = {\n url: url,\n details: levelDetails\n };\n\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url: url,\n stats: stats,\n networkDetails: networkDetails\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n var sidxUrl = levelDetails.initSegment.url;\n this.load(sidxUrl, {\n isSidxRequest: true,\n type: type,\n level: level,\n levelDetails: levelDetails,\n id: id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n };\n\n PlaylistLoader.prototype._handleSidxRequest = function _handleSidxRequest(response, context) {\n var sidxInfo = __WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__[\"a\" /* default */].parseSegmentIndex(new Uint8Array(response.data));\n sidxInfo.references.forEach(function (segmentRef, index) {\n var segRefInfo = segmentRef.info;\n var frag = context.levelDetails.fragments[index];\n\n if (frag.byteRange.length === 0) {\n frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);\n }\n });\n\n context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';\n };\n\n PlaylistLoader.prototype._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) {\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason: reason,\n networkDetails: networkDetails\n });\n };\n\n PlaylistLoader.prototype._handleNetworkError = function _handleNetworkError(context, networkDetails) {\n var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].info('A network error occured while loading a ' + context.type + '-type playlist');\n\n var details = void 0;\n var fatal = void 0;\n\n var loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case ContextType.MANIFEST:\n details = timeout ? __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].MANIFEST_LOAD_TIMEOUT : __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].MANIFEST_LOAD_ERROR;\n fatal = true;\n break;\n case ContextType.LEVEL:\n details = timeout ? __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT : __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_ERROR;\n fatal = false;\n break;\n case ContextType.AUDIO_TRACK:\n details = timeout ? __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT : __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR;\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR,\n details: details,\n fatal: fatal,\n url: loader.url,\n loader: loader,\n context: context,\n networkDetails: networkDetails\n });\n };\n\n PlaylistLoader.prototype._handlePlaylistLoaded = function _handlePlaylistLoaded(response, stats, context, networkDetails) {\n var type = context.type,\n level = context.level,\n id = context.id,\n levelDetails = context.levelDetails;\n\n\n if (!levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats: stats,\n networkDetails: networkDetails\n });\n } else {\n switch (type) {\n case ContextType.AUDIO_TRACK:\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id: id,\n stats: stats,\n networkDetails: networkDetails\n });\n break;\n case ContextType.SUBTITLE_TRACK:\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id: id,\n stats: stats,\n networkDetails: networkDetails\n });\n break;\n }\n }\n };\n\n _createClass(PlaylistLoader, null, [{\n key: 'ContextType',\n get: function get() {\n return ContextType;\n }\n }, {\n key: 'LevelType',\n get: function get() {\n return LevelType;\n }\n }]);\n\n return PlaylistLoader;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (PlaylistLoader);\n\n/***/ }),\n/* 12 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * MP4 demuxer\n */\n\n\n\nvar UINT32_MAX = Math.pow(2, 32) - 1;\n\nvar MP4Demuxer = function () {\n function MP4Demuxer(observer, remuxer) {\n _classCallCheck(this, MP4Demuxer);\n\n this.observer = observer;\n this.remuxer = remuxer;\n }\n\n MP4Demuxer.prototype.resetTimeStamp = function resetTimeStamp(initPTS) {\n this.initPTS = initPTS;\n };\n\n MP4Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {\n // jshint unused:false\n if (initSegment && initSegment.byteLength) {\n var 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\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\n if (initData.video) {\n tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };\n }\n }\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\n\n if (videoCodec) {\n this.videoCodec = videoCodec;\n }\n }\n };\n\n MP4Demuxer.probe = function 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 MP4Demuxer.bin2str = function bin2str(buffer) {\n return String.fromCharCode.apply(null, buffer);\n };\n\n MP4Demuxer.readUint16 = function readUint16(buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n var val = buffer[offset] << 8 | buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\n };\n\n MP4Demuxer.readUint32 = function readUint32(buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];\n return val < 0 ? 4294967296 + val : val;\n };\n\n MP4Demuxer.writeUint32 = function 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 // Find the data for a box specified by its path\n\n\n MP4Demuxer.findBox = function findBox(data, path) {\n var results = [],\n i = void 0,\n size = void 0,\n type = void 0,\n end = void 0,\n subresults = void 0,\n start = void 0,\n endbox = void 0;\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 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 MP4Demuxer.parseSegmentIndex = function parseSegmentIndex(initSegment) {\n var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n var index = 0;\n var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n var references = void 0;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n var version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n var timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n var earliestPresentationTime = 0;\n var firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n var startByte = sidx.end + firstOffset;\n\n var referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (var i = 0; i < referencesCount; i++) {\n var referenceIndex = index;\n\n var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n var referenceSize = referenceInfo & 0x7FFFFFFF;\n var referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize: referenceSize,\n subsegmentDuration: subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime: earliestPresentationTime,\n timescale: timescale,\n version: version,\n referencesCount: referencesCount,\n references: references,\n moovEndOffset: moovEndOffset\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\n\n MP4Demuxer.parseInitSegment = function parseInitSegment(initSegment) {\n var result = [];\n var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);\n\n traks.forEach(function (trak) {\n var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n var version = tkhd.data[tkhd.start];\n var index = version === 0 ? 12 : 20;\n var trackId = MP4Demuxer.readUint32(tkhd, index);\n\n var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd.data[mdhd.start];\n index = version === 0 ? 12 : 20;\n var timescale = MP4Demuxer.readUint32(mdhd, index);\n\n var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));\n var 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 var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);\n if (codecBox.length) {\n codecBox = codecBox[0];\n var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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 * 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 */\n\n\n MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) {\n var trafs = void 0,\n baseTimes = void 0,\n result = void 0;\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 = void 0,\n scale = void 0,\n baseTime = void 0;\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 = void 0,\n result = void 0;\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 MP4Demuxer.offsetStartDTS = function 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 var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n var 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\n\n MP4Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {\n var initData = this.initData;\n if (!initData) {\n this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);\n initData = this.initData;\n }\n var startDTS = void 0,\n initPTS = this.initPTS;\n if (initPTS === undefined) {\n var _startDTS = MP4Demuxer.getStartDTS(initData, data);\n this.initPTS = initPTS = _startDTS - timeOffset;\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].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 MP4Demuxer.prototype.destroy = function destroy() {};\n\n return MP4Demuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (MP4Demuxer);\n\n/***/ }),\n/* 13 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit__ = __webpack_require__(6);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_url_toolkit__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__level_key__ = __webpack_require__(14);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\nvar Fragment = function () {\n function Fragment() {\n var _elementaryStreams;\n\n _classCallCheck(this, Fragment);\n\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n this.tagList = [];\n\n // Holds the types of data this fragment supports\n this._elementaryStreams = (_elementaryStreams = {}, _elementaryStreams[Fragment.ElementaryStreamTypes.AUDIO] = false, _elementaryStreams[Fragment.ElementaryStreamTypes.VIDEO] = false, _elementaryStreams);\n }\n\n /**\n * `type` property for this._elementaryStreams\n *\n * @enum\n */\n\n\n /**\n * @param {ElementaryStreamType} type\n */\n Fragment.prototype.addElementaryStream = function addElementaryStream(type) {\n this._elementaryStreams[type] = true;\n };\n\n /**\n * @param {ElementaryStreamType} type\n */\n\n\n Fragment.prototype.hasElementaryStream = function hasElementaryStream(type) {\n return this._elementaryStreams[type] === true;\n };\n\n /**\n * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n * @returns {Uint8Array}\n */\n\n\n Fragment.prototype.createInitializationVector = function 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\n\n Fragment.prototype.fragmentDecryptdataFromLevelkey = function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {\n var decryptdata = levelkey;\n\n if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {\n decryptdata = new __WEBPACK_IMPORTED_MODULE_1__level_key__[\"a\" /* default */]();\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 _createClass(Fragment, [{\n key: 'url',\n get: function get() {\n if (!this._url && this.relurl) {\n this._url = __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default.a.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\n\n return this._url;\n },\n set: function set(value) {\n this._url = value;\n }\n }, {\n key: 'programDateTime',\n get: function get() {\n if (!this._programDateTime && this.rawProgramDateTime) {\n this._programDateTime = new Date(Date.parse(this.rawProgramDateTime));\n }\n\n return this._programDateTime;\n }\n }, {\n key: 'byteRange',\n get: function get() {\n if (!this._byteRange && !this.rawByteRange) {\n return [];\n }\n\n if (this._byteRange) {\n return this._byteRange;\n }\n\n var byteRange = [];\n if (this.rawByteRange) {\n var params = this.rawByteRange.split('@', 2);\n if (params.length === 1) {\n var lastByteRangeEndOffset = this.lastByteRangeEndOffset;\n byteRange[0] = lastByteRangeEndOffset || 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n return byteRange;\n }\n\n /**\n * @type {number}\n */\n\n }, {\n key: 'byteRangeStartOffset',\n get: function get() {\n return this.byteRange[0];\n }\n }, {\n key: 'byteRangeEndOffset',\n get: function get() {\n return this.byteRange[1];\n }\n }, {\n key: 'decryptdata',\n get: function get() {\n if (!this._decryptdata) {\n this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);\n }\n\n return this._decryptdata;\n }\n }, {\n key: 'encrypted',\n get: function get() {\n return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);\n }\n }], [{\n key: 'ElementaryStreamTypes',\n get: function get() {\n return {\n AUDIO: 'audio',\n VIDEO: 'video'\n };\n }\n }]);\n\n return Fragment;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (Fragment);\n\n/***/ }),\n/* 14 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit__ = __webpack_require__(6);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_url_toolkit__);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\nvar LevelKey = function () {\n function LevelKey() {\n _classCallCheck(this, LevelKey);\n\n this.method = null;\n this.key = null;\n this.iv = null;\n this._uri = null;\n }\n\n _createClass(LevelKey, [{\n key: 'uri',\n get: function get() {\n if (!this._uri && this.reluri) {\n this._uri = __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default.a.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });\n }\n\n return this._uri;\n }\n }]);\n\n return LevelKey;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (LevelKey);\n\n/***/ }),\n/* 15 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return isCodecType; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return isCodecSupportedInMp4; });\n// from http://mp4ra.org/codecs.html\nvar 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 var typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nfunction isCodecSupportedInMp4(codec, type) {\n return window.MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs=\"' + codec + '\"');\n}\n\n\n\n/***/ }),\n/* 16 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return FragmentState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return FragmentTracker; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n\n\n\nvar FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nvar FragmentTracker = function (_EventHandler) {\n _inherits(FragmentTracker, _EventHandler);\n\n function FragmentTracker(hls) {\n _classCallCheck(this, FragmentTracker);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].BUFFER_APPENDED, __WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_BUFFERED, __WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_LOADED));\n\n _this.bufferPadding = 0.2;\n\n _this.fragments = Object.create(null);\n _this.timeRanges = Object.create(null);\n\n _this.config = hls.config;\n return _this;\n }\n\n FragmentTracker.prototype.destroy = function destroy() {\n this.fragments = null;\n this.timeRanges = null;\n this.config = null;\n __WEBPACK_IMPORTED_MODULE_0__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n _EventHandler.prototype.destroy.call(this);\n };\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n\n\n FragmentTracker.prototype.getBufferedFrag = function getBufferedFrag(position, levelType) {\n var fragments = this.fragments;\n var bufferedFrags = Object.keys(fragments).filter(function (key) {\n var fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n var frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n var bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n };\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n\n\n FragmentTracker.prototype.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) {\n var _this2 = this;\n\n var fragmentTimes = void 0,\n time = void 0;\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(function (key) {\n var fragmentEntity = _this2.fragments[key];\n if (fragmentEntity.buffered === true) {\n var esData = fragmentEntity.range[elementaryStream];\n if (esData) {\n fragmentTimes = esData.time;\n for (var i = 0; i < fragmentTimes.length; i++) {\n time = fragmentTimes[i];\n\n if (_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {\n // Unregister partial fragment as it needs to load again to be reused\n _this2.removeFragment(fragmentEntity.body);\n break;\n }\n }\n }\n }\n });\n };\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n\n\n FragmentTracker.prototype.detectPartialFragments = function detectPartialFragments(fragment) {\n var _this3 = this;\n\n var fragKey = this.getFragmentKey(fragment);\n var fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(function (elementaryStream) {\n if (fragment.hasElementaryStream(elementaryStream) === true) {\n var timeRange = _this3.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n };\n\n FragmentTracker.prototype.getBufferedTimes = function getBufferedTimes(startPTS, endPTS, timeRange) {\n var fragmentTimes = [];\n var startTime = void 0,\n endTime = void 0;\n var fragmentPartial = false;\n for (var i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n };\n\n FragmentTracker.prototype.getFragmentKey = function getFragmentKey(fragment) {\n return fragment.type + '_' + fragment.level + '_' + fragment.urlId + '_' + fragment.sn;\n };\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n\n\n FragmentTracker.prototype.getPartialFragment = function getPartialFragment(time) {\n var _this4 = this;\n\n var timePadding = void 0,\n startTime = void 0,\n endTime = void 0;\n var bestFragment = null;\n var bestOverlap = 0;\n Object.keys(this.fragments).forEach(function (key) {\n var fragmentEntity = _this4.fragments[key];\n if (_this4.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;\n endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n };\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n\n\n FragmentTracker.prototype.getState = function getState(fragment) {\n var fragKey = this.getFragmentKey(fragment);\n var fragmentEntity = this.fragments[fragKey];\n var state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n };\n\n FragmentTracker.prototype.isPartial = function isPartial(fragmentEntity) {\n return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);\n };\n\n FragmentTracker.prototype.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {\n var startTime = void 0,\n endTime = void 0;\n for (var i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n };\n\n /**\n * Fires when a fragment loading is completed\n */\n\n\n FragmentTracker.prototype.onFragLoaded = function onFragLoaded(e) {\n var fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!isNaN(fragment.sn) && !fragment.bitrateTest) {\n var fragKey = this.getFragmentKey(fragment);\n var fragmentEntity = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n this.fragments[fragKey] = fragmentEntity;\n }\n };\n\n /**\n * Fires when the buffer is updated\n */\n\n\n FragmentTracker.prototype.onBufferAppended = function onBufferAppended(e) {\n var _this5 = this;\n\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(function (elementaryStream) {\n var timeRange = _this5.timeRanges[elementaryStream];\n _this5.detectEvictedFragments(elementaryStream, timeRange);\n });\n };\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n\n\n FragmentTracker.prototype.onFragBuffered = function onFragBuffered(e) {\n this.detectPartialFragments(e.frag);\n };\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n\n\n FragmentTracker.prototype.hasFragment = function hasFragment(fragment) {\n var fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n };\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n\n\n FragmentTracker.prototype.removeFragment = function removeFragment(fragment) {\n var fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n };\n\n /**\n * Remove all fragments from fragment tracker.\n */\n\n\n FragmentTracker.prototype.removeAllFragments = function removeAllFragments() {\n this.fragments = Object.create(null);\n };\n\n return FragmentTracker;\n}(__WEBPACK_IMPORTED_MODULE_0__event_handler__[\"a\" /* default */]);\n\n/***/ }),\n/* 17 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return BufferHelper; });\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\nvar BufferHelper = function () {\n function BufferHelper() {\n _classCallCheck(this, BufferHelper);\n }\n\n /**\n * Return true if `media`'s buffered include `position`\n * @param {HTMLMediaElement|SourceBuffer} media\n * @param {number} position\n * @returns {boolean}\n */\n BufferHelper.isBuffered = function isBuffered(media, position) {\n try {\n if (media) {\n var buffered = media.buffered;\n for (var i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n };\n\n BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {\n try {\n if (media) {\n var vbuffered = media.buffered,\n buffered = [],\n i = void 0;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });\n }\n\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n };\n\n BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {\n var buffered2 = [],\n\n // bufferStart and bufferEnd are buffer boundaries around current video position\n bufferLen = void 0,\n bufferStart = void 0,\n bufferEnd = void 0,\n bufferStartNext = void 0,\n i = void 0;\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 return BufferHelper;\n}();\n\n/***/ }),\n/* 18 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__crypt_decrypter__ = __webpack_require__(19);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__demux_aacdemuxer__ = __webpack_require__(34);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__ = __webpack_require__(12);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__demux_tsdemuxer__ = __webpack_require__(35);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__demux_mp3demuxer__ = __webpack_require__(38);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__ = __webpack_require__(39);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__remux_passthrough_remuxer__ = __webpack_require__(42);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_get_self_scope__ = __webpack_require__(5);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n// see https://stackoverflow.com/a/11237259/589493\nvar global = Object(__WEBPACK_IMPORTED_MODULE_9__utils_get_self_scope__[\"a\" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread\nvar performance = global;\n\nvar DemuxerInline = function () {\n function DemuxerInline(observer, typeSupported, config, vendor) {\n _classCallCheck(this, DemuxerInline);\n\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n }\n\n DemuxerInline.prototype.destroy = function destroy() {\n var demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n };\n\n DemuxerInline.prototype.push = function 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 var decrypter = this.decrypter;\n if (decrypter == null) {\n decrypter = this.decrypter = new __WEBPACK_IMPORTED_MODULE_2__crypt_decrypter__[\"a\" /* default */](this.observer, this.config);\n }\n\n var localthis = this;\n // performance.now() not available on WebWorker, at least on Safari Desktop\n var startTime = void 0;\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 = void 0;\n try {\n endTime = performance.now();\n } catch (error) {\n endTime = Date.now();\n }\n localthis.observer.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 DemuxerInline.prototype.pushDecrypted = function 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, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n // so let's check that current demuxer is still valid\n (discontinuity || trackSwitch) && !this.probe(data)) {\n var observer = this.observer;\n var typeSupported = this.typeSupported;\n var config = this.config;\n // probing order is TS/AAC/MP3/MP4\n var muxConfig = [{ demux: __WEBPACK_IMPORTED_MODULE_5__demux_tsdemuxer__[\"a\" /* default */], remux: __WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__[\"a\" /* default */] }, { demux: __WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__[\"a\" /* default */], remux: __WEBPACK_IMPORTED_MODULE_8__remux_passthrough_remuxer__[\"a\" /* default */] }, { demux: __WEBPACK_IMPORTED_MODULE_3__demux_aacdemuxer__[\"a\" /* default */], remux: __WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__[\"a\" /* default */] }, { demux: __WEBPACK_IMPORTED_MODULE_6__demux_mp3demuxer__[\"a\" /* default */], remux: __WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__[\"a\" /* default */] }];\n\n // probe for content type\n for (var i = 0, len = muxConfig.length; i < len; i++) {\n var mux = muxConfig[i];\n var probe = mux.demux.probe;\n if (probe(data)) {\n var _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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_1__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_1__errors__[\"a\" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });\n return;\n }\n this.demuxer = demuxer;\n }\n var 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\n demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);\n };\n\n return DemuxerInline;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (DemuxerInline);\n\n/***/ }),\n/* 19 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__aes_crypto__ = __webpack_require__(31);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__fast_aes_key__ = __webpack_require__(32);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__aes_decryptor__ = __webpack_require__(33);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_get_self_scope__ = __webpack_require__(5);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\n\n\n\n\n\n\n\n// see https://stackoverflow.com/a/11237259/589493\nvar global = Object(__WEBPACK_IMPORTED_MODULE_6__utils_get_self_scope__[\"a\" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread\n\nvar Decrypter = function () {\n function Decrypter(observer, config) {\n var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},\n _ref$removePKCS7Paddi = _ref.removePKCS7Padding,\n removePKCS7Padding = _ref$removePKCS7Paddi === undefined ? true : _ref$removePKCS7Paddi;\n\n _classCallCheck(this, Decrypter);\n\n this.logEnabled = true;\n this.observer = observer;\n this.config = config;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n var browserCrypto = global.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {}\n }\n this.disableWebCrypto = !this.subtle;\n }\n\n Decrypter.prototype.isSync = function isSync() {\n return this.disableWebCrypto && this.config.enableSoftwareAES;\n };\n\n Decrypter.prototype.decrypt = function decrypt(data, key, iv, callback) {\n var _this = this;\n\n if (this.disableWebCrypto && this.config.enableSoftwareAES) {\n if (this.logEnabled) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('JS AES decrypt');\n this.logEnabled = false;\n }\n var decryptor = this.decryptor;\n if (!decryptor) {\n this.decryptor = decryptor = new __WEBPACK_IMPORTED_MODULE_2__aes_decryptor__[\"a\" /* default */]();\n }\n\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));\n } else {\n if (this.logEnabled) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('WebCrypto AES decrypt');\n this.logEnabled = false;\n }\n var subtle = this.subtle;\n if (this.key !== key) {\n this.key = key;\n this.fastAesKey = new __WEBPACK_IMPORTED_MODULE_1__fast_aes_key__[\"a\" /* default */](subtle, key);\n }\n\n this.fastAesKey.expandKey().then(function (aesKey) {\n // decrypt using web crypto\n var crypto = new __WEBPACK_IMPORTED_MODULE_0__aes_crypto__[\"a\" /* default */](subtle, iv);\n crypto.decrypt(data, aesKey).catch(function (err) {\n _this.onWebCryptoError(err, data, key, iv, callback);\n }).then(function (result) {\n callback(result);\n });\n }).catch(function (err) {\n _this.onWebCryptoError(err, data, key, iv, callback);\n });\n }\n };\n\n Decrypter.prototype.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) {\n if (this.config.enableSoftwareAES) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('WebCrypto Error, disable WebCrypto API');\n this.disableWebCrypto = true;\n this.logEnabled = true;\n this.decrypt(data, key, iv, callback);\n } else {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].error('decrypting error : ' + err.message);\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_5__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });\n }\n };\n\n Decrypter.prototype.destroy = function destroy() {\n var decryptor = this.decryptor;\n if (decryptor) {\n decryptor.destroy();\n this.decryptor = undefined;\n }\n };\n\n return Decrypter;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (Decrypter);\n\n/***/ }),\n/* 20 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export getAudioConfig */\n/* unused harmony export isHeaderPattern */\n/* unused harmony export getHeaderLength */\n/* unused harmony export getFullFrameLength */\n/* harmony export (immutable) */ __webpack_exports__[\"d\"] = isHeader;\n/* harmony export (immutable) */ __webpack_exports__[\"e\"] = probe;\n/* harmony export (immutable) */ __webpack_exports__[\"c\"] = initTrackConfig;\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = getFrameDuration;\n/* unused harmony export parseFrameHeader */\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = appendFrame;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_get_self_scope__ = __webpack_require__(5);\n/**\n * ADTS parser helper\n */\n\n\n\n\n\n\n\nfunction getAudioConfig(observer, data, offset, audioCodec) {\n var adtsObjectType = void 0,\n // :int\n adtsSampleingIndex = void 0,\n // :int\n adtsExtensionSampleingIndex = void 0,\n // :int\n adtsChanelConfig = void 0,\n // :int\n config = void 0,\n userAgent = navigator.userAgent.toLowerCase(),\n manifestCodec = audioCodec,\n adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_1__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_1__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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 || audioCodec.indexOf('mp4a.40.5') !== -1) || !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 || /vivaldi/i.test(userAgent)) || !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\nfunction isHeaderPattern(data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nfunction getHeaderLength(data, offset) {\n return data[offset + 1] & 0x01 ? 7 : 9;\n}\n\nfunction getFullFrameLength(data, offset) {\n return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;\n}\n\nfunction 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\n return false;\n}\n\nfunction 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 var headerLength = getHeaderLength(data, offset);\n // ADTS frame Length\n var frameLength = headerLength;\n if (offset + 5 < data.length) {\n frameLength = getFullFrameLength(data, offset);\n }\n\n var 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\nfunction 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);\n }\n}\n\nfunction getFrameDuration(samplerate) {\n return 1024 * 90000 / samplerate;\n}\n\nfunction parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {\n var headerLength = void 0,\n frameLength = void 0,\n stamp = void 0;\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: headerLength, frameLength: frameLength, stamp: stamp };\n }\n\n return undefined;\n}\n\nfunction 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/* 21 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/**\n * MPEG parser helper\n */\n\nvar MpegAudio = {\n\n 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],\n\n SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],\n\n SamplesCoefficients: [\n // MPEG 2.5\n [0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]],\n\n BytesInSlot: [0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\n\n appendFrame: function appendFrame(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 = header.samplesPerFrame * 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: sample, length: header.frameLength };\n }\n\n return undefined;\n },\n\n parseHeader: function parseHeader(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] >> 1 & 1;\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 channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n var bytesInSlot = MpegAudio.BytesInSlot[headerC];\n var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame };\n }\n\n return undefined;\n },\n\n isHeaderPattern: function isHeaderPattern(data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n },\n\n isHeader: function isHeader(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\n return false;\n },\n\n probe: function probe(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 var headerLength = 4;\n // MPEG frame Length\n var header = this.parseHeader(data, offset);\n var frameLength = headerLength;\n if (header && header.frameLength) {\n frameLength = header.frameLength;\n }\n\n var 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\n/* harmony default export */ __webpack_exports__[\"a\"] = (MpegAudio);\n\n/***/ }),\n/* 22 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = addGroupId;\n/* unused harmony export updatePTS */\n/* harmony export (immutable) */ __webpack_exports__[\"c\"] = updateFragPTSDTS;\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = mergeDetails;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\n/**\n * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\n\n\nfunction addGroupId(level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nfunction updatePTS(fragments, fromIdx, toIdx) {\n var fragFrom = fragments[fromIdx],\n fragTo = fragments[toIdx],\n 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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\nfunction updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {\n // update frag PTS/DTS\n var maxStartPTS = startPTS;\n if (!isNaN(frag.startPTS)) {\n // delta PTS between audio and video\n var 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\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 var 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 var sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n\n var fragIdx = void 0,\n fragments = void 0,\n i = void 0;\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\n details.PTSKnown = true;\n // logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);\n\n return drift;\n}\n\nfunction 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 = void 0;\n\n // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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/* 23 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit__ = __webpack_require__(6);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_url_toolkit__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__loader_playlist_loader__ = __webpack_require__(11);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__loader_fragment_loader__ = __webpack_require__(26);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__loader_key_loader__ = __webpack_require__(27);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__controller_fragment_tracker__ = __webpack_require__(16);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__controller_stream_controller__ = __webpack_require__(28);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__controller_level_controller__ = __webpack_require__(48);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__controller_id3_track_controller__ = __webpack_require__(49);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__is_supported__ = __webpack_require__(51);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__config__ = __webpack_require__(52);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13_events__ = __webpack_require__(8);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_13_events__);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// polyfill for IE11\n__webpack_require__(61);\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\n\nvar Hls = function () {\n\n /**\n * @type {boolean}\n */\n Hls.isSupported = function isSupported() {\n return Object(__WEBPACK_IMPORTED_MODULE_9__is_supported__[\"a\" /* isSupported */])();\n };\n\n /**\n * @type {HlsEvents}\n */\n\n\n _createClass(Hls, null, [{\n key: 'version',\n\n /**\n * @type {string}\n */\n get: function get() {\n return \"0.10.0\";\n }\n }, {\n key: 'Events',\n get: function get() {\n return __WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */];\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n\n }, {\n key: 'ErrorTypes',\n get: function get() {\n return __WEBPACK_IMPORTED_MODULE_1__errors__[\"b\" /* ErrorTypes */];\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n\n }, {\n key: 'ErrorDetails',\n get: function get() {\n return __WEBPACK_IMPORTED_MODULE_1__errors__[\"a\" /* ErrorDetails */];\n }\n\n /**\n * @type {HlsConfig}\n */\n\n }, {\n key: 'DefaultConfig',\n get: function get() {\n if (!Hls.defaultConfig) {\n return __WEBPACK_IMPORTED_MODULE_11__config__[\"a\" /* hlsDefaultConfig */];\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n ,\n set: function set(defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n\n }]);\n\n function Hls() {\n var _this = this;\n\n var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Hls);\n\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 Object(__WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"a\" /* enableLogs */])(config.debug);\n this.config = config;\n this._autoLevelCapping = -1;\n // observer setup\n var observer = this.observer = new __WEBPACK_IMPORTED_MODULE_13_events___default.a();\n observer.trigger = function trigger(event) {\n for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n data[_key - 1] = arguments[_key];\n }\n\n observer.emit.apply(observer, [event, event].concat(data));\n };\n\n observer.off = function off(event) {\n for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n data[_key2 - 1] = arguments[_key2];\n }\n\n observer.removeListener.apply(observer, [event].concat(data));\n };\n this.on = observer.on.bind(observer);\n this.off = observer.off.bind(observer);\n this.once = observer.once.bind(observer);\n this.trigger = observer.trigger.bind(observer);\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n var abrController = this.abrController = new config.abrController(this);\n\n var bufferController = new config.bufferController(this);\n var capLevelController = new config.capLevelController(this);\n var fpsController = new config.fpsController(this);\n var playListLoader = new __WEBPACK_IMPORTED_MODULE_2__loader_playlist_loader__[\"a\" /* default */](this);\n var fragmentLoader = new __WEBPACK_IMPORTED_MODULE_3__loader_fragment_loader__[\"a\" /* default */](this);\n var keyLoader = new __WEBPACK_IMPORTED_MODULE_4__loader_key_loader__[\"a\" /* default */](this);\n var id3TrackController = new __WEBPACK_IMPORTED_MODULE_8__controller_id3_track_controller__[\"a\" /* default */](this);\n\n // network controllers\n\n /**\n * @member {LevelController} levelController\n */\n var levelController = this.levelController = new __WEBPACK_IMPORTED_MODULE_7__controller_level_controller__[\"a\" /* default */](this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n var fragmentTracker = new __WEBPACK_IMPORTED_MODULE_5__controller_fragment_tracker__[\"b\" /* FragmentTracker */](this);\n\n /**\n * @member {StreamController} streamController\n */\n var streamController = this.streamController = new __WEBPACK_IMPORTED_MODULE_6__controller_stream_controller__[\"a\" /* default */](this, fragmentTracker);\n\n var networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n var Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n var audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n var subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n coreComponents.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n var emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\n }\n\n // optional subtitle controller\n [config.subtitleStreamController, config.timelineController].forEach(function (Controller) {\n if (Controller) {\n coreComponents.push(new Controller(_this));\n }\n });\n\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n\n\n Hls.prototype.destroy = function destroy() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('destroy');\n this.trigger(__WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */].DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(function (component) {\n component.destroy();\n });\n this.url = null;\n this.observer.removeAllListeners();\n this._autoLevelCapping = -1;\n };\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n\n\n Hls.prototype.attachMedia = function attachMedia(media) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('attachMedia');\n this.media = media;\n this.trigger(__WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */].MEDIA_ATTACHING, { media: media });\n };\n\n /**\n * Detach from the media\n */\n\n\n Hls.prototype.detachMedia = function detachMedia() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('detachMedia');\n this.trigger(__WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */].MEDIA_DETACHING);\n this.media = null;\n };\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\n */\n\n\n Hls.prototype.loadSource = function loadSource(url) {\n url = __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default.a.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('loadSource:' + url);\n this.url = url;\n // when attaching to a source URL, trigger a playlist load\n this.trigger(__WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */].MANIFEST_LOADING, { url: url });\n };\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n\n\n Hls.prototype.startLoad = function startLoad() {\n var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;\n\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('startLoad(' + startPosition + ')');\n this.networkControllers.forEach(function (controller) {\n controller.startLoad(startPosition);\n });\n };\n\n /**\n * Stop loading of any stream data.\n */\n\n\n Hls.prototype.stopLoad = function stopLoad() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('stopLoad');\n this.networkControllers.forEach(function (controller) {\n controller.stopLoad();\n });\n };\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n\n\n Hls.prototype.swapAudioCodec = function swapAudioCodec() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n };\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n\n\n Hls.prototype.recoverMediaError = function recoverMediaError() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('recoverMediaError');\n var media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n };\n\n /**\n * @type {QualityLevel[]}\n */\n\n\n _createClass(Hls, [{\n key: 'levels',\n get: function get() {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n\n }, {\n key: 'currentLevel',\n get: function get() {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @type {number} -1 for automatic level selection\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set currentLevel:' + newLevel);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n\n }, {\n key: 'nextLevel',\n get: function get() {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set nextLevel:' + newLevel);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n\n }, {\n key: 'loadLevel',\n get: function get() {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set loadLevel:' + newLevel);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n\n }, {\n key: 'nextLoadLevel',\n get: function get() {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n ,\n set: function set(level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n\n }, {\n key: 'firstLevel',\n get: function get() {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set firstLevel:' + newLevel);\n this.levelController.firstLevel = newLevel;\n }\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\n * (determined from download of first segment)\n * @type {number}\n */\n\n }, {\n key: 'startLevel',\n get: function get() {\n return this.levelController.startLevel;\n }\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\n * (determined from download of first segment)\n * @type {number} newLevel\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set startLevel:' + newLevel);\n var 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\n hls.levelController.startLevel = newLevel;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n\n }, {\n key: 'autoLevelCapping',\n get: function get() {\n return this._autoLevelCapping;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set autoLevelCapping:' + newLevel);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n\n }, {\n key: 'autoLevelEnabled',\n get: function get() {\n return this.levelController.manualLevel === -1;\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n\n }, {\n key: 'manualLevel',\n get: function get() {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\n\n }, {\n key: 'minAutoLevel',\n get: function get() {\n var hls = this,\n levels = hls.levels,\n minAutoBitrate = hls.config.minAutoBitrate,\n len = levels ? levels.length : 0;\n for (var i = 0; i < len; i++) {\n var 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 /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\n\n }, {\n key: 'maxAutoLevel',\n get: function get() {\n var hls = this;\n var levels = hls.levels;\n var autoLevelCapping = hls.autoLevelCapping;\n var maxAutoLevel = void 0;\n if (autoLevelCapping === -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\n\n }, {\n key: 'nextAutoLevel',\n get: function get() {\n var 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 /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * 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,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n ,\n set: function set(nextLevel) {\n var hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n\n }, {\n key: 'audioTracks',\n get: function get() {\n var audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n\n }, {\n key: 'audioTrack',\n get: function get() {\n var audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n ,\n set: function set(audioTrackId) {\n var audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n\n }, {\n key: 'liveSyncPosition',\n get: function get() {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n\n }, {\n key: 'subtitleTracks',\n get: function get() {\n var subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n\n }, {\n key: 'subtitleTrack',\n get: function get() {\n var subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type{number}\n */\n ,\n set: function set(subtitleTrackId) {\n var subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n\n }, {\n key: 'subtitleDisplay',\n get: function get() {\n var subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\n */\n ,\n set: function set(value) {\n var subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n }]);\n\n return Hls;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Hls);\n\n/***/ }),\n/* 24 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit__ = __webpack_require__(6);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_url_toolkit__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__fragment__ = __webpack_require__(13);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__level_key__ = __webpack_require__(14);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__ = __webpack_require__(25);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_codecs__ = __webpack_require__(15);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\n\n\n\n\n\n/**\n * M3U8 parser\n * @module\n */\n\n// https://regex101.com is your friend\nvar MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)/g;\nvar MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nvar LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#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\nvar 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\nvar MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nvar M3U8Parser = function () {\n function M3U8Parser() {\n _classCallCheck(this, M3U8Parser);\n }\n\n M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {\n if (!groups) {\n return null;\n }\n\n var matchingGroup = null;\n\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n if (group.id === mediaGroupId) {\n matchingGroup = group;\n }\n }\n\n return matchingGroup;\n };\n\n M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {\n var result = void 0,\n 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 M3U8Parser.resolve = function resolve(url, baseUrl) {\n return __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default.a.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n };\n\n M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {\n var levels = [],\n result = void 0;\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n function setCodecs(codecs, level) {\n ['video', 'audio'].forEach(function (type) {\n var filtered = codecs.filter(function (codec) {\n return Object(__WEBPACK_IMPORTED_MODULE_5__utils_codecs__[\"b\" /* isCodecType */])(codec, type);\n });\n if (filtered.length) {\n var preferred = filtered.filter(function (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(function (codec) {\n return filtered.indexOf(codec) === -1;\n });\n }\n });\n\n level.unknownCodecs = codecs;\n }\n\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n var level = {};\n\n var attrs = level.attrs = new __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](result[1]);\n level.url = M3U8Parser.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 = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n }\n return levels;\n };\n\n M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type) {\n var audioGroups = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];\n\n var result = void 0;\n var medias = [];\n var id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n var media = {};\n var attrs = new __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](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 = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n media.lang = attrs.LANGUAGE;\n if (!media.name) {\n media.name = media.lang;\n }\n\n if (audioGroups.length) {\n var groupCodec = M3U8Parser.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 M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {\n var currentSN = 0,\n totalduration = 0,\n level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 },\n levelkey = new __WEBPACK_IMPORTED_MODULE_2__level_key__[\"a\" /* default */](),\n cc = 0,\n prevFrag = null,\n frag = new __WEBPACK_IMPORTED_MODULE_1__fragment__[\"a\" /* default */](),\n result = void 0,\n i = void 0;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n var duration = result[1];\n if (duration) {\n // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n var title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);\n } else if (result[3]) {\n // url\n if (!isNaN(frag.duration)) {\n var 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.urlId = levelUrlId;\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 if (level.programDateTime) {\n if (prevFrag) {\n if (frag.rawProgramDateTime) {\n // PDT discontinuity found\n frag.pdt = Date.parse(frag.rawProgramDateTime);\n } else {\n // Contiguous fragment\n frag.pdt = prevFrag.pdt + prevFrag.duration * 1000;\n }\n } else {\n // First fragment\n frag.pdt = Date.parse(level.programDateTime);\n }\n frag.endPdt = frag.pdt + frag.duration * 1000;\n }\n\n level.fragments.push(frag);\n prevFrag = frag;\n totalduration += frag.duration;\n\n frag = new __WEBPACK_IMPORTED_MODULE_1__fragment__[\"a\" /* default */]();\n }\n } else if (result[4]) {\n // X-BYTERANGE\n frag.rawByteRange = (' ' + result[4]).slice(1);\n if (prevFrag) {\n var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;\n if (lastByteRangeEndOffset) {\n frag.lastByteRangeEndOffset = lastByteRangeEndOffset;\n }\n }\n } else if (result[5]) {\n // 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 var value1 = (' ' + result[i + 1]).slice(1);\n var 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 __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](decryptparams);\n var decryptmethod = keyAttrs.enumeratedString('METHOD'),\n decrypturi = keyAttrs.URI,\n decryptiv = keyAttrs.hexadecimalInteger('IV');\n if (decryptmethod) {\n levelkey = new __WEBPACK_IMPORTED_MODULE_2__level_key__[\"a\" /* default */]();\n if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].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 var startParams = value1;\n var startAttrs = new __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](startParams);\n var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n // TIME-OFFSET can be 0\n if (!isNaN(startTimeOffset)) {\n level.startTimeOffset = startTimeOffset;\n }\n\n break;\n case 'MAP':\n var mapAttrs = new __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](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 __WEBPACK_IMPORTED_MODULE_1__fragment__[\"a\" /* default */]();\n break;\n default:\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every(function (frag) {\n return MP4_REGEX_SUFFIX.test(frag.relurl);\n })) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new __WEBPACK_IMPORTED_MODULE_1__fragment__[\"a\" /* default */]();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n return level;\n };\n\n return M3U8Parser;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (M3U8Parser);\n\n/***/ }),\n/* 25 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nvar ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\n\nvar AttrList = function () {\n function AttrList(attrs) {\n _classCallCheck(this, AttrList);\n\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (var attr in attrs) {\n if (attrs.hasOwnProperty(attr)) {\n this[attr] = attrs[attr];\n }\n }\n }\n\n AttrList.prototype.decimalInteger = function decimalInteger(attrName) {\n var intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n };\n\n AttrList.prototype.hexadecimalInteger = function hexadecimalInteger(attrName) {\n if (this[attrName]) {\n var stringValue = (this[attrName] || '0x').slice(2);\n stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;\n\n var value = new Uint8Array(stringValue.length / 2);\n for (var i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n };\n\n AttrList.prototype.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {\n var intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n };\n\n AttrList.prototype.decimalFloatingPoint = function decimalFloatingPoint(attrName) {\n return parseFloat(this[attrName]);\n };\n\n AttrList.prototype.enumeratedString = function enumeratedString(attrName) {\n return this[attrName];\n };\n\n AttrList.prototype.decimalResolution = function decimalResolution(attrName) {\n var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n };\n\n AttrList.parseAttrList = function parseAttrList(input) {\n var match = void 0,\n attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n var value = match[2],\n quote = '\"';\n\n if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {\n value = value.slice(1, -1);\n }\n\n attrs[match[1]] = value;\n }\n return attrs;\n };\n\n return AttrList;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AttrList);\n\n/***/ }),\n/* 26 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Fragment Loader\n*/\n\n\n\n\n\n\nvar FragmentLoader = function (_EventHandler) {\n _inherits(FragmentLoader, _EventHandler);\n\n function FragmentLoader(hls) {\n _classCallCheck(this, FragmentLoader);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADING));\n\n _this.loaders = {};\n return _this;\n }\n\n FragmentLoader.prototype.destroy = function destroy() {\n var loaders = this.loaders;\n for (var loaderName in loaders) {\n var loader = loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n\n _EventHandler.prototype.destroy.call(this);\n };\n\n FragmentLoader.prototype.onFragLoading = function onFragLoading(data) {\n var frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n var loader = loaders[type];\n if (loader) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].warn('abort previous fragment loader for type: ' + type);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n var loaderContext = void 0,\n loaderConfig = void 0,\n loaderCallbacks = void 0;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n var start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (!isNaN(start) && !isNaN(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\n loader.load(loaderContext, loaderConfig, loaderCallbacks);\n };\n\n FragmentLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {\n var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n\n var payload = response.data,\n frag = context.frag;\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });\n };\n\n FragmentLoader.prototype.loaderror = function loaderror(response, context) {\n var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n var loader = context.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR, details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });\n };\n\n FragmentLoader.prototype.loadtimeout = function loadtimeout(stats, context) {\n var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n var loader = context.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR, details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });\n };\n\n // data will be used for progressive parsing\n\n\n FragmentLoader.prototype.loadprogress = function loadprogress(stats, context, data) {\n var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n // jshint ignore:line\n var frag = context.frag;\n frag.loaded = stats.loaded;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });\n };\n\n return FragmentLoader;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (FragmentLoader);\n\n/***/ }),\n/* 27 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Decrypt key Loader\n*/\n\n\n\n\n\n\nvar KeyLoader = function (_EventHandler) {\n _inherits(KeyLoader, _EventHandler);\n\n function KeyLoader(hls) {\n _classCallCheck(this, KeyLoader);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].KEY_LOADING));\n\n _this.loaders = {};\n _this.decryptkey = null;\n _this.decrypturl = null;\n return _this;\n }\n\n KeyLoader.prototype.destroy = function destroy() {\n for (var loaderName in this.loaders) {\n var loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n KeyLoader.prototype.onKeyLoading = function onKeyLoading(data) {\n var 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 var config = this.hls.config;\n\n if (loader) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* 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 var loaderContext = void 0,\n loaderConfig = void 0,\n loaderCallbacks = void 0;\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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].KEY_LOADED, { frag: frag });\n }\n };\n\n KeyLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {\n var 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].KEY_LOADED, { frag: frag });\n };\n\n KeyLoader.prototype.loaderror = function loaderror(response, context) {\n var frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR, details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });\n };\n\n KeyLoader.prototype.loadtimeout = function loadtimeout(stats, context) {\n var frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR, details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_TIMEOUT, fatal: false, frag: frag });\n };\n\n return KeyLoader;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (KeyLoader);\n\n/***/ }),\n/* 28 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export State */\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__ = __webpack_require__(7);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__ = __webpack_require__(17);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__demux_demuxer__ = __webpack_require__(29);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__fragment_tracker__ = __webpack_require__(16);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__loader_fragment__ = __webpack_require__(13);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__loader_playlist_loader__ = __webpack_require__(11);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__level_helper__ = __webpack_require__(22);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_time_ranges__ = __webpack_require__(44);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_discontinuities__ = __webpack_require__(45);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__task_loop__ = __webpack_require__(46);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__fragment_finders__ = __webpack_require__(47);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Stream Controller\n*/\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar 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\nvar StreamController = function (_TaskLoop) {\n _inherits(StreamController, _TaskLoop);\n\n function StreamController(hls, fragmentTracker) {\n _classCallCheck(this, StreamController);\n\n var _this = _possibleConstructorReturn(this, _TaskLoop.call(this, hls, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MEDIA_ATTACHED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MANIFEST_LOADING, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MANIFEST_PARSED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].LEVEL_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].KEY_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSING_DATA, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHING, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_CREATED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_APPENDED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_FLUSHED));\n\n _this.fragmentTracker = fragmentTracker;\n _this.config = hls.config;\n _this.audioCodecSwap = false;\n _this._state = State.STOPPED;\n _this.stallReported = false;\n return _this;\n }\n\n StreamController.prototype.onHandlerDestroying = function onHandlerDestroying() {\n this.stopLoad();\n _TaskLoop.prototype.onHandlerDestroying.call(this);\n };\n\n StreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n _TaskLoop.prototype.onHandlerDestroyed.call(this);\n };\n\n StreamController.prototype.startLoad = function startLoad(startPosition) {\n if (this.levels) {\n var lastCurrentTime = this.lastCurrentTime,\n hls = this.hls;\n this.stopLoad();\n this.setInterval(100);\n this.level = -1;\n this.fragLoadError = 0;\n if (!this.startFragRequested) {\n // determine load level\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 StreamController.prototype.stopLoad = function stopLoad() {\n var frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.clearInterval();\n this.state = State.STOPPED;\n this.forceStartLoad = false;\n };\n\n StreamController.prototype.doTick = function doTick() {\n switch (this.state) {\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\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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\n\n StreamController.prototype._doTickIdle = function _doTickIdle() {\n var hls = this.hls,\n config = hls.config,\n media = this.media;\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 || !media && (this.startFragRequested || !config.startFragPrefetch)) {\n return;\n }\n\n // if we have not yet loaded any fragment, start loading from start position\n var pos = void 0;\n if (this.loadedmetadata) {\n pos = media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n\n // determine next load level\n var level = hls.nextLoadLevel,\n levelInfo = this.levels[level];\n\n if (!levelInfo) {\n return;\n }\n\n var levelBitrate = levelInfo.bitrate,\n maxBufLen = void 0;\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\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 var bufferInfo = __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 var 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 (!levelDetails || 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 var 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 var 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 var data = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 StreamController.prototype._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {\n var 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 var start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n bufferEnd = bufferInfo.end,\n frag = void 0;\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 var initialLiveManifestSize = this.config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 } 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\n if (frag) {\n if (frag.encrypted) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);\n this._loadKey(frag);\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));\n this._loadFragment(frag);\n }\n }\n };\n\n StreamController.prototype._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {\n var config = this.hls.config,\n media = this.media;\n\n var frag = void 0;\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 var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n\n if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {\n var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n __WEBPACK_IMPORTED_MODULE_10__utils_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));\n bufferEnd = liveSyncPosition;\n if (media && media.readyState && media.duration > liveSyncPosition) {\n media.currentTime = liveSyncPosition;\n }\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 if (!levelDetails.programDateTime) {\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n var targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n var fragNext = fragments[targetSN - levelDetails.startSN];\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 = __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__[\"a\" /* default */].search(fragments, function (frag) {\n return fragPrevious.cc - frag.cc;\n });\n if (frag) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist, switching playlist, load frag with same CC: ' + frag.sn);\n }\n }\n } else {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n frag = Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"b\" /* findFragmentByPDT */])(fragments, fragPrevious.endPdt + 1);\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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);\n }\n }\n return frag;\n };\n\n StreamController.prototype._findFragment = function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {\n var config = this.hls.config;\n var fragBySN = function fragBySN() {\n return Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"c\" /* findFragmentBySN */])(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n };\n var frag = void 0;\n var foundFrag = void 0;\n\n if (bufferEnd < end) {\n if (!levelDetails.programDateTime) {\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"c\" /* findFragmentBySN */])(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n } else {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"b\" /* findFragmentByPDT */])(fragments, Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"a\" /* calculateNextPDT */])(start, bufferEnd, levelDetails));\n if (!foundFrag || Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"d\" /* fragmentWithinToleranceTest */])(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) {\n // Fall back to SN order if finding by PDT returns a frag which won't fit within the stream\n // fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN');\n foundFrag = fragBySN();\n }\n }\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen - 1];\n }\n if (foundFrag) {\n frag = foundFrag;\n var curSNIdx = frag.sn - levelDetails.startSN;\n var sameLevel = fragPrevious && frag.level === fragPrevious.level;\n var prevFrag = fragments[curSNIdx - 1];\n var 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 var 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 __WEBPACK_IMPORTED_MODULE_10__utils_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');\n } else {\n frag = nextFrag;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');\n frag.dropped = 0;\n if (prevFrag) {\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 StreamController.prototype._loadKey = function _loadKey(frag) {\n this.state = State.KEY_LOADING;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].KEY_LOADING, { frag: frag });\n };\n\n StreamController.prototype._loadFragment = function _loadFragment(frag) {\n // Check if fragment is not loaded\n var fragState = this.fragmentTracker.getState(frag);\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\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === __WEBPACK_IMPORTED_MODULE_4__fragment_tracker__[\"a\" /* FragmentState */].NOT_LOADED || fragState === __WEBPACK_IMPORTED_MODULE_4__fragment_tracker__[\"a\" /* FragmentState */].PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 __WEBPACK_IMPORTED_MODULE_2__demux_demuxer__[\"a\" /* default */](this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === __WEBPACK_IMPORTED_MODULE_4__fragment_tracker__[\"a\" /* FragmentState */].APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\n }\n };\n\n StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) {\n return this.fragmentTracker.getBufferedFrag(position, __WEBPACK_IMPORTED_MODULE_6__loader_playlist_loader__[\"a\" /* default */].LevelType.MAIN);\n };\n\n StreamController.prototype.followingBufferedFrag = function 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 StreamController.prototype._checkFragmentChanged = function _checkFragmentChanged() {\n var fragPlayingCurrent = void 0,\n currentTime = void 0,\n 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 > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\n\n if (__WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getBufferedFrag(currentTime);\n } else if (__WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_CHANGED, { frag: fragPlaying });\n var fragPlayingLevel = fragPlaying.level;\n if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].LEVEL_SWITCHED, { level: fragPlayingLevel });\n }\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\n\n StreamController.prototype.immediateLevelSwitch = function immediateLevelSwitch() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('immediateLevelSwitch');\n if (!this.immediateSwitch) {\n this.immediateSwitch = true;\n var media = this.media,\n previouslyPaused = void 0;\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\n this.fragCurrent = null;\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\n\n StreamController.prototype.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() {\n var media = this.media;\n if (media && media.buffered.length) {\n this.immediateSwitch = false;\n if (__WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* 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 /**\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\n\n StreamController.prototype.nextLevelSwitch = function nextLevelSwitch() {\n var media = this.media;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media && media.readyState) {\n var fetchdelay = void 0,\n fragPlayingCurrent = void 0,\n nextBufferedFrag = void 0;\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,\n nextLevel = this.levels[nextLevelId],\n 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\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 StreamController.prototype.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {\n this.state = State.BUFFER_FLUSHING;\n var 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\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_FLUSHING, flushScope);\n };\n\n StreamController.prototype.onMediaAttached = function 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 var config = this.config;\n if (this.levels && config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n };\n\n StreamController.prototype.onMediaDetaching = function onMediaDetaching() {\n var media = this.media;\n if (media && media.ended) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment backtracked flag\n var levels = this.levels;\n if (levels) {\n levels.forEach(function (level) {\n if (level.details) {\n level.details.fragments.forEach(function (fragment) {\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 StreamController.prototype.onMediaSeeking = function onMediaSeeking() {\n var media = this.media,\n currentTime = media ? media.currentTime : undefined,\n config = this.config;\n if (!isNaN(currentTime)) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('media seeking to ' + currentTime.toFixed(3));\n }\n\n var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n var bufferInfo = __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(mediaBuffer, currentTime, this.config.maxBufferHole);\n if (this.state === State.FRAG_LOADING) {\n var 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 var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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\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\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\n // tick to speed up processing\n this.tick();\n };\n\n StreamController.prototype.onMediaSeeked = function onMediaSeeked() {\n var media = this.media,\n currentTime = media ? media.currentTime : undefined;\n if (!isNaN(currentTime)) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('media seeked to ' + currentTime.toFixed(3));\n }\n\n // tick to speed up FRAGMENT_PLAYING triggering\n this.tick();\n };\n\n StreamController.prototype.onMediaEnded = function onMediaEnded() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('media ended');\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n };\n\n StreamController.prototype.onManifestLoading = function onManifestLoading() {\n // reset buffer on manifest loading\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('trigger BUFFER_RESET');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n };\n\n StreamController.prototype.onManifestParsed = function onManifestParsed(data) {\n var aac = false,\n heaac = false,\n codec = void 0;\n data.levels.forEach(function (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\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = aac && heaac;\n if (this.audioCodecSwitch) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');\n }\n\n this.levels = data.levels;\n this.startFragRequested = false;\n var config = this.config;\n if (config.autoStartLoad || this.forceStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n };\n\n StreamController.prototype.onLevelLoaded = function onLevelLoaded(data) {\n var newDetails = data.details;\n var newLevelId = data.level;\n var lastLevel = this.levels[this.levelLastLoaded];\n var curLevel = this.levels[newLevelId];\n var duration = newDetails.totalduration;\n var sliding = 0;\n\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_7__level_helper__[\"b\" /* mergeDetails */](curDetails, newDetails);\n sliding = newDetails.fragments[0].start;\n this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown && !isNaN(sliding)) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist sliding:' + sliding.toFixed(3));\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist - outdated PTS, unknown sliding');\n Object(__WEBPACK_IMPORTED_MODULE_11__utils_discontinuities__[\"a\" /* alignDiscontinuities */])(this.fragPrevious, lastLevel, newDetails);\n }\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist - first load, unknown sliding');\n newDetails.PTSKnown = false;\n Object(__WEBPACK_IMPORTED_MODULE_11__utils_discontinuities__[\"a\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 var startTimeOffset = newDetails.startTimeOffset;\n if (!isNaN(startTimeOffset)) {\n if (startTimeOffset < 0) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');\n startTimeOffset = sliding + duration + startTimeOffset;\n }\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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\n // trigger handler right now\n this.tick();\n };\n\n StreamController.prototype.onKeyLoaded = function onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n };\n\n StreamController.prototype.onFragLoaded = function onFragLoaded(data) {\n var fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {\n var stats = data.stats;\n var currentLevel = this.levels[fragCurrent.level];\n var details = currentLevel.details;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 = window.performance.now();\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 = window.performance.now();\n details.initSegment.data = data.payload;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 var duration = details.totalduration,\n level = fragCurrent.level,\n sn = fragCurrent.sn,\n audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('swapping playlist audio codec');\n if (audioCodec === undefined) {\n audioCodec = this.lastAudioCodec;\n }\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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc);\n var demuxer = this.demuxer;\n if (!demuxer) {\n demuxer = this.demuxer = new __WEBPACK_IMPORTED_MODULE_2__demux_demuxer__[\"a\" /* default */](this.hls, 'main');\n }\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 var media = this.media;\n var mediaSeeking = media && media.seeking;\n var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);\n var 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 StreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) {\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n\n if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {\n var tracks = data.tracks,\n trackName = void 0,\n track = void 0;\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\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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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') {\n // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });\n }\n }\n // trigger handler right now\n this.tick();\n }\n };\n\n StreamController.prototype.onFragParsingData = function onFragParsingData(data) {\n var _this2 = this;\n\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n 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\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 if (data.hasAudio === true) {\n frag.addElementaryStream(__WEBPACK_IMPORTED_MODULE_5__loader_fragment__[\"a\" /* default */].ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(__WEBPACK_IMPORTED_MODULE_5__loader_fragment__[\"a\" /* default */].ElementaryStreamTypes.VIDEO);\n }\n\n __WEBPACK_IMPORTED_MODULE_10__utils_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));\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 var levelDetails = level.details;\n if (levelDetails && frag.sn === levelDetails.startSN) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('missing video frame(s) on first frag, appending with gap', frag.sn);\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('missing video frame(s), backtracking fragment', frag.sn);\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 this.fragmentTracker.removeFragment(frag);\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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('Already backtracked on this fragment, appending with the gap', frag.sn);\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 = __WEBPACK_IMPORTED_MODULE_7__level_helper__[\"c\" /* updateFragPTSDTS */](level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),\n hls = this.hls;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });\n // has remuxer dropped video frames located before first keyframe ?\n [data.data1, data.data2].forEach(function (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 && _this2.state === State.PARSING) {\n _this2.appended = true;\n // arm pending Buffering flag before appending a segment\n _this2.pendingBuffering = true;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 StreamController.prototype.onFragParsed = function onFragParsed(data) {\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {\n this.stats.tparsed = window.performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n };\n\n StreamController.prototype.onAudioTrackSwitching = function 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('switching on main audio, use media.buffered to schedule main fragment loading');\n this.mediaBuffer = this.media;\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 var hls = this.hls;\n // switching to main audio, flush all audio and trigger track switched\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId });\n this.altAudio = false;\n }\n };\n\n StreamController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) {\n var trackId = data.id,\n altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 StreamController.prototype.onBufferCreated = function onBufferCreated(data) {\n var tracks = data.tracks,\n mediaTrack = void 0,\n name = void 0,\n alternate = false;\n for (var type in tracks) {\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 StreamController.prototype.onBufferAppended = function onBufferAppended(data) {\n if (data.parent === 'main') {\n var 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 StreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n var frag = this.fragCurrent;\n if (frag) {\n var media = this.mediaBuffer ? this.mediaBuffer : this.media;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('main buffered : ' + __WEBPACK_IMPORTED_MODULE_8__utils_time_ranges__[\"a\" /* default */].toString(media.buffered));\n this.fragPrevious = frag;\n var stats = this.stats;\n stats.tbuffered = window.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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });\n this.state = State.IDLE;\n }\n this.tick();\n }\n };\n\n StreamController.prototype.onError = function onError(data) {\n var 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\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n var mediaBuffered = !!this.media && __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].isBuffered(this.media, this.media.currentTime) && __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].isBuffered(this.media, this.media.currentTime + 0.5);\n\n switch (data.details) {\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* 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 var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('mediaController: frag loading failed, retry in ' + delay + ' ms');\n this.retryDate = window.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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 StreamController.prototype._reduceMaxBufferLength = function _reduceMaxBufferLength(minLength) {\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's');\n return true;\n }\n return false;\n };\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n\n\n StreamController.prototype._checkBuffer = function _checkBuffer() {\n var config = this.config,\n media = this.media;\n\n var stallDebounceInterval = 1000;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n var currentTime = media.currentTime;\n var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n var buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n var expectedPlaying = !(media.paused && media.readyState > 1 || // not playing when media is paused and sufficiently buffered\n media.ended || // not playing when media is ended\n media.buffered.length === 0); // not playing if nothing buffered\n var tnow = window.performance.now();\n\n if (currentTime !== this.lastCurrentTime) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(tnow - this.stalled) + 'ms');\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n } else if (expectedPlaying) {\n // The playhead isn't moving but it should be\n // Allow some slack time to for small stalls to resolve themselves\n var stalledDuration = tnow - this.stalled;\n var bufferInfo = __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(media, currentTime, config.maxBufferHole);\n if (!this.stalled) {\n this.stalled = tnow;\n return;\n } else if (stalledDuration >= stallDebounceInterval) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n this._tryFixBufferStall(bufferInfo, stalledDuration);\n }\n }\n };\n\n StreamController.prototype.onFragLoadEmergencyAborted = function 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 StreamController.prototype.onBufferFlushed = function 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 var media = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n this.fragmentTracker.detectEvictedFragments(__WEBPACK_IMPORTED_MODULE_5__loader_fragment__[\"a\" /* default */].ElementaryStreamTypes.VIDEO, media.buffered);\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 StreamController.prototype.swapAudioCodec = function swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n };\n\n StreamController.prototype.computeLivePosition = function computeLivePosition(sliding, levelDetails) {\n var 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 /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDuration - The amount of time Hls.js has been stalling for.\n * @private\n */\n\n\n StreamController.prototype._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDuration) {\n var config = this.config,\n media = this.media;\n\n var currentTime = media.currentTime;\n var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end\n\n var partial = this.fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n this._trySkipBufferHole(partial);\n }\n\n if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n };\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n\n\n StreamController.prototype._reportStall = function _reportStall(bufferLen) {\n var hls = this.hls,\n media = this.media,\n stallReported = this.stallReported;\n\n if (!stallReported) {\n // Report stalled error once\n this.stallReported = true;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('Playback stalling at @' + media.currentTime + ' due to low buffer');\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_9__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n };\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n\n\n StreamController.prototype._trySkipBufferHole = function _trySkipBufferHole(partial) {\n var hls = this.hls,\n media = this.media;\n\n var currentTime = media.currentTime;\n var lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (var i = 0; i < media.buffered.length; i++) {\n var startTime = media.buffered.start(i);\n if (currentTime >= lastEndTime && currentTime < startTime) {\n media.currentTime = Math.max(startTime, media.currentTime + 0.1);\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('skipping hole, adjusting currentTime from ' + currentTime + ' to ' + media.currentTime);\n this.stalled = null;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_9__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: 'fragment loaded with buffer holes, seeking from ' + currentTime + ' to ' + media.currentTime,\n frag: partial\n });\n return;\n }\n lastEndTime = media.buffered.end(i);\n }\n };\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n\n\n StreamController.prototype._tryNudgeBuffer = function _tryNudgeBuffer() {\n var config = this.config,\n hls = this.hls,\n media = this.media;\n\n var currentTime = media.currentTime;\n var nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n var targetTime = currentTime + nudgeRetry * config.nudgeOffset;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_9__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_9__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n };\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n\n\n StreamController.prototype._seekToStartPos = function _seekToStartPos() {\n var media = this.media;\n\n var currentTime = media.currentTime;\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 var startPosition = media.seeking ? currentTime : this.startPosition;\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition) {\n // if startPosition not buffered, let's seek to buffered.start(0)\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition + ' from current time ' + currentTime + ' ');\n media.currentTime = startPosition;\n }\n };\n\n _createClass(StreamController, [{\n key: 'state',\n set: function set(nextState) {\n if (this.state !== nextState) {\n var previousState = this.state;\n this._state = nextState;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('main stream:' + previousState + '->' + nextState);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });\n }\n },\n get: function get() {\n return this._state;\n }\n }, {\n key: 'currentLevel',\n get: function get() {\n var media = this.media;\n if (media) {\n var frag = this.getBufferedFrag(media.currentTime);\n if (frag) {\n return frag.level;\n }\n }\n return -1;\n }\n }, {\n key: 'nextBufferedFrag',\n get: function get() {\n var 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 key: 'nextLevel',\n get: function get() {\n var frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n } else {\n return -1;\n }\n }\n }, {\n key: 'liveSyncPosition',\n get: function get() {\n return this._liveSyncPosition;\n },\n set: function set(value) {\n this._liveSyncPosition = value;\n }\n }]);\n\n return StreamController;\n}(__WEBPACK_IMPORTED_MODULE_12__task_loop__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (StreamController);\n\n/***/ }),\n/* 29 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_events__ = __webpack_require__(8);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_events__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_webworkify_webpack__ = __webpack_require__(30);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_webworkify_webpack___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_webworkify_webpack__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__demux_demuxer_inline__ = __webpack_require__(18);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_mediasource_helper__ = __webpack_require__(10);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_get_self_scope__ = __webpack_require__(5);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\n\n\n\n\n\n\n// see https://stackoverflow.com/a/11237259/589493\nvar global = Object(__WEBPACK_IMPORTED_MODULE_7__utils_get_self_scope__[\"a\" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread\nvar MediaSource = Object(__WEBPACK_IMPORTED_MODULE_6__utils_mediasource_helper__[\"a\" /* getMediaSource */])();\n\nvar Demuxer = function () {\n function Demuxer(hls, id) {\n _classCallCheck(this, Demuxer);\n\n this.hls = hls;\n this.id = id;\n // observer setup\n var observer = this.observer = new __WEBPACK_IMPORTED_MODULE_0_events___default.a();\n var config = hls.config;\n observer.trigger = function trigger(event) {\n for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n data[_key - 1] = arguments[_key];\n }\n\n observer.emit.apply(observer, [event, event].concat(data));\n };\n\n observer.off = function off(event) {\n for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n data[_key2 - 1] = arguments[_key2];\n }\n\n observer.removeListener.apply(observer, [event].concat(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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_DECRYPTED, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_DATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSED, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_METADATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].INIT_PTS_FOUND, forwardMessage);\n\n var 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 var vendor = navigator.vendor;\n if (config.enableWorker && typeof Worker !== 'undefined') {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('demuxing in webworker');\n var w = void 0;\n try {\n w = this.w = __WEBPACK_IMPORTED_MODULE_1_webworkify_webpack___default()(/*require.resolve*/(43));\n this.onwmsg = this.onWorkerMessage.bind(this);\n w.addEventListener('message', this.onwmsg);\n w.onerror = function (event) {\n hls.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_5__errors__[\"b\" /* ErrorTypes */].OTHER_ERROR, details: __WEBPACK_IMPORTED_MODULE_5__errors__[\"a\" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });\n };\n w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });\n } catch (err) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 global.URL.revokeObjectURL(w.objectURL);\n }\n this.demuxer = new __WEBPACK_IMPORTED_MODULE_3__demux_demuxer_inline__[\"a\" /* default */](observer, typeSupported, config, vendor);\n this.w = undefined;\n }\n } else {\n this.demuxer = new __WEBPACK_IMPORTED_MODULE_3__demux_demuxer_inline__[\"a\" /* default */](observer, typeSupported, config, vendor);\n }\n }\n\n Demuxer.prototype.destroy = function destroy() {\n var w = this.w;\n if (w) {\n w.removeEventListener('message', this.onwmsg);\n w.terminate();\n this.w = null;\n } else {\n var demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n this.demuxer = null;\n }\n }\n var observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n this.observer = null;\n }\n };\n\n Demuxer.prototype.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {\n var w = this.w;\n var timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start;\n var decryptdata = frag.decryptdata;\n var lastFrag = this.frag;\n var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);\n var trackSwitch = !(lastFrag && frag.level === lastFrag.level);\n var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;\n var contiguous = !trackSwitch && nextSN;\n if (discontinuity) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log(this.id + ':discontinuity detected');\n }\n\n if (trackSwitch) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log(this.id + ':switch detected');\n }\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: 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] : []);\n } else {\n var 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 Demuxer.prototype.onWorkerMessage = function onWorkerMessage(ev) {\n var data = ev.data,\n hls = this.hls;\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 global.URL.revokeObjectURL(this.w.objectURL);\n break;\n // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects\n case __WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].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\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 return Demuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (Demuxer);\n\n/***/ }),\n/* 30 */\n/***/ (function(module, exports, __webpack_require__) {\n\nfunction 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\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\((\\/\\\\*.*?\\\\*\\/)?\\s?.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_require__.m\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\\n'\n })\n\n src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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/* 31 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar AESCrypto = function () {\n function AESCrypto(subtle, iv) {\n _classCallCheck(this, AESCrypto);\n\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n AESCrypto.prototype.decrypt = function decrypt(data, key) {\n return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);\n };\n\n return AESCrypto;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AESCrypto);\n\n/***/ }),\n/* 32 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar FastAESKey = function () {\n function FastAESKey(subtle, key) {\n _classCallCheck(this, FastAESKey);\n\n this.subtle = subtle;\n this.key = key;\n }\n\n FastAESKey.prototype.expandKey = function expandKey() {\n return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);\n };\n\n return FastAESKey;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (FastAESKey);\n\n/***/ }),\n/* 33 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export removePadding */\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n// PKCS7\nfunction removePadding(buffer) {\n var outputBytes = buffer.byteLength;\n var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return buffer.slice(0, outputBytes - paddingBytes);\n } else {\n return buffer;\n }\n}\n\nvar AESDecryptor = function () {\n function AESDecryptor() {\n _classCallCheck(this, AESDecryptor);\n\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\n\n AESDecryptor.prototype.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {\n var view = new DataView(arrayBuffer);\n var newArray = new Uint32Array(4);\n for (var i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n\n return newArray;\n };\n\n AESDecryptor.prototype.initTable = function initTable() {\n var sBox = this.sBox;\n var invSBox = this.invSBox;\n var subMix = this.subMix;\n var subMix0 = subMix[0];\n var subMix1 = subMix[1];\n var subMix2 = subMix[2];\n var subMix3 = subMix[3];\n var invSubMix = this.invSubMix;\n var invSubMix0 = invSubMix[0];\n var invSubMix1 = invSubMix[1];\n var invSubMix2 = invSubMix[2];\n var invSubMix3 = invSubMix[3];\n\n var d = new Uint32Array(256);\n var x = 0;\n var xi = 0;\n var 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 var 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 var x2 = d[x];\n var x4 = d[x2];\n var x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n var 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 AESDecryptor.prototype.expandKey = function expandKey(keyBuffer) {\n // convert keyBuffer to Uint32Array\n var key = this.uint8ArrayToUint32Array_(keyBuffer);\n var sameKey = true;\n var 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 var 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 var ksRows = this.ksRows = (keySize + 6 + 1) * 4;\n var ksRow = void 0;\n var invKsRow = void 0;\n\n var keySchedule = this.keySchedule = new Uint32Array(ksRows);\n var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);\n var sbox = this.sBox;\n var rcon = this.rcon;\n\n var invSubMix = this.invSubMix;\n var invSubMix0 = invSubMix[0];\n var invSubMix1 = invSubMix[1];\n var invSubMix2 = invSubMix[2];\n var invSubMix3 = invSubMix[3];\n\n var prev = void 0;\n var t = void 0;\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\n\n AESDecryptor.prototype.networkToHostOrderSwap = function networkToHostOrderSwap(word) {\n return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;\n };\n\n AESDecryptor.prototype.decrypt = function decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {\n var nRounds = this.keySize + 6;\n var invKeySchedule = this.invKeySchedule;\n var invSBOX = this.invSBox;\n\n var invSubMix = this.invSubMix;\n var invSubMix0 = invSubMix[0];\n var invSubMix1 = invSubMix[1];\n var invSubMix2 = invSubMix[2];\n var invSubMix3 = invSubMix[3];\n\n var initVector = this.uint8ArrayToUint32Array_(aesIV);\n var initVector0 = initVector[0];\n var initVector1 = initVector[1];\n var initVector2 = initVector[2];\n var initVector3 = initVector[3];\n\n var inputInt32 = new Int32Array(inputArrayBuffer);\n var outputInt32 = new Int32Array(inputInt32.length);\n\n var t0 = void 0,\n t1 = void 0,\n t2 = void 0,\n t3 = void 0;\n var s0 = void 0,\n s1 = void 0,\n s2 = void 0,\n s3 = void 0;\n var inputWords0 = void 0,\n inputWords1 = void 0,\n inputWords2 = void 0,\n inputWords3 = void 0;\n\n var ksRow = void 0,\n i = void 0;\n var 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 removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;\n };\n\n AESDecryptor.prototype.destroy = function 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 return AESDecryptor;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AESDecryptor);\n\n/***/ }),\n/* 34 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__adts__ = __webpack_require__(20);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__demux_id3__ = __webpack_require__(9);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * AAC demuxer\n */\n\n\n\n\nvar AACDemuxer = function () {\n function AACDemuxer(observer, remuxer, config) {\n _classCallCheck(this, AACDemuxer);\n\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n AACDemuxer.prototype.resetInitSegment = function 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 AACDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};\n\n AACDemuxer.probe = function probe(data) {\n if (!data) {\n return false;\n }\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 var id3Data = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].getID3Data(data, 0) || [];\n var offset = id3Data.length;\n\n for (var length = data.length; offset < length; offset++) {\n if (__WEBPACK_IMPORTED_MODULE_0__adts__[\"e\" /* probe */](data, offset)) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* 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\n\n AACDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {\n var track = this._audioTrack;\n var id3Data = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].getID3Data(data, 0) || [];\n var timestamp = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].getTimeStamp(id3Data);\n var pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n var frameIndex = 0;\n var stamp = pts;\n var length = data.length;\n var offset = id3Data.length;\n\n var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];\n\n while (offset < length - 1) {\n if (__WEBPACK_IMPORTED_MODULE_0__adts__[\"d\" /* isHeader */](data, offset) && offset + 5 < length) {\n __WEBPACK_IMPORTED_MODULE_0__adts__[\"c\" /* initTrackConfig */](track, this.observer, data, offset, track.manifestCodec);\n var frame = __WEBPACK_IMPORTED_MODULE_0__adts__[\"a\" /* appendFrame */](track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('Unable to parse AAC frame');\n break;\n }\n } else if (__WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].isHeader(data, offset)) {\n id3Data = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].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, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);\n };\n\n AACDemuxer.prototype.destroy = function destroy() {};\n\n return AACDemuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AACDemuxer);\n\n/***/ }),\n/* 35 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__adts__ = __webpack_require__(20);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__mpegaudio__ = __webpack_require__(21);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__exp_golomb__ = __webpack_require__(36);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__sample_aes__ = __webpack_require__(37);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__errors__ = __webpack_require__(2);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n*/\n\n\n\n\n\n\n// import Hex from '../utils/hex';\n\n\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.\nvar RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nvar TSDemuxer = function () {\n function TSDemuxer(observer, remuxer, config, typeSupported) {\n _classCallCheck(this, TSDemuxer);\n\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.remuxer = remuxer;\n this.sampleAes = null;\n }\n\n TSDemuxer.prototype.setDecryptData = function setDecryptData(decryptdata) {\n if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {\n this.sampleAes = new __WEBPACK_IMPORTED_MODULE_4__sample_aes__[\"a\" /* default */](this.observer, this.config, decryptdata, this.discardEPB);\n } else {\n this.sampleAes = null;\n }\n };\n\n TSDemuxer.probe = function probe(data) {\n var syncOffset = TSDemuxer._syncOffset(data);\n if (syncOffset < 0) {\n return false;\n } else {\n if (syncOffset) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?');\n }\n\n return true;\n }\n };\n\n TSDemuxer._syncOffset = function _syncOffset(data) {\n // scan 1000 first bytes\n var scanwindow = Math.min(1000, data.length - 3 * 188);\n var 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\n\n TSDemuxer.createTrack = function createTrack(type, duration) {\n return {\n container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type: 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\n\n TSDemuxer.prototype.resetInitSegment = function 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\n\n TSDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};\n\n // feed incoming data to the front of the parsing pipeline\n\n\n TSDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {\n var start = void 0,\n len = data.length,\n stt = void 0,\n pid = void 0,\n atf = void 0,\n offset = void 0,\n pes = void 0,\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 var 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)) && pes.pts !== undefined) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n parseID3PES(pes);\n }\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\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n var 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\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\n if (unknownPIDs && !pmtParsed) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_6__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* 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)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n\n audioTrack.pesData = null;\n } else {\n if (audioData && audioData.size) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].log('last AAC PES packet truncated,might overlap between fragments');\n }\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)) && pes.pts !== undefined) {\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 TSDemuxer.prototype.decryptAndRemux = function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (audioTrack.samples && audioTrack.isAAC) {\n var 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 TSDemuxer.prototype.decryptAndRemuxAvc = function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (videoTrack.samples) {\n var 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 TSDemuxer.prototype.destroy = function destroy() {\n this._initPTS = this._initDTS = undefined;\n this._duration = 0;\n };\n\n TSDemuxer.prototype._parsePAT = function _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 TSDemuxer.prototype._parsePMT = function _parsePMT(data, offset, mpegSupported, isSampleAes) {\n var sectionLength = void 0,\n tableEnd = void 0,\n programInfoLength = void 0,\n pid = void 0,\n 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:\n // SAMPLE-AES AAC\n if (!isSampleAes) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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\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\n break;\n\n case 0xdb:\n // SAMPLE-AES AVC\n if (!isSampleAes) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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\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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].warn('HEVC stream type found, not supported for now');\n break;\n\n default:\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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 TSDemuxer.prototype._parsePES = function _parsePES(stream) {\n var i = 0,\n frag = void 0,\n pesFlags = void 0,\n pesPrefix = void 0,\n pesLen = void 0,\n pesHdrLen = void 0,\n pesData = void 0,\n pesPts = void 0,\n pesDts = void 0,\n payloadStartOffset = void 0,\n 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 var 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\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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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 (var j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n var 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 TSDemuxer.prototype.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n var samples = avcTrack.samples;\n var 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 || avcSample.key === true || 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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n };\n\n TSDemuxer.prototype._parseAVCPES = function _parseAVCPES(pes, last) {\n var _this = this;\n\n // logger.log('parse new PES');\n var track = this._avcTrack,\n units = this._parseAVCNALu(pes.data),\n debug = false,\n expGolombDecoder = void 0,\n avcSample = this.avcSample,\n push = void 0,\n spsfound = false,\n i = void 0,\n pushAccesUnit = this.pushAccesUnit.bind(this),\n createAVCSample = function createAVCSample(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(function (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\n if (debug) {\n avcSample.debug += 'NDR ';\n }\n\n avcSample.frame = true;\n var 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 var sliceType = new __WEBPACK_IMPORTED_MODULE_3__exp_golomb__[\"a\" /* default */](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\n if (debug) {\n avcSample.debug += 'IDR ';\n }\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\n expGolombDecoder = new __WEBPACK_IMPORTED_MODULE_3__exp_golomb__[\"a\" /* default */](_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 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 } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\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\n if (!track.sps) {\n expGolombDecoder = new __WEBPACK_IMPORTED_MODULE_3__exp_golomb__[\"a\" /* default */](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\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\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\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\n break;\n }\n if (avcSample && push) {\n var _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 TSDemuxer.prototype._insertSampleInOrder = function _insertSampleInOrder(arr, data) {\n var len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\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 } else {\n arr.push(data);\n }\n };\n\n TSDemuxer.prototype._getLastNalUnit = function _getLastNalUnit() {\n var avcSample = this.avcSample,\n lastUnit = void 0;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n var track = this._avcTrack,\n samples = track.samples;\n avcSample = samples[samples.length - 1];\n }\n if (avcSample) {\n var units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n };\n\n TSDemuxer.prototype._parseAVCNALu = function _parseAVCNALu(array) {\n var i = 0,\n len = array.byteLength,\n value = void 0,\n overflow = void 0,\n track = this._avcTrack,\n state = track.naluState || 0,\n lastState = state;\n var units = [],\n unit = void 0,\n unitType = void 0,\n lastUnitStart = -1,\n lastUnitType = void 0;\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 var 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 var 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 var _lastUnit = this._getLastNalUnit();\n if (_lastUnit) {\n var _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\n\n TSDemuxer.prototype.discardEPB = function discardEPB(data) {\n var length = data.byteLength,\n EPBPositions = [],\n i = 1,\n newLength = void 0,\n newData = void 0;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 && data[i + 1] === 0 && 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 TSDemuxer.prototype._parseAACPES = function _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 = void 0,\n frameIndex = void 0,\n offset = void 0,\n stamp = void 0,\n len = void 0;\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 (__WEBPACK_IMPORTED_MODULE_0__adts__[\"d\" /* 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 = void 0,\n fatal = void 0;\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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].warn('parsing error:' + reason);\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_6__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: fatal, reason: reason });\n if (fatal) {\n return;\n }\n }\n\n __WEBPACK_IMPORTED_MODULE_0__adts__[\"c\" /* initTrackConfig */](track, this.observer, data, offset, this.audioCodec);\n frameIndex = 0;\n frameDuration = __WEBPACK_IMPORTED_MODULE_0__adts__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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 (__WEBPACK_IMPORTED_MODULE_0__adts__[\"d\" /* isHeader */](data, offset) && offset + 5 < len) {\n var frame = __WEBPACK_IMPORTED_MODULE_0__adts__[\"a\" /* 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\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n };\n\n TSDemuxer.prototype._parseMPEGPES = function _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 (__WEBPACK_IMPORTED_MODULE_1__mpegaudio__[\"a\" /* default */].isHeader(data, offset)) {\n var frame = __WEBPACK_IMPORTED_MODULE_1__mpegaudio__[\"a\" /* default */].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 TSDemuxer.prototype._parseID3PES = function _parseID3PES(pes) {\n this._id3Track.samples.push(pes);\n };\n\n return TSDemuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (TSDemuxer);\n\n/***/ }),\n/* 36 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n*/\n\n\n\nvar ExpGolomb = function () {\n function ExpGolomb(data) {\n _classCallCheck(this, ExpGolomb);\n\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\n\n ExpGolomb.prototype.loadWord = function loadWord() {\n var 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\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\n\n ExpGolomb.prototype.skipBits = function skipBits(count) {\n var skipBytes = void 0; // :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\n\n ExpGolomb.prototype.readBits = function readBits(size) {\n var bits = Math.min(this.bitsAvailable, size),\n // :uint\n valu = this.word >>> 32 - bits; // :uint\n if (size > 32) {\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].error('Cannot read more than 32 bits at a time');\n }\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\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\n\n ExpGolomb.prototype.skipLZ = function skipLZ() {\n var leadingZeroCount = void 0; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {\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\n\n ExpGolomb.prototype.skipUEG = function skipUEG() {\n this.skipBits(1 + this.skipLZ());\n };\n\n // ():void\n\n\n ExpGolomb.prototype.skipEG = function skipEG() {\n this.skipBits(1 + this.skipLZ());\n };\n\n // ():uint\n\n\n ExpGolomb.prototype.readUEG = function readUEG() {\n var clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n };\n\n // ():int\n\n\n ExpGolomb.prototype.readEG = function 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\n\n ExpGolomb.prototype.readBoolean = function readBoolean() {\n return this.readBits(1) === 1;\n };\n\n // ():int\n\n\n ExpGolomb.prototype.readUByte = function readUByte() {\n return this.readBits(8);\n };\n\n // ():int\n\n\n ExpGolomb.prototype.readUShort = function readUShort() {\n return this.readBits(16);\n };\n // ():int\n\n\n ExpGolomb.prototype.readUInt = function 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\n\n ExpGolomb.prototype.skipScalingList = function skipScalingList(count) {\n var lastScale = 8,\n nextScale = 8,\n j = void 0,\n deltaScale = void 0;\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\n\n ExpGolomb.prototype.readSPS = function readSPS() {\n var frameCropLeftOffset = 0,\n frameCropRightOffset = 0,\n frameCropTopOffset = 0,\n frameCropBottomOffset = 0,\n profileIdc = void 0,\n profileCompat = void 0,\n levelIdc = void 0,\n numRefFramesInPicOrderCntCycle = void 0,\n picWidthInMbsMinus1 = void 0,\n picHeightInMapUnitsMinus1 = void 0,\n frameMbsOnlyFlag = void 0,\n scalingListCount = void 0,\n i = void 0,\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 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {\n var chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // 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()) {\n // seq_scaling_matrix_present_flag\n scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) {\n // 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();\n } // offset_for_ref_frame[ i ]\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);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) {\n // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n var pixelRatio = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n var aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1:\n pixelRatio = [1, 1];break;\n case 2:\n pixelRatio = [12, 11];break;\n case 3:\n pixelRatio = [10, 11];break;\n case 4:\n pixelRatio = [16, 11];break;\n case 5:\n pixelRatio = [40, 33];break;\n case 6:\n pixelRatio = [24, 11];break;\n case 7:\n pixelRatio = [20, 11];break;\n case 8:\n pixelRatio = [32, 11];break;\n case 9:\n pixelRatio = [80, 33];break;\n case 10:\n pixelRatio = [18, 11];break;\n case 11:\n pixelRatio = [15, 11];break;\n case 12:\n pixelRatio = [64, 33];break;\n case 13:\n pixelRatio = [160, 99];break;\n case 14:\n pixelRatio = [4, 3];break;\n case 15:\n pixelRatio = [3, 2];break;\n case 16:\n pixelRatio = [2, 1];break;\n case 255:\n {\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 ExpGolomb.prototype.readSliceType = function 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 return ExpGolomb;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (ExpGolomb);\n\n/***/ }),\n/* 37 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__crypt_decrypter__ = __webpack_require__(19);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * SAMPLE-AES decrypter\n*/\n\n\n\nvar SampleAesDecrypter = function () {\n function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {\n _classCallCheck(this, SampleAesDecrypter);\n\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new __WEBPACK_IMPORTED_MODULE_0__crypt_decrypter__[\"a\" /* default */](observer, config, { removePKCS7Padding: false });\n }\n\n SampleAesDecrypter.prototype.decryptBuffer = function 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\n\n SampleAesDecrypter.prototype.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {\n var curUnit = samples[sampleIndex].unit;\n var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);\n var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);\n\n var 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 SampleAesDecrypter.prototype.decryptAacSamples = function 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 var 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\n\n SampleAesDecrypter.prototype.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {\n var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n var encryptedData = new Int8Array(encryptedDataLen);\n var outputPos = 0;\n for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {\n encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return encryptedData;\n };\n\n SampleAesDecrypter.prototype.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n var inputPos = 0;\n for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {\n decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return decodedData;\n };\n\n SampleAesDecrypter.prototype.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {\n var decodedData = this.discardEPB(curUnit.data);\n var encryptedData = this.getAvcEncryptedData(decodedData);\n var 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 SampleAesDecrypter.prototype.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {\n for (;; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n var curUnits = samples[sampleIndex].units;\n for (;; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n var curUnit = curUnits[unitIndex];\n if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {\n continue;\n }\n\n var 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 return SampleAesDecrypter;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (SampleAesDecrypter);\n\n/***/ }),\n/* 38 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demux_id3__ = __webpack_require__(9);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__mpegaudio__ = __webpack_require__(21);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * MP3 demuxer\n */\n\n\n\n\nvar MP3Demuxer = function () {\n function MP3Demuxer(observer, remuxer, config) {\n _classCallCheck(this, MP3Demuxer);\n\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n MP3Demuxer.prototype.resetInitSegment = function 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 MP3Demuxer.prototype.resetTimeStamp = function resetTimeStamp() {};\n\n MP3Demuxer.probe = function probe(data) {\n // check if data contains ID3 timestamp and MPEG sync word\n var offset = void 0,\n length = void 0;\n var id3Data = __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].getID3Data(data, 0);\n if (id3Data && __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].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 (__WEBPACK_IMPORTED_MODULE_2__mpegaudio__[\"a\" /* default */].probe(data, offset)) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* 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\n\n MP3Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {\n var id3Data = __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].getID3Data(data, 0);\n var timestamp = __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].getTimeStamp(id3Data);\n var pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n var offset = id3Data.length;\n var length = data.length;\n var frameIndex = 0,\n stamp = 0;\n var track = this._audioTrack;\n\n var id3Samples = [{ pts: pts, dts: pts, data: id3Data }];\n\n while (offset < length) {\n if (__WEBPACK_IMPORTED_MODULE_2__mpegaudio__[\"a\" /* default */].isHeader(data, offset)) {\n var frame = __WEBPACK_IMPORTED_MODULE_2__mpegaudio__[\"a\" /* default */].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 (__WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].isHeader(data, offset)) {\n id3Data = __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].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, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);\n };\n\n MP3Demuxer.prototype.destroy = function destroy() {};\n\n return MP3Demuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (MP3Demuxer);\n\n/***/ }),\n/* 39 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__aac_helper__ = __webpack_require__(40);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__mp4_generator__ = __webpack_require__(41);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * fMP4 remuxer\n*/\n\n\n\n\n\n\n\n\n\n// 10 seconds\nvar MAX_SILENT_FRAME_DURATION = 10 * 1000;\n\nvar MP4Remuxer = function () {\n function MP4Remuxer(observer, config, typeSupported, vendor) {\n _classCallCheck(this, MP4Remuxer);\n\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n var userAgent = navigator.userAgent;\n this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');\n this.ISGenerated = false;\n }\n\n MP4Remuxer.prototype.destroy = function destroy() {};\n\n MP4Remuxer.prototype.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {\n this._initPTS = this._initDTS = defaultTimeStamp;\n };\n\n MP4Remuxer.prototype.resetInitSegment = function resetInitSegment() {\n this.ISGenerated = false;\n };\n\n MP4Remuxer.prototype.remux = function 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 var nbAudioSamples = audioTrack.samples.length;\n var nbVideoSamples = videoTrack.samples.length;\n var audioTimeOffset = timeOffset;\n var 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 var 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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('regenerate InitSegment as audio detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n var audioTrackLength = void 0;\n if (audioData) {\n audioTrackLength = audioData.endPTS - audioData.startPTS;\n }\n\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.timescale) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSED);\n };\n\n MP4Remuxer.prototype.generateIS = function 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 = void 0,\n initDTS = void 0;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('audio sampling rate : ' + audioTrack.samplerate);\n if (!audioTrack.isAAC) {\n if (typeSupported.mpeg) {\n // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) {\n // 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() : __WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].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 var inputTimeScale = videoTrack.inputTimeScale;\n videoTrack.timescale = inputTimeScale;\n tracks.video = {\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: __WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].INIT_PTS_FOUND, { initPTS: initPTS });\n }\n }\n\n if (Object.keys(tracks).length) {\n observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });\n }\n };\n\n MP4Remuxer.prototype.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {\n var offset = 8,\n timeScale = track.timescale,\n mp4SampleDuration = void 0,\n mdat = void 0,\n moof = void 0,\n firstPTS = void 0,\n firstDTS = void 0,\n nextDTS = void 0,\n lastPTS = void 0,\n lastDTS = void 0,\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 var nextAvcDts = this.nextAvcDts;\n\n var isSafari = this.isSafari;\n\n if (nbSamples === 0) {\n return;\n }\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 && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initDTS) < timeScale / 5);\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 var deltadts = a.dts - b.dts;\n var deltapts = a.pts - b.pts;\n return deltadts || deltapts || a.id - b.id;\n });\n\n // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)\n var PTSDTSshift = inputSamples.reduce(function (prev, curr) {\n return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);\n }, 0);\n if (PTSDTSshift < 0) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');\n for (var 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 var 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 var 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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('AVC:' + delta + ' ms hole between fragments detected,filling it');\n } else if (delta < -1) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('AVC:' + -delta + ' ms overlapping between fragments detected');\n }\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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 var nbNalu = 0,\n naluLen = 0;\n for (var _i = 0; _i < nbSamples; _i++) {\n // compute total/avc sample length and nb of NAL units\n var _sample = inputSamples[_i],\n units = _sample.units,\n nbUnits = units.length,\n sampleLen = 0;\n for (var j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\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 var mdatSize = naluLen + 4 * nbNalu + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MUX_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating video mdat ' + mdatSize });\n return;\n }\n var view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(__WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].types.mdat, 4);\n\n for (var _i2 = 0; _i2 < nbSamples; _i2++) {\n var avcSample = inputSamples[_i2],\n avcSampleUnits = avcSample.units,\n mp4SampleLength = 0,\n compositionTimeOffset = void 0;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {\n var 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 (_i2 < nbSamples - 1) {\n mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;\n } else {\n var config = this.config,\n lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].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 maxBufferHole.\n // 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 var maxBufferHole = config.maxBufferHole,\n gapTolerance = Math.floor(maxBufferHole * 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 should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\n\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 // 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 var 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 var 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 = __WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].moof(track.sequenceNumber++, firstDTS, track);\n track.samples = [];\n\n var 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 hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: dropped\n };\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_DATA, data);\n return data;\n };\n\n MP4Remuxer.prototype.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {\n var 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 = void 0,\n mp4Sample = void 0,\n fillFrame = void 0,\n mdat = void 0,\n moof = void 0,\n firstPTS = void 0,\n lastPTS = void 0,\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 && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initDTS) < 20 * inputSampleDuration);\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter(function (sample) {\n return sample.pts >= 0;\n });\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = timeOffset * inputTimeScale;\n }\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 if (track.isAAC) {\n var maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (var 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],\n delta;\n var pts = sample.pts;\n delta = pts - nextPts;\n\n var 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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 } // eslint-disable-line brace-style\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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 var newStamp = Math.max(nextPts, 0);\n fillFrame = __WEBPACK_IMPORTED_MODULE_0__aac_helper__[\"a\" /* default */].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {\n var audioSample = inputSamples[_j2];\n var unit = audioSample.unit;\n var _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 var _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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log(_delta + ' ms hole between AAC samples detected,filling it');\n if (numMissingFrames > 0) {\n fillFrame = __WEBPACK_IMPORTED_MODULE_0__aac_helper__[\"a\" /* default */].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n fillFrame = unit.subarray();\n }\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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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\n firstPTS = _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 var 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MUX_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating audio mdat ' + mdatSize });\n return;\n }\n if (!rawMPEG) {\n var view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(__WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n for (var _i3 = 0; _i3 < numMissingFrames; _i3++) {\n fillFrame = __WEBPACK_IMPORTED_MODULE_0__aac_helper__[\"a\" /* default */].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 var 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 = __WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].moof(track.sequenceNumber++, firstPTS / scaleFactor, track);\n }\n\n track.samples = [];\n var start = firstPTS / inputTimeScale;\n var end = nextAudioPts / inputTimeScale;\n var audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type: 'audio',\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples\n };\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_DATA, audioData);\n return audioData;\n }\n return null;\n };\n\n MP4Remuxer.prototype.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {\n var inputTimeScale = track.inputTimeScale,\n mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,\n scaleFactor = inputTimeScale / mp4timeScale,\n nextAudioPts = this.nextAudioPts,\n\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\n // one sample's duration value\n sampleDuration = 1024,\n frameDuration = scaleFactor * sampleDuration,\n\n\n // samples count of this segment's duration\n nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),\n\n\n // silent frame\n silentFrame = __WEBPACK_IMPORTED_MODULE_0__aac_helper__[\"a\" /* default */].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');\n return;\n }\n\n var 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 MP4Remuxer.prototype.remuxID3 = function remuxID3(track, timeOffset) {\n var length = track.samples.length,\n sample = void 0;\n var inputTimeScale = track.inputTimeScale;\n var initPTS = this._initPTS;\n var 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_METADATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n timeOffset = timeOffset;\n };\n\n MP4Remuxer.prototype.remuxText = function remuxText(track, timeOffset) {\n track.samples.sort(function (a, b) {\n return a.pts - b.pts;\n });\n\n var length = track.samples.length,\n sample = void 0;\n var inputTimeScale = track.inputTimeScale;\n var 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_USERDATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n timeOffset = timeOffset;\n };\n\n MP4Remuxer.prototype._PTSNormalize = function _PTSNormalize(value, reference) {\n var offset = void 0;\n if (reference === undefined) {\n return value;\n }\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\n return value;\n };\n\n return MP4Remuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (MP4Remuxer);\n\n/***/ }),\n/* 40 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * AAC helper\n */\n\nvar AAC = function () {\n function AAC() {\n _classCallCheck(this, AAC);\n }\n\n AAC.getSilentFrame = function 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\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 return AAC;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AAC);\n\n/***/ }),\n/* 41 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Generate MP4 Box\n*/\n\nvar UINT32_MAX = Math.pow(2, 32) - 1;\n\nvar MP4 = function () {\n function MP4() {\n _classCallCheck(this, MP4);\n }\n\n MP4.init = function 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 = void 0;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];\n }\n }\n\n var videoHdlr = new Uint8Array([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, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n ]);\n\n var audioHdlr = new Uint8Array([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, 0x64, 0x48, 0x61, 0x6e, 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([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([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([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([0x00, // version\n 0x00, 0x00, 0x01, // flags\n 0x00, 0x00, // graphicsmode\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor\n ]);\n MP4.SMHD = new Uint8Array([0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, // balance\n 0x00, 0x00 // reserved\n ]);\n\n MP4.STSD = new Uint8Array([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 MP4.box = function box(type) {\n var payload = Array.prototype.slice.call(arguments, 1),\n size = 8,\n i = payload.length,\n len = i,\n result = void 0;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\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 MP4.hdlr = function hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n };\n\n MP4.mdat = function mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n };\n\n MP4.mdhd = function mdhd(timescale, duration) {\n duration *= timescale;\n var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.mdhd, new Uint8Array([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, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale\n 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)\n 0x00, 0x00]));\n };\n\n MP4.mdia = function 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 MP4.mfhd = function mfhd(sequenceNumber) {\n return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags\n sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number\n ]));\n };\n\n MP4.minf = function 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 MP4.moof = function 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\n\n MP4.moov = function moov(tracks) {\n var 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 MP4.mvex = function mvex(tracks) {\n var i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));\n };\n\n MP4.mvhd = function mvhd(timescale, duration) {\n duration *= timescale;\n var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n var bytes = new Uint8Array([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, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale\n 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\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, 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\n 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\n 0xff, 0xff, 0xff, 0xff // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n };\n\n MP4.sdtp = function sdtp(track) {\n var samples = track.samples || [],\n bytes = new Uint8Array(4 + samples.length),\n flags = void 0,\n i = void 0;\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 | flags.isDependedOn << 2 | flags.hasRedundancy;\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n };\n\n MP4.stbl = function 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 MP4.avc1 = function avc1(track) {\n var sps = [],\n pps = [],\n i = void 0,\n data = void 0,\n len = void 0;\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\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\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\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n var avcc = MP4.box(MP4.types.avcC, new Uint8Array([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([track.pps.length // numOfPictureParameterSets\n ]).concat(pps))),\n // \"PPS\"\n width = track.width,\n height = track.height,\n hSpacing = track.pixelRatio[0],\n vSpacing = track.pixelRatio[1];\n\n return MP4.box(MP4.types.avc1, new Uint8Array([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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined\n width >> 8 & 0xFF, width & 0xff, // width\n height >> 8 & 0xFF, 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, 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js\n 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\n 0x00, 0x18, // depth = 24\n 0x11, 0x11]), // pre_defined = -1\n avcc, MP4.box(MP4.types.btrt, new Uint8Array([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([hSpacing >> 24, // hSpacing\n hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing\n vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));\n };\n\n MP4.esds = function esds(track) {\n var configlen = track.config.length;\n return new Uint8Array([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 MP4.mp4a = function mp4a(track) {\n var samplerate = track.samplerate;\n return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00, 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, samplerate & 0xff, //\n 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));\n };\n\n MP4.mp3 = function mp3(track) {\n var samplerate = track.samplerate;\n return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00, 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, samplerate & 0xff, //\n 0x00, 0x00]));\n };\n\n MP4.stsd = function 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\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 MP4.tkhd = function 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([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, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID\n 0x00, 0x00, 0x00, 0x00, // reserved\n 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\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, 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\n width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width\n height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height\n ]));\n };\n\n MP4.traf = function 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, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF]) // track_ID\n ), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 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\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\n\n MP4.trak = function trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n };\n\n MP4.trex = function trex(track) {\n var id = track.id;\n return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, 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 MP4.trun = function trun(track, offset) {\n var samples = track.samples || [],\n len = samples.length,\n arraylen = 12 + 16 * len,\n array = new Uint8Array(arraylen),\n i = void 0,\n sample = void 0,\n duration = void 0,\n size = void 0,\n flags = void 0,\n cts = void 0;\n offset += 8 + arraylen;\n array.set([0x00, // version 0\n 0x00, 0x0f, 0x01, // flags\n len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count\n offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, 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([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration\n size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size\n 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\n cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset\n ], 12 + 16 * i);\n }\n return MP4.box(MP4.types.trun, array);\n };\n\n MP4.initSegment = function initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n var movie = MP4.moov(tracks),\n result = void 0;\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 return MP4;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (MP4);\n\n/***/ }),\n/* 42 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * passthrough remuxer\n*/\n\n\nvar PassThroughRemuxer = function () {\n function PassThroughRemuxer(observer) {\n _classCallCheck(this, PassThroughRemuxer);\n\n this.observer = observer;\n }\n\n PassThroughRemuxer.prototype.destroy = function destroy() {};\n\n PassThroughRemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};\n\n PassThroughRemuxer.prototype.resetInitSegment = function resetInitSegment() {};\n\n PassThroughRemuxer.prototype.remux = function 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\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\n nb: 1,\n dropped: 0\n });\n // notify end of parsing\n observer.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_PARSED);\n };\n\n return PassThroughRemuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (PassThroughRemuxer);\n\n/***/ }),\n/* 43 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__ = __webpack_require__(18);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events__ = __webpack_require__(8);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_events__);\n/* demuxer web worker.\n * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.\n * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.\n */\n\n\n\n\n\n\nvar DemuxerWorker = function DemuxerWorker(self) {\n // observer setup\n var observer = new __WEBPACK_IMPORTED_MODULE_3_events___default.a();\n observer.trigger = function trigger(event) {\n for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n data[_key - 1] = arguments[_key];\n }\n\n observer.emit.apply(observer, [event, event].concat(data));\n };\n\n observer.off = function off(event) {\n for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n data[_key2 - 1] = arguments[_key2];\n }\n\n observer.removeListener.apply(observer, [event].concat(data));\n };\n\n var forwardMessage = function forwardMessage(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 var config = JSON.parse(data.config);\n self.demuxer = new __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__[\"a\" /* default */](observer, data.typeSupported, config, data.vendor);\n try {\n Object(__WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"a\" /* 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(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_DECRYPTED, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSED, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_METADATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].INIT_PTS_FOUND, forwardMessage);\n\n // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_DATA, function (ev, data) {\n var transferable = [];\n var 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\n/* harmony default export */ __webpack_exports__[\"default\"] = (DemuxerWorker);\n\n/***/ }),\n/* 44 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/**\n * TimeRanges to string helper\n */\n\nvar TimeRanges = {\n toString: function toString(r) {\n var log = '',\n 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\n return log;\n }\n};\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (TimeRanges);\n\n/***/ }),\n/* 45 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export findFirstFragWithCC */\n/* unused harmony export findFragWithCC */\n/* unused harmony export shouldAlignOnDiscontinuities */\n/* unused harmony export findDiscontinuousReferenceFrag */\n/* unused harmony export adjustPts */\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = alignDiscontinuities;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__binary_search__ = __webpack_require__(7);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_logger__ = __webpack_require__(0);\n\n\n\nfunction findFirstFragWithCC(fragments, cc) {\n var firstFrag = null;\n\n for (var i = 0; i < fragments.length; i += 1) {\n var currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nfunction findFragWithCC(fragments, CC) {\n return __WEBPACK_IMPORTED_MODULE_0__binary_search__[\"a\" /* default */].search(fragments, function (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\nfunction shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {\n var 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\nfunction findDiscontinuousReferenceFrag(prevDetails, curDetails) {\n var prevFrags = prevDetails.fragments;\n var curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('No fragments to align');\n return;\n }\n\n var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nfunction adjustPts(sliding, details) {\n details.fragments.forEach(function (frag) {\n if (frag) {\n var 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\nfunction alignDiscontinuities(lastFrag, lastLevel, details) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);\n if (referenceFrag) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* 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 && lastLevel.details.fragments && lastLevel.details.fragments.length) {\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 var lastPDT = lastLevel.details.programDateTime;\n var newPDT = details.programDateTime;\n // date diff is in ms. frag.start is in seconds\n var sliding = (newPDT - lastPDT) / 1000 + lastLevel.details.fragments[0].start;\n if (!isNaN(sliding)) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3));\n adjustPts(sliding, details);\n }\n }\n}\n\n/***/ }),\n/* 46 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__event_handler__ = __webpack_require__(3);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n\n\n/**\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\n\nvar TaskLoop = function (_EventHandler) {\n _inherits(TaskLoop, _EventHandler);\n\n function TaskLoop(hls) {\n _classCallCheck(this, TaskLoop);\n\n for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n events[_key - 1] = arguments[_key];\n }\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call.apply(_EventHandler, [this, hls].concat(events)));\n\n _this._tickInterval = null;\n _this._tickTimer = null;\n _this._tickCallCount = 0;\n _this._boundTick = _this.tick.bind(_this);\n return _this;\n }\n\n /**\n * @override\n */\n\n\n TaskLoop.prototype.onHandlerDestroying = function onHandlerDestroying() {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n };\n\n /**\n * @returns {boolean}\n */\n\n\n TaskLoop.prototype.hasInterval = function hasInterval() {\n return !!this._tickInterval;\n };\n\n /**\n * @returns {boolean}\n */\n\n\n TaskLoop.prototype.hasNextTick = function hasNextTick() {\n return !!this._tickTimer;\n };\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n */\n\n\n TaskLoop.prototype.setInterval = function (_setInterval) {\n function setInterval(_x) {\n return _setInterval.apply(this, arguments);\n }\n\n setInterval.toString = function () {\n return _setInterval.toString();\n };\n\n return setInterval;\n }(function (millis) {\n if (!this._tickInterval) {\n this._tickInterval = setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n });\n\n /**\n * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n */\n\n\n TaskLoop.prototype.clearInterval = function (_clearInterval) {\n function clearInterval() {\n return _clearInterval.apply(this, arguments);\n }\n\n clearInterval.toString = function () {\n return _clearInterval.toString();\n };\n\n return clearInterval;\n }(function () {\n if (this._tickInterval) {\n clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n });\n\n /**\n * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n\n\n TaskLoop.prototype.clearNextTick = function clearNextTick() {\n if (this._tickTimer) {\n clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n };\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n\n\n TaskLoop.prototype.tick = function tick() {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.clearNextTick();\n this._tickTimer = setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n };\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n\n\n TaskLoop.prototype.doTick = function doTick() {};\n\n return TaskLoop;\n}(__WEBPACK_IMPORTED_MODULE_0__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (TaskLoop);\n\n/***/ }),\n/* 47 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = calculateNextPDT;\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = findFragmentByPDT;\n/* harmony export (immutable) */ __webpack_exports__[\"c\"] = findFragmentBySN;\n/* harmony export (immutable) */ __webpack_exports__[\"d\"] = fragmentWithinToleranceTest;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__ = __webpack_require__(7);\n\n\n/**\n * Calculates the PDT of the next load position.\n * bufferEnd in this function is usually the position of the playhead.\n * @param {number} [start = 0] - The PTS of the first fragment within the level\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level\n * @returns {number} nextPdt - The computed PDT\n */\nfunction calculateNextPDT() {\n var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var bufferEnd = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var levelDetails = arguments[2];\n\n var pdt = 0;\n if (levelDetails.programDateTime) {\n var parsedDateInt = Date.parse(levelDetails.programDateTime);\n if (!isNaN(parsedDateInt)) {\n pdt = bufferEnd * 1000 + parsedDateInt - 1000 * start;\n }\n }\n return pdt;\n}\n\n/**\n * Finds the first fragment whose endPDT value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @returns {*|null} fragment - The best matching fragment\n */\nfunction findFragmentByPDT(fragments) {\n var PDTValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n\n if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) {\n return null;\n }\n\n // if less than start\n var firstSegment = fragments[0];\n\n if (PDTValue < firstSegment.pdt) {\n return null;\n }\n\n var lastSegment = fragments[fragments.length - 1];\n\n if (PDTValue >= lastSegment.endPdt) {\n return null;\n }\n\n for (var seg = 0; seg < fragments.length; ++seg) {\n var frag = fragments[seg];\n if (PDTValue < frag.endPdt) {\n return frag;\n }\n }\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} [end = 0] - The computed end time of the stream\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nfunction findFragmentBySN(fragPrevious, fragments) {\n var bufferEnd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n var maxFragLookUpTolerance = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;\n\n var foundFrag = void 0;\n var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__[\"a\" /* default */].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n }\n }\n return foundFrag;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nfunction fragmentWithinToleranceTest() {\n var bufferEnd = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var maxFragLookUpTolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var candidate = arguments[2];\n\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 var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n/***/ }),\n/* 48 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_codecs__ = __webpack_require__(15);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__level_helper__ = __webpack_require__(22);\nvar _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; };\n\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Level Controller\n*/\n\n\n\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\nvar LevelController = function (_EventHandler) {\n _inherits(LevelController, _EventHandler);\n\n function LevelController(hls) {\n _classCallCheck(this, LevelController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR));\n\n _this.canload = false;\n _this.currentLevelIndex = null;\n _this.manualLevelIndex = -1;\n _this.timer = null;\n return _this;\n }\n\n LevelController.prototype.onHandlerDestroying = function onHandlerDestroying() {\n this.clearTimer();\n this.manualLevelIndex = -1;\n };\n\n LevelController.prototype.clearTimer = function clearTimer() {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n };\n\n LevelController.prototype.startLoad = function startLoad() {\n var 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(function (level) {\n level.loadError = 0;\n var 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 !== null) {\n this.loadLevel();\n }\n };\n\n LevelController.prototype.stopLoad = function stopLoad() {\n this.canload = false;\n };\n\n LevelController.prototype.onManifestLoaded = function onManifestLoaded(data) {\n var levels = [];\n var bitrateStart = void 0;\n var levelSet = {};\n var levelFromSet = null;\n var videoCodecFound = false;\n var audioCodecFound = false;\n var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());\n var audioTracks = [];\n\n // regroup redundant levels together\n data.levels.forEach(function (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 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (level.attrs && level.attrs.AUDIO) {\n Object(__WEBPACK_IMPORTED_MODULE_5__level_helper__[\"a\" /* addGroupId */])(levelFromSet || level, 'audio', level.attrs.AUDIO);\n }\n\n if (level.attrs && level.attrs.SUBTITLES) {\n Object(__WEBPACK_IMPORTED_MODULE_5__level_helper__[\"a\" /* addGroupId */])(levelFromSet || level, 'text', level.attrs.SUBTITLES);\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\n levels = levels.filter(function (_ref) {\n var videoCodec = _ref.videoCodec;\n return !!videoCodec;\n });\n }\n\n // only keep levels with supported audio/video codecs\n levels = levels.filter(function (_ref2) {\n var audioCodec = _ref2.audioCodec,\n videoCodec = _ref2.videoCodec;\n\n return (!audioCodec || Object(__WEBPACK_IMPORTED_MODULE_4__utils_codecs__[\"a\" /* isCodecSupportedInMp4 */])(audioCodec)) && (!videoCodec || Object(__WEBPACK_IMPORTED_MODULE_4__utils_codecs__[\"a\" /* isCodecSupportedInMp4 */])(videoCodec));\n });\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(function (track) {\n return !track.audioCodec || Object(__WEBPACK_IMPORTED_MODULE_4__utils_codecs__[\"a\" /* isCodecSupportedInMp4 */])(track.audioCodec, 'audio');\n });\n }\n\n if (levels.length > 0) {\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 (var i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);\n break;\n }\n }\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_PARSED, {\n levels: levels,\n audioTracks: audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: audioTracks.length > 0 && videoCodecFound\n });\n } else {\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* 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 LevelController.prototype.setLevelInternal = function setLevelInternal(newLevel) {\n var levels = this._levels;\n var 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.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('switching to level ' + newLevel);\n this.currentLevelIndex = newLevel;\n var levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_SWITCHING, levelProperties);\n }\n var level = levels[newLevel];\n var levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n var urlId = level.urlId;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });\n }\n } else {\n // invalid level id given, trigger error\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].OTHER_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n };\n\n LevelController.prototype.onError = function onError(data) {\n if (data.fatal) {\n if (data.type === __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n var levelError = false,\n fragmentError = false;\n var levelIndex = void 0;\n\n // try to recover not fatal errors\n switch (data.details) {\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_TIMEOUT:\n levelIndex = data.frag.level;\n fragmentError = true;\n break;\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT:\n levelIndex = data.context.level;\n levelError = true;\n break;\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].REMUX_ALLOC_ERROR:\n levelIndex = data.level;\n levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n };\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n\n\n LevelController.prototype.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {\n var _this2 = this;\n\n var config = this.hls.config;\n var errorDetails = errorEvent.details;\n\n var level = this._levels[levelIndex];\n var redundantLevels = void 0,\n delay = void 0,\n nextLevel = void 0;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(function () {\n return _this2.loadLevel();\n }, delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount);\n } else {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('level controller, cannot recover from ' + errorDetails + ' error');\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('level controller, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant URL-id ' + level.urlId);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('level controller, ' + errorDetails + ': switch to ' + nextLevel);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('level controller, ' + errorDetails + ': reload a fragment');\n this.currentLevelIndex = null;\n }\n }\n }\n };\n\n // reset errors on the successful load of a fragment\n\n\n LevelController.prototype.onFragLoaded = function onFragLoaded(_ref3) {\n var frag = _ref3.frag;\n\n if (frag !== undefined && frag.type === 'main') {\n var 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 LevelController.prototype.onLevelLoaded = function onLevelLoaded(data) {\n var _this3 = this;\n\n var levelId = data.level;\n // only process level loaded events matching with expected level\n if (levelId !== this.currentLevelIndex) {\n return;\n }\n\n var 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) {\n curLevel.loadError = 0;\n this.levelRetryCount = 0;\n }\n var newDetails = data.details;\n // if current playlist is a live playlist, arm a timer to reload it\n if (newDetails.live) {\n var targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration);\n var reloadInterval = targetdurationMs,\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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 half of target duration\n reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval));\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('live playlist, reload in ' + Math.round(reloadInterval) + ' ms');\n this.timer = setTimeout(function () {\n return _this3.loadLevel();\n }, reloadInterval);\n } else {\n this.clearTimer();\n }\n };\n\n LevelController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) {\n var audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n var currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n var urlId = currentLevel.audioGroupIds.findIndex(function (groupId) {\n return groupId === audioGroupId;\n });\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n };\n\n LevelController.prototype.loadLevel = function loadLevel() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n var levelObject = this._levels[this.currentLevelIndex];\n\n if ((typeof levelObject === 'undefined' ? 'undefined' : _typeof(levelObject)) === 'object' && levelObject.url.length > 0) {\n var level = this.currentLevelIndex;\n var id = levelObject.urlId;\n var url = levelObject.url[id];\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('Attempt loading level index ' + level + ' with URL-id ' + id);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADING, { url: url, level: level, id: id });\n }\n }\n };\n\n _createClass(LevelController, [{\n key: 'levels',\n get: function get() {\n return this._levels;\n }\n }, {\n key: 'level',\n get: function get() {\n return this.currentLevelIndex;\n },\n set: function set(newLevel) {\n var levels = this._levels;\n if (levels) {\n newLevel = Math.min(newLevel, levels.length - 1);\n if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {\n this.setLevelInternal(newLevel);\n }\n }\n }\n }, {\n key: 'manualLevel',\n get: function get() {\n return this.manualLevelIndex;\n },\n set: function set(newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n }, {\n key: 'firstLevel',\n get: function get() {\n return this._firstLevel;\n },\n set: function set(newLevel) {\n this._firstLevel = newLevel;\n }\n }, {\n key: 'startLevel',\n get: function get() {\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 var 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 set: function set(newLevel) {\n this._startLevel = newLevel;\n }\n }, {\n key: 'nextLoadLevel',\n get: function get() {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n },\n set: function set(nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n }]);\n\n return LevelController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (LevelController);\n\n/***/ }),\n/* 49 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__demux_id3__ = __webpack_require__(9);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_texttrack_utils__ = __webpack_require__(50);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * id3 metadata track controller\n*/\n\n\n\n\n\n\nvar ID3TrackController = function (_EventHandler) {\n _inherits(ID3TrackController, _EventHandler);\n\n function ID3TrackController(hls) {\n _classCallCheck(this, ID3TrackController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_PARSING_METADATA));\n\n _this.id3Track = undefined;\n _this.media = undefined;\n return _this;\n }\n\n ID3TrackController.prototype.destroy = function destroy() {\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n // Add ID3 metatadata text track.\n\n\n ID3TrackController.prototype.onMediaAttached = function onMediaAttached(data) {\n this.media = data.media;\n if (!this.media) {}\n };\n\n ID3TrackController.prototype.onMediaDetaching = function onMediaDetaching() {\n Object(__WEBPACK_IMPORTED_MODULE_3__utils_texttrack_utils__[\"a\" /* clearCurrentCues */])(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n };\n\n ID3TrackController.prototype.getID3Track = function getID3Track(textTracks) {\n for (var i = 0; i < textTracks.length; i++) {\n var textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n Object(__WEBPACK_IMPORTED_MODULE_3__utils_texttrack_utils__[\"b\" /* sendAddTrackEvent */])(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n };\n\n ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) {\n var fragment = data.frag;\n var samples = data.samples;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.getID3Track(this.media.textTracks);\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 var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;\n\n for (var i = 0; i < samples.length; i++) {\n var frames = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].getID3Frames(samples[i].data);\n if (frames) {\n var startTime = samples[i].pts;\n var 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 (var j = 0; j < frames.length; j++) {\n var frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!__WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].isTimeStampFrame(frame)) {\n var cue = new Cue(startTime, endTime, '');\n cue.value = frame;\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n };\n\n return ID3TrackController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (ID3TrackController);\n\n/***/ }),\n/* 50 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = sendAddTrackEvent;\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = clearCurrentCues;\n\nfunction sendAddTrackEvent(track, videoEl) {\n var event = null;\n try {\n event = new window.Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n event.track = track;\n videoEl.dispatchEvent(event);\n}\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\n/***/ }),\n/* 51 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = isSupported;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_mediasource_helper__ = __webpack_require__(10);\n\n\nfunction isSupported() {\n var mediaSource = Object(__WEBPACK_IMPORTED_MODULE_0__utils_mediasource_helper__[\"a\" /* getMediaSource */])();\n var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;\n var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && 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 var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';\n return !!isTypeSupported && !!sourceBufferValidAPI;\n}\n\n/***/ }),\n/* 52 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return hlsDefaultConfig; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__controller_abr_controller__ = __webpack_require__(53);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__controller_buffer_controller__ = __webpack_require__(56);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__controller_cap_level_controller__ = __webpack_require__(57);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__controller_fps_controller__ = __webpack_require__(58);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_xhr_loader__ = __webpack_require__(59);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__controller_audio_track_controller__ = __webpack_require__(4);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__controller_audio_track_controller___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__controller_audio_track_controller__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__controller_audio_stream_controller__ = __webpack_require__(4);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__controller_audio_stream_controller___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_6__controller_audio_stream_controller__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_cues__ = __webpack_require__(4);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_cues___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_7__utils_cues__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__controller_timeline_controller__ = __webpack_require__(4);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__controller_timeline_controller___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8__controller_timeline_controller__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__controller_subtitle_track_controller__ = __webpack_require__(4);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__controller_subtitle_track_controller___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_9__controller_subtitle_track_controller__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__controller_subtitle_stream_controller__ = __webpack_require__(4);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__controller_subtitle_stream_controller___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_10__controller_subtitle_stream_controller__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__controller_eme_controller__ = __webpack_require__(4);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__controller_eme_controller___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_11__controller_eme_controller__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__utils_mediakeys_helper__ = __webpack_require__(60);\n/**\n * HLS config\n */\n\n\n\n\n\n\n// import FetchLoader from './utils/fetch-loader';\n\n\n\n\n\n\n\n\n\n\n\n\nvar 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\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 liveDurationInfinity: false, // used by buffer-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 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: __WEBPACK_IMPORTED_MODULE_4__utils_xhr_loader__[\"a\" /* default */],\n // loader: FetchLoader,\n fLoader: undefined, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\n // fetchSetup: undefined,\n abrController: __WEBPACK_IMPORTED_MODULE_0__controller_abr_controller__[\"a\" /* default */],\n bufferController: __WEBPACK_IMPORTED_MODULE_1__controller_buffer_controller__[\"a\" /* default */],\n capLevelController: __WEBPACK_IMPORTED_MODULE_2__controller_cap_level_controller__[\"a\" /* default */],\n fpsController: __WEBPACK_IMPORTED_MODULE_3__controller_fps_controller__[\"a\" /* default */],\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 emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n requestMediaKeySystemAccessFunc: __WEBPACK_IMPORTED_MODULE_12__utils_mediakeys_helper__[\"a\" /* requestMediaKeySystemAccess */] // used by eme-controller\n};\n\nif (false) {\n hlsDefaultConfig.subtitleStreamController = SubtitleStreamController;\n hlsDefaultConfig.subtitleTrackController = SubtitleTrackController;\n hlsDefaultConfig.timelineController = TimelineController;\n hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller\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 (false) {\n hlsDefaultConfig.audioStreamController = AudioStreamController;\n hlsDefaultConfig.audioTrackController = AudioTrackController;\n}\n\nif (false) {\n hlsDefaultConfig.emeController = EMEController;\n}\n\n/***/ }),\n/* 53 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_buffer_helper__ = __webpack_require__(17);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_ewma_bandwidth_estimator__ = __webpack_require__(54);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * simple ABR Controller\n * - compute next level based on last fragment bw heuristics\n * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling\n */\n\n\n\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\nvar AbrController = function (_EventHandler) {\n _inherits(AbrController, _EventHandler);\n\n function AbrController(hls) {\n _classCallCheck(this, AbrController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_BUFFERED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR));\n\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 return _this;\n }\n\n AbrController.prototype.destroy = function destroy() {\n this.clearTimer();\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n AbrController.prototype.onFragLoading = function onFragLoading(data) {\n var frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, 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 var hls = this.hls;\n var config = hls.config;\n var level = frag.level;\n var isLive = hls.levels[level].details.live;\n\n var ewmaFast = void 0,\n ewmaSlow = void 0;\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 __WEBPACK_IMPORTED_MODULE_5__utils_ewma_bandwidth_estimator__[\"a\" /* default */](hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);\n }\n }\n };\n\n AbrController.prototype._abandonRulesCheck = function _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 var hls = this.hls;\n var video = hls.media;\n var frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n var loader = frag.loader;\n var 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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('frag loader destroy or aborted, disarm abandonRules');\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n var 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 (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {\n var requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(video.playbackRate);\n // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate\n if (requestDelay > 500 * frag.duration / playbackRate) {\n var levels = hls.levels,\n loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),\n // 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 = video.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (__WEBPACK_IMPORTED_MODULE_2__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(video, 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 var fragLevelNextLoadedDelay = void 0,\n nextLoadLevel = void 0;\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 var 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 __WEBPACK_IMPORTED_MODULE_4__utils_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));\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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });\n }\n }\n }\n }\n };\n\n AbrController.prototype.onFragLoaded = function onFragLoaded(data) {\n var 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 var level = this.hls.levels[frag.level];\n var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;\n var 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 var stats = data.stats;\n stats.tparsed = stats.tbuffered = stats.tload;\n this.onFragBuffered(data);\n }\n }\n };\n\n AbrController.prototype.onFragBuffered = function onFragBuffered(data) {\n var stats = data.stats;\n var 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.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 var fragLoadingProcessingMs = stats.tparsed - stats.trequest;\n __WEBPACK_IMPORTED_MODULE_4__utils_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)));\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 AbrController.prototype.onError = function onError(data) {\n // stop timer in case of frag loading error\n switch (data.details) {\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:\n this.clearTimer();\n break;\n default:\n break;\n }\n };\n\n AbrController.prototype.clearTimer = function clearTimer() {\n clearInterval(this.timer);\n this.timer = null;\n };\n\n // return next auto level\n\n\n AbrController.prototype._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {\n for (var i = maxAutoLevel; i >= minAutoLevel; i--) {\n var levelInfo = levels[i],\n levelDetails = levelInfo.details,\n avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,\n live = levelDetails ? levelDetails.live : false,\n adjustedbw = void 0;\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\n var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,\n fetchDuration = bitrate * avgDuration / adjustedbw;\n\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 _createClass(AbrController, [{\n key: 'nextAutoLevel',\n get: function get() {\n var forcedAutoLevel = this._nextAutoLevel;\n var 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\n // compute next level using ABR logic\n var 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\n return nextABRAutoLevel;\n },\n set: function set(nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n }, {\n key: '_nextABRAutoLevel',\n get: function get() {\n var hls = this.hls,\n maxAutoLevel = hls.maxAutoLevel,\n levels = hls.levels,\n config = hls.config,\n minAutoLevel = hls.minAutoLevel;\n var video = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = video ? video.currentTime : 0,\n\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0,\n avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,\n\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n bufferStarvationDelay = (__WEBPACK_IMPORTED_MODULE_2__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(video, 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 var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);\n if (bestLevel >= 0) {\n return bestLevel;\n } else {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 var 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 var 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 var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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\n return AbrController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AbrController);\n\n/***/ }),\n/* 54 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_ewma__ = __webpack_require__(55);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\n\n\nvar EwmaBandWidthEstimator = function () {\n function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {\n _classCallCheck(this, EwmaBandWidthEstimator);\n\n this.hls = hls;\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new __WEBPACK_IMPORTED_MODULE_0__utils_ewma__[\"a\" /* default */](slow);\n this.fast_ = new __WEBPACK_IMPORTED_MODULE_0__utils_ewma__[\"a\" /* default */](fast);\n }\n\n EwmaBandWidthEstimator.prototype.sample = function sample(durationMs, numBytes) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n var bandwidth = 8000 * numBytes / durationMs,\n\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 EwmaBandWidthEstimator.prototype.canEstimate = function canEstimate() {\n var fast = this.fast_;\n return fast && fast.getTotalWeight() >= this.minWeight_;\n };\n\n EwmaBandWidthEstimator.prototype.getEstimate = function 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 EwmaBandWidthEstimator.prototype.destroy = function destroy() {};\n\n return EwmaBandWidthEstimator;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (EwmaBandWidthEstimator);\n\n/***/ }),\n/* 55 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nvar EWMA = function () {\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n function EWMA(halfLife) {\n _classCallCheck(this, EWMA);\n\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 EWMA.prototype.sample = function 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 EWMA.prototype.getTotalWeight = function getTotalWeight() {\n return this.totalWeight_;\n };\n\n EWMA.prototype.getEstimate = function 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 return EWMA;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (EWMA);\n\n/***/ }),\n/* 56 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_mediasource_helper__ = __webpack_require__(10);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Buffer Controller\n*/\n\n\n\n\n\n\n\nvar MediaSource = Object(__WEBPACK_IMPORTED_MODULE_4__utils_mediasource_helper__[\"a\" /* getMediaSource */])();\n\nvar BufferController = function (_EventHandler) {\n _inherits(BufferController, _EventHandler);\n\n function BufferController(hls) {\n _classCallCheck(this, BufferController);\n\n // the value that we have set mediasource.duration to\n // (the actual duration may be tweaked slighly by the browser)\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_PARSED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_RESET, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_APPENDING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_CODECS, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_EOS, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_FLUSHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_PTS_UPDATED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_UPDATED));\n\n _this._msDuration = null;\n // the value that we want to set mediaSource.duration to\n _this._levelDuration = null;\n // current stream state: true - for live broadcast, false - for VoD content\n _this._live = null;\n // cache the self generated object url to detect hijack of video tag\n _this._objectUrl = 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 return _this;\n }\n\n BufferController.prototype.destroy = function destroy() {\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n BufferController.prototype.onLevelPtsUpdated = function onLevelPtsUpdated(data) {\n var type = data.type;\n var 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') {\n // Chrome audio mp3 track\n var audioBuffer = this.sourceBuffer.audio;\n var 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 var updating = audioBuffer.updating;\n\n try {\n audioBuffer.abort();\n } catch (err) {\n updating = true;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('can not abort audio buffer: ' + err);\n }\n\n if (!updating) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 BufferController.prototype.onManifestParsed = function onManifestParsed(data) {\n var audioExpected = data.audio,\n videoExpected = data.video || data.levels.length && data.altAudio,\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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log(sourceBufferNb + ' sourceBuffer(s) expected');\n }\n this.sourceBufferNb = sourceBufferNb;\n };\n\n BufferController.prototype.onMediaAttaching = function onMediaAttaching(data) {\n var 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 = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n };\n\n BufferController.prototype.onMediaDetaching = function onMediaDetaching() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 window.URL.revokeObjectURL(this._objectUrl);\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_DETACHED);\n };\n\n BufferController.prototype.onMediaSourceOpen = function onMediaSourceOpen() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('media source opened');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHED, { media: this.media });\n var 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 BufferController.prototype.checkPendingTracks = function checkPendingTracks() {\n // if any buffer codecs pending, check if we have enough to create sourceBuffers\n var 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 && (this.sourceBufferNb <= pendingTracksNb || 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 BufferController.prototype.onMediaSourceClose = function onMediaSourceClose() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('media source closed');\n };\n\n BufferController.prototype.onMediaSourceEnded = function onMediaSourceEnded() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('media source ended');\n };\n\n BufferController.prototype.onSBUpdateEnd = function onSBUpdateEnd() {\n // update timestampOffset\n if (this.audioTimestampOffset) {\n var audioBuffer = this.sourceBuffer.audio;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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\n this.appending = false;\n var parent = this.parent;\n // count nb of pending segments waiting for appending on this sourcebuffer\n var pending = this.segments.reduce(function (counter, segment) {\n return segment.parent === parent ? counter + 1 : counter;\n }, 0);\n\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n var timeRanges = {};\n var sourceBuffer = this.sourceBuffer;\n for (var streamType in sourceBuffer) {\n timeRanges[streamType] = sourceBuffer[streamType].buffered;\n }\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges });\n // don't append in flushing mode\n if (!this._needsFlush) {\n this.doAppending();\n }\n\n this.updateMediaElementDuration();\n };\n\n BufferController.prototype.onSBUpdateError = function onSBUpdateError(event) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* 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 BufferController.prototype.onBufferReset = function 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 this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n };\n\n BufferController.prototype.onBufferCodecs = function 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) {\n this.pendingTracks[trackName] = tracks[trackName];\n }var 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 BufferController.prototype.createSourceBuffers = function createSourceBuffers(tracks) {\n var sourceBuffer = this.sourceBuffer,\n mediaSource = this.mediaSource;\n\n for (var trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n var track = tracks[trackName];\n // use levelCodec as first priority\n var codec = track.levelCodec || track.codec;\n var mimeType = track.container + ';codecs=' + codec;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('creating sourceBuffer(' + mimeType + ')');\n try {\n var 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('error while trying to add sourceBuffer:' + err.message);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });\n }\n }\n }\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_CREATED, { tracks: tracks });\n };\n\n BufferController.prototype.onBufferAppending = function onBufferAppending(data) {\n if (!this._needsFlush) {\n if (!this.segments) {\n this.segments = [data];\n } else {\n this.segments.push(data);\n }\n\n this.doAppending();\n }\n };\n\n BufferController.prototype.onBufferAppendFail = function onBufferAppendFail(data) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false });\n };\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n\n\n BufferController.prototype.onBufferEos = function onBufferEos(data) {\n var sb = this.sourceBuffer;\n var dataType = data.type;\n for (var type in sb) {\n if (!dataType || type === dataType) {\n if (!sb[type].ended) {\n sb[type].ended = true;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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\n\n BufferController.prototype.checkEos = function checkEos() {\n var sb = this.sourceBuffer,\n mediaSource = this.mediaSource;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n for (var type in sb) {\n var sbobj = sb[type];\n if (!sbobj.ended) {\n return;\n }\n\n if (sbobj.updating) {\n this._needsEos = true;\n return;\n }\n }\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n };\n\n BufferController.prototype.onBufferFlushing = function onBufferFlushing(data) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n };\n\n BufferController.prototype.onLevelUpdated = function onLevelUpdated(_ref) {\n var details = _ref.details;\n\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\n };\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n\n\n BufferController.prototype.updateMediaElementDuration = function updateMediaElementDuration() {\n var config = this.hls.config;\n\n var duration = void 0;\n\n if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {\n return;\n }\n\n for (var type in this.sourceBuffer) {\n if (this.sourceBuffer[type].updating === true) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n\n duration = this.media.duration;\n // initialise to the value that the media source is reporting\n if (this._msDuration === null) {\n this._msDuration = this.mediaSource.duration;\n }\n\n if (this._live === true && config.liveDurationInfinity === true) {\n // Override duration to Infinity\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || duration === Infinity || isNaN(duration)) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('Updating Media Source duration to ' + this._levelDuration.toFixed(3));\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n };\n\n BufferController.prototype.doFlush = function 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('error while accessing sourceBuffer.buffered');\n }\n this.appended = appended;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_FLUSHED);\n }\n };\n\n BufferController.prototype.doAppending = function doAppending() {\n var hls = this.hls,\n sourceBuffer = this.sourceBuffer,\n segments = this.segments;\n if (Object.keys(sourceBuffer).length) {\n if (this.media.error) {\n this.segments = [];\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 var segment = segments.shift();\n try {\n var type = segment.type,\n 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('error while trying to append buffer:' + err.message);\n segments.unshift(segment);\n var event = { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* 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\n event.details = __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');\n segments = [];\n event.fatal = true;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, event);\n } else {\n event.fatal = false;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 = __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].BUFFER_FULL_ERROR;\n event.fatal = false;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, event);\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\n\n BufferController.prototype.flushBuffer = function flushBuffer(startOffset, endOffset, typeIn) {\n var sb = void 0,\n i = void 0,\n bufStart = void 0,\n bufEnd = void 0,\n flushStart = void 0,\n flushEnd = void 0,\n sourceBuffer = this.sourceBuffer;\n if (Object.keys(sourceBuffer).length) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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\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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('cannot flush, sb updating in progress');\n return false;\n }\n }\n } else {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('abort flushing too many retries');\n }\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('buffer flushed');\n }\n // everything flushed !\n return true;\n };\n\n return BufferController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (BufferController);\n\n/***/ }),\n/* 57 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * cap stream level to media size dimension controller\n*/\n\n\n\n\nvar CapLevelController = function (_EventHandler) {\n _inherits(CapLevelController, _EventHandler);\n\n function CapLevelController(hls) {\n _classCallCheck(this, CapLevelController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FPS_DROP_LEVEL_CAPPING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_PARSED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_CODECS));\n\n _this.autoLevelCapping = Number.POSITIVE_INFINITY;\n _this.firstLevel = null;\n _this.levels = [];\n _this.media = null;\n _this.restrictedLevels = [];\n _this.timer = null;\n return _this;\n }\n\n CapLevelController.prototype.destroy = function destroy() {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this._stopCapping();\n }\n };\n\n CapLevelController.prototype.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) {\n // 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 CapLevelController.prototype.onMediaAttaching = function onMediaAttaching(data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n };\n\n CapLevelController.prototype.onManifestParsed = function onManifestParsed(data) {\n var hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && (data.video || data.levels.length && data.altAudio)) {\n // Start capping immediately if the manifest has signaled video codecs\n this._startCapping();\n }\n };\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n\n\n CapLevelController.prototype.onBufferCodecs = function onBufferCodecs(data) {\n var hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this._startCapping();\n }\n };\n\n CapLevelController.prototype.onLevelsUpdated = function onLevelsUpdated(data) {\n this.levels = data.levels;\n };\n\n CapLevelController.prototype.detectPlayerSize = function detectPlayerSize() {\n if (this.media) {\n var levelsLength = this.levels ? this.levels.length : 0;\n if (levelsLength) {\n var 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\n\n CapLevelController.prototype.getMaxLevel = function getMaxLevel(capLevelIndex) {\n var _this2 = this;\n\n if (!this.levels) {\n return -1;\n }\n\n var validLevels = this.levels.filter(function (level, index) {\n return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;\n });\n\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n };\n\n CapLevelController.prototype._startCapping = function _startCapping() {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n };\n\n CapLevelController.prototype._stopCapping = function _stopCapping() {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\n };\n\n CapLevelController.isLevelAllowed = function isLevelAllowed(level) {\n var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n\n return restrictedLevels.indexOf(level) === -1;\n };\n\n CapLevelController.getMaxLevelByMediaSize = function 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 var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {\n if (!nextLevel) {\n return true;\n }\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 var maxLevelIndex = levels.length - 1;\n\n for (var i = 0; i < levels.length; i += 1) {\n var 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 _createClass(CapLevelController, [{\n key: 'mediaWidth',\n get: function get() {\n var width = void 0;\n var 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 key: 'mediaHeight',\n get: function get() {\n var height = void 0;\n var 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 key: 'contentScaleFactor',\n get: function get() {\n var pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch (e) {}\n return pixelRatio;\n }\n }]);\n\n return CapLevelController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (CapLevelController);\n\n/***/ }),\n/* 58 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * FPS Controller\n*/\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\nvar FPSController = function (_EventHandler) {\n _inherits(FPSController, _EventHandler);\n\n function FPSController(hls) {\n _classCallCheck(this, FPSController);\n\n return _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHING));\n }\n\n FPSController.prototype.destroy = function destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.isVideoPlaybackQualityAvailable = false;\n };\n\n FPSController.prototype.onMediaAttaching = function onMediaAttaching(data) {\n var config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n var video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n }\n };\n\n FPSController.prototype.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {\n var currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n var 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 var currentLevel = hls.currentLevel;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 FPSController.prototype.checkFPSInterval = function checkFPSInterval() {\n var video = this.video;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n var 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 return FPSController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (FPSController);\n\n/***/ }),\n/* 59 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * XHR based logger\n*/\n\n\n\nvar _window = window,\n performance = _window.performance,\n XMLHttpRequest = _window.XMLHttpRequest;\n\nvar XhrLoader = function () {\n function XhrLoader(config) {\n _classCallCheck(this, XhrLoader);\n\n if (config && config.xhrSetup) {\n this.xhrSetup = config.xhrSetup;\n }\n }\n\n XhrLoader.prototype.destroy = function destroy() {\n this.abort();\n this.loader = null;\n };\n\n XhrLoader.prototype.abort = function 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 XhrLoader.prototype.load = function 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 XhrLoader.prototype.loadInternal = function loadInternal() {\n var xhr = void 0,\n context = this.context;\n xhr = this.loader = new XMLHttpRequest();\n\n var stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n var 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\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 XhrLoader.prototype.readystatechange = function 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\n if (readyState === 4) {\n var 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 var data = void 0,\n len = void 0;\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 var 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].error(status + ' while loading ' + context.url);\n this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);\n } else {\n // retry\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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 XhrLoader.prototype.loadtimeout = function loadtimeout() {\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].warn('timeout while loading ' + this.context.url);\n this.callbacks.onTimeout(this.stats, this.context, null);\n };\n\n XhrLoader.prototype.loadprogress = function 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\n var 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 return XhrLoader;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (XhrLoader);\n\n/***/ }),\n/* 60 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return requestMediaKeySystemAccess; });\nvar requestMediaKeySystemAccess = function () {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {\n return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);\n } else {\n return null;\n }\n}();\n\n\n\n/***/ }),\n/* 61 */\n/***/ (function(module, exports) {\n\n/*! http://mths.be/endswith v0.2.0 by @mathias */\nif (!String.prototype.endsWith) {\n\t(function() {\n\t\t'use strict'; // needed to support `apply`/`call` with `undefined`/`null`\n\t\tvar defineProperty = (function() {\n\t\t\t// IE 8 only supports `Object.defineProperty` on DOM elements\n\t\t\ttry {\n\t\t\t\tvar object = {};\n\t\t\t\tvar $defineProperty = Object.defineProperty;\n\t\t\t\tvar result = $defineProperty(object, object, object) && $defineProperty;\n\t\t\t} catch(error) {}\n\t\t\treturn result;\n\t\t}());\n\t\tvar toString = {}.toString;\n\t\tvar endsWith = function(search) {\n\t\t\tif (this == null) {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar string = String(this);\n\t\t\tif (search && toString.call(search) == '[object RegExp]') {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar stringLength = string.length;\n\t\t\tvar searchString = String(search);\n\t\t\tvar searchLength = searchString.length;\n\t\t\tvar pos = stringLength;\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tvar position = arguments[1];\n\t\t\t\tif (position !== undefined) {\n\t\t\t\t\t// `ToInteger`\n\t\t\t\t\tpos = position ? Number(position) : 0;\n\t\t\t\t\tif (pos != pos) { // better `isNaN`\n\t\t\t\t\t\tpos = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar end = Math.min(Math.max(pos, 0), stringLength);\n\t\t\tvar start = end - searchLength;\n\t\t\tif (start < 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar index = -1;\n\t\t\twhile (++index < searchLength) {\n\t\t\t\tif (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\tif (defineProperty) {\n\t\t\tdefineProperty(String.prototype, 'endsWith', {\n\t\t\t\t'value': endsWith,\n\t\t\t\t'configurable': true,\n\t\t\t\t'writable': true\n\t\t\t});\n\t\t} else {\n\t\t\tString.prototype.endsWith = endsWith;\n\t\t}\n\t}());\n}\n\n\n/***/ })\n/******/ ])[\"default\"];\n});\n\n\n// WEBPACK FOOTER //\n// hls.light.min.js"," \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 = 23);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap e41fd7e1af865b2c2322","import { getSelfScope } from './get-self-scope';\n\nfunction noop () {}\n\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nlet exportedLogger = fakeLogger;\n\n// 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\nconst global = getSelfScope();\n\nfunction consolePrintFn (type) {\n const func = global.console[type];\n if (func) {\n return function (...args) {\n if (args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n\n func.apply(global.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 } else {\n exportedLogger = fakeLogger;\n }\n};\n\nexport var logger = exportedLogger;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/logger.js","/**\n * @readonly\n * @enum {string}\n */\nconst HlsEvents = {\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 }\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 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\nexport default HlsEvents;\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 // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR: 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nexport const ErrorDetails = {\n KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',\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 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*\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\nconst FORBIDDEN_EVENT_NAMES = new Set([\n 'hlsEventGeneric',\n 'hlsHandlerDestroying',\n 'hlsHandlerDestroyed'\n]);\n\nclass EventHandler {\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.onHandlerDestroying();\n this.unregisterListeners();\n this.onHandlerDestroyed();\n }\n\n onHandlerDestroying () {}\n onHandlerDestroyed () {}\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 (FORBIDDEN_EVENT_NAMES.has(event)) {\n throw new Error('Forbidden event-name: ' + event);\n }\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 let eventToFunction = function (event, data) {\n let 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\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n logger.error(`An internal error happened while handling event ${event}. Error message: \"${err.message}\". Here is a stacktrace:`, err);\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","// This file is inserted as a shim for modules which we do not want to include into the distro.\n// This replacement is done in the \"resolve\" section of the webpack config.\nmodule.exports = void 0;\n\n\n\n// WEBPACK FOOTER //\n// ./src/empty.js","export function getSelfScope () {\n // see https://stackoverflow.com/a/11237259/589493\n if (typeof window === 'undefined') {\n /* eslint-disable-next-line no-undef */\n return self;\n } else {\n return window;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/get-self-scope.js","// 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 = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\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 (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","let 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 let minIndex = 0;\n let maxIndex = list.length - 1;\n let currentIndex = null;\n let currentElement = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n\n let comparisonResult = comparisonFunction(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\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","// 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 = 8\n// module chunks = 0","/**\n * ID3 parser\n */\nclass 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\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;\n } // 2^32 / 90\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, true);\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, exitOnNull = false) {\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 (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\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","/**\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/utils/mediasource-helper.js","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport M3U8Parser from './m3u8-parser';\n\nconst { performance } = window;\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\nconst ContextType = {\n MANIFEST: 'manifest',\n LEVEL: 'level',\n AUDIO_TRACK: 'audioTrack',\n SUBTITLE_TRACK: 'subtitleTrack'\n};\n\n/**\n * @enum {string}\n */\nconst LevelType = {\n MAIN: 'main',\n AUDIO: 'audio',\n SUBTITLE: 'subtitle'\n};\n\n/**\n * @constructor\n */\nclass PlaylistLoader extends EventHandler {\n /**\n * @constructs\n * @param {Hls} hls\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\n this.loaders = {};\n }\n\n static get ContextType () {\n return ContextType;\n }\n\n static get LevelType () {\n return LevelType;\n }\n\n /**\n * @param {ContextType} type\n * @returns {boolean}\n */\n static canHaveQualityLevels (type) {\n return (type !== ContextType.AUDIO_TRACK &&\n type !== ContextType.SUBTITLE_TRACK);\n }\n\n /**\n * Map context.type to LevelType\n * @param {{type: ContextType}} context\n * @returns {LevelType}\n */\n static mapContextToLevelType (context) {\n const { type } = context;\n\n switch (type) {\n case ContextType.AUDIO_TRACK:\n return LevelType.AUDIO;\n case ContextType.SUBTITLE_TRACK:\n return LevelType.SUBTITLE;\n default:\n return LevelType.MAIN;\n }\n }\n\n static getResponseUrl (response, context) {\n let url = response.url;\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 return url;\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {object} context\n * @returns {XHRLoader} or other compatible configured overload\n */\n createInternalLoader (context) {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n\n const loader = new InternalLoader(config);\n\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n getInternalLoader (context) {\n return this.loaders[context.type];\n }\n\n resetInternalLoader (contextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n destroyInternalLoaders () {\n for (let contextType in this.loaders) {\n let loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n }\n\n destroy () {\n this.destroyInternalLoaders();\n\n super.destroy();\n }\n\n onManifestLoading (data) {\n this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });\n }\n\n onLevelLoading (data) {\n this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });\n }\n\n onAudioTrackLoading (data) {\n this.load(data.url, { type: ContextType.AUDIO_TRACK, level: 0, id: data.id });\n }\n\n onSubtitleTrackLoading (data) {\n this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: 0, id: data.id });\n }\n\n load (url, context) {\n const config = this.hls.config;\n\n logger.debug(`Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) { // same URL can't overlap\n logger.trace('playlist request ongoing');\n return false;\n } else {\n logger.warn(`aborting previous loader for type: ${context.type}`);\n loader.abort();\n }\n }\n\n let maxRetry,\n timeout,\n retryDelay,\n maxRetryDelay;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case ContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case ContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n context.url = url;\n context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)\n\n const loaderConfig = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay\n };\n\n const loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n logger.debug(`Calling internal loader delegate for URL: ${url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n }\n\n loadsuccess (response, stats, context, networkDetails = null) {\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n\n const string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n }\n\n loaderror (response, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails);\n }\n\n loadtimeout (stats, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, true);\n }\n\n _handleMasterPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n const string = response.data;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levels = M3U8Parser.parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n\n const audioGroups = levels.map(level => ({\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n }));\n\n let audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n let subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n\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\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // 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({\n type: 'main',\n name: 'main'\n });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n url,\n stats,\n networkDetails\n });\n }\n\n _handleTrackOrLevelPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n\n const { id, level, type } = context;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levelUrlId = isNaN(id) ? 0 : id;\n const levelId = isNaN(level) ? levelUrlId : level; // level -> id -> 0\n const levelType = PlaylistLoader.mapContextToLevelType(context);\n\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n levelDetails.tload = stats.tload;\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === ContextType.MANIFEST) {\n const singleLevel = {\n url,\n details: levelDetails\n };\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n const sidxUrl = levelDetails.initSegment.url;\n this.load(sidxUrl, {\n isSidxRequest: true,\n type,\n level,\n levelDetails,\n id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n }\n\n _handleSidxRequest (response, context) {\n const sidxInfo = MP4Demuxer.parseSegmentIndex(new Uint8Array(response.data));\n sidxInfo.references.forEach((segmentRef, index) => {\n const segRefInfo = segmentRef.info;\n const frag = context.levelDetails.fragments[index];\n\n if (frag.byteRange.length === 0) {\n frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);\n }\n });\n\n context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';\n }\n\n _handleManifestParsingError (response, context, reason, networkDetails) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason,\n networkDetails\n });\n }\n\n _handleNetworkError (context, networkDetails, timeout = false) {\n logger.info(`A network error occured while loading a ${context.type}-type playlist`);\n\n let details;\n let fatal;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case ContextType.MANIFEST:\n details = (timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR);\n fatal = true;\n break;\n case ContextType.LEVEL:\n details = (timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR);\n fatal = false;\n break;\n case ContextType.AUDIO_TRACK:\n details = (timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR);\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: loader.url,\n loader,\n context,\n networkDetails\n });\n }\n\n _handlePlaylistLoaded (response, stats, context, networkDetails) {\n const { type, level, id, levelDetails } = context;\n\n if (!levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n const canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(Event.LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats,\n networkDetails\n });\n } else {\n switch (type) {\n case ContextType.AUDIO_TRACK:\n this.hls.trigger(Event.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n case ContextType.SUBTITLE_TRACK:\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n }\n }\n }\n}\n\nexport default PlaylistLoader;\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/playlist-loader.js","/**\n * MP4 demuxer\n */\nimport { logger } from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4Demuxer {\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\n if (videoCodec == null) {\n videoCodec = 'avc1.42e01e';\n }\n\n const 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\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 });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\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 static bin2str (buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint16 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 8 |\n buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\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 // Find the data for a box specified by its path\n static findBox (data, path) {\n let 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 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 static parseSegmentIndex (initSegment) {\n const moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n const moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n let index = 0;\n let sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n let references;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n const version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n const timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.end + firstOffset;\n\n const referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7FFFFFFF;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n const subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n moovEndOffset\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 let result = [];\n let 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 * 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 */\n static getStartDTS (initData, fragment) {\n let 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 let 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 let 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 static 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 let id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n let 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 let version = tfdt.data[tfdt.start];\n let 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, false);\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\nexport default MP4Demuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/mp4demuxer.js","\nimport URLToolkit from 'url-toolkit';\n\nimport LevelKey from './level-key';\n\nexport default class Fragment {\n constructor () {\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n this.tagList = [];\n\n // Holds the types of data this fragment supports\n this._elementaryStreams = {\n [Fragment.ElementaryStreamTypes.AUDIO]: false,\n [Fragment.ElementaryStreamTypes.VIDEO]: false\n };\n }\n\n /**\n * `type` property for this._elementaryStreams\n *\n * @enum\n */\n static get ElementaryStreamTypes () {\n return {\n AUDIO: 'audio',\n VIDEO: 'video'\n };\n }\n\n get url () {\n if (!this._url && this.relurl) {\n this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\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\n return this._programDateTime;\n }\n\n get byteRange () {\n if (!this._byteRange && !this.rawByteRange) {\n return [];\n }\n\n if (this._byteRange) {\n return this._byteRange;\n }\n\n let 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 || 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n return byteRange;\n }\n\n /**\n * @type {number}\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\n return this._decryptdata;\n }\n\n get encrypted () {\n return !!((this.decryptdata && this.decryptdata.uri !== null) && (this.decryptdata.key === null));\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n addElementaryStream (type) {\n this._elementaryStreams[type] = true;\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n hasElementaryStream (type) {\n return this._elementaryStreams[type] === true;\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 let uint8View = new Uint8Array(16);\n\n for (let 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 let 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\n\n\n// WEBPACK FOOTER //\n// ./src/loader/fragment.js","import URLToolkit from 'url-toolkit';\n\nexport default class LevelKey {\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\n return this._uri;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/level-key.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 window.MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/codecs.js","import EventHandler from '../event-handler';\nimport Event from '../events';\n\nexport const FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nexport class FragmentTracker extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.BUFFER_APPENDED,\n Event.FRAG_BUFFERED,\n Event.FRAG_LOADED\n );\n\n this.bufferPadding = 0.2;\n\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n\n this.config = hls.config;\n }\n\n destroy () {\n this.fragments = null;\n this.timeRanges = null;\n this.config = null;\n EventHandler.prototype.destroy.call(this);\n super.destroy();\n }\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n getBufferedFrag (position, levelType) {\n const fragments = this.fragments;\n const bufferedFrags = Object.keys(fragments).filter(key => {\n const fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n const frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n const bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n detectEvictedFragments (elementaryStream, timeRange) {\n let fragmentTimes, time;\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (fragmentEntity.buffered === true) {\n const esData = fragmentEntity.range[elementaryStream];\n if (esData) {\n fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n time = fragmentTimes[i];\n\n if (this.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n break;\n }\n }\n }\n }\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n detectPartialFragments (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n if (fragment.hasElementaryStream(elementaryStream) === true) {\n let timeRange = this.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n }\n\n getBufferedTimes (startPTS, endPTS, timeRange) {\n let fragmentTimes = [];\n let startTime, endTime;\n let fragmentPartial = false;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n }\n\n getFragmentKey (fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n }\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n getPartialFragment (time) {\n let timePadding, startTime, endTime;\n let bestFragment = null;\n let bestOverlap = 0;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (this.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - this.bufferPadding;\n endTime = fragmentEntity.body.endPTS + this.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n getState (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n let state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n }\n\n isPartial (fragmentEntity) {\n return fragmentEntity.buffered === true &&\n ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||\n (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));\n }\n\n isTimeBuffered (startPTS, endPTS, timeRange) {\n let startTime, endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n /**\n * Fires when a fragment loading is completed\n */\n onFragLoaded (e) {\n let fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!isNaN(fragment.sn) && !fragment.bitrateTest) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n this.fragments[fragKey] = fragmentEntity;\n }\n }\n\n /**\n * Fires when the buffer is updated\n */\n onBufferAppended (e) {\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n let timeRange = this.timeRanges[elementaryStream];\n this.detectEvictedFragments(elementaryStream, timeRange);\n });\n }\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n onFragBuffered (e) {\n this.detectPartialFragments(e.frag);\n }\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n hasFragment (fragment) {\n const fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n }\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n removeFragment (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n }\n\n /**\n * Remove all fragments from fragment tracker.\n */\n removeAllFragments () {\n this.fragments = Object.create(null);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fragment-tracker.js","/**\n * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n * @param {HTMLMediaElement|SourceBuffer} media\n * @param {number} position\n * @returns {boolean}\n */\n static isBuffered (media, position) {\n try {\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 } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo (media, pos, maxHoleDuration) {\n try {\n if (media) {\n let 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\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo (buffered, pos, maxHoleDuration) {\n let 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 let 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 let buf2len = buffered2.length;\n if (buf2len) {\n let 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 let start = buffered2[i].start,\n end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/buffer-helper.js","/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\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\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst performance = global;\n\nclass DemuxerInline {\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 let 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\n let localthis = this;\n // performance.now() not available on WebWorker, at least on Safari Desktop\n let 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 let 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 let demuxer = this.demuxer;\n if (!demuxer ||\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n // so let's check that current demuxer is still valid\n ((discontinuity || trackSwitch) && !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: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer }\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\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","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\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nclass Decrypter {\n constructor (observer, config, { removePKCS7Padding = true } = {}) {\n this.logEnabled = true;\n this.observer = observer;\n this.config = config;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = global.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {}\n }\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\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));\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 } 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","/**\n * ADTS parser helper\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\nexport function getAudioConfig (observer, data, offset, audioCodec) {\n let 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\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\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 let 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 let headerLength, frameLength, stamp;\n let 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 let frameDuration = getFrameDuration(track.samplerate);\n let header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n let stamp = header.stamp;\n let headerLength = header.headerLength;\n let frameLength = header.frameLength;\n\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n let 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// WEBPACK FOOTER //\n// ./src/demux/adts.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 SamplesCoefficients: [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]\n ],\n\n BytesInSlot: [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\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 let header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n let frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;\n let stamp = pts + frameIndex * frameDuration;\n let 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 let headerB = (data[offset + 1] >> 3) & 3;\n let headerC = (data[offset + 1] >> 1) & 3;\n let headerE = (data[offset + 2] >> 4) & 15;\n let headerF = (data[offset + 2] >> 2) & 3;\n let headerG = (data[offset + 2] >> 1) & 1;\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n let columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n let bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n let columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n let sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n let channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n let sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n let bytesInSlot = MpegAudio.BytesInSlot[headerC];\n let samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n let frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\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\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\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 * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\nimport { logger } from '../utils/logger';\n\nexport function addGroupId (level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nexport function updatePTS (fragments, fromIdx, toIdx) {\n let 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\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\n let 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\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 let 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 // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\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 let 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 let 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/controller/level-helper.js","import URLToolkit from 'url-toolkit';\n\nimport {\n ErrorTypes,\n ErrorDetails\n} from './errors';\n\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { hlsDefaultConfig } from './config';\n\nimport HlsEvents from './events';\nimport EventEmitter from 'events';\n\n// polyfill for IE11\nrequire('string.prototype.endswith');\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\nexport default class Hls {\n /**\n * @type {string}\n */\n static get version () {\n return __VERSION__;\n }\n\n /**\n * @type {boolean}\n */\n static isSupported () {\n return isSupported();\n }\n\n /**\n * @type {HlsEvents}\n */\n static get Events () {\n return HlsEvents;\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n static get ErrorTypes () {\n return ErrorTypes;\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n static get ErrorDetails () {\n return ErrorDetails;\n }\n\n /**\n * @type {HlsConfig}\n */\n static get DefaultConfig () {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n static set DefaultConfig (defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n constructor (config = {}) {\n let 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 (let 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 let 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.once = observer.once.bind(observer);\n this.trigger = observer.trigger.bind(observer);\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n const abrController = this.abrController = new config.abrController(this);\n\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\n /**\n * @member {LevelController} levelController\n */\n const levelController = this.levelController = new LevelController(this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n\n /**\n * @member {StreamController} streamController\n */\n const streamController = this.streamController = new StreamController(this, fragmentTracker);\n\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n const coreComponents = [\n playListLoader,\n fragmentLoader,\n keyLoader,\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker\n ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n const audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n const subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n coreComponents.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n const emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\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\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n destroy () {\n logger.log('destroy');\n this.trigger(HlsEvents.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {\n component.destroy();\n });\n this.url = null;\n this.observer.removeAllListeners();\n this._autoLevelCapping = -1;\n }\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n attachMedia (media) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(HlsEvents.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach from the media\n */\n detachMedia () {\n logger.log('detachMedia');\n this.trigger(HlsEvents.MEDIA_DETACHING);\n this.media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\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(HlsEvents.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n startLoad (startPosition = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach(controller => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad () {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec () {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError () {\n logger.log('recoverMediaError');\n let media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n }\n\n /**\n * @type {QualityLevel[]}\n */\n get levels () {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel () {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @type {number} -1 for automatic level selection\n */\n set currentLevel (newLevel) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n get nextLevel () {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n set nextLevel (newLevel) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n get loadLevel () {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n set loadLevel (newLevel) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n get nextLoadLevel () {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n set nextLoadLevel (level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n get firstLevel () {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n set firstLevel (newLevel) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\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\n * (determined from download of first segment)\n * @type {number}\n */\n get startLevel () {\n return this.levelController.startLevel;\n }\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\n * (determined from download of first segment)\n * @type {number} newLevel\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\n hls.levelController.startLevel = newLevel;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n get autoLevelCapping () {\n return this._autoLevelCapping;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n set autoLevelCapping (newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n get autoLevelEnabled () {\n return (this.levelController.manualLevel === -1);\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n get manualLevel () {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\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 /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\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\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\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 /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * 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,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n set nextAutoLevel (nextLevel) {\n const hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n get audioTracks () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n get audioTrack () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n set audioTrack (audioTrackId) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n get liveSyncPosition () {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n get subtitleTracks () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n get subtitleTrack () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type{number}\n */\n set subtitleTrack (subtitleTrackId) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n get subtitleDisplay () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\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","\nimport URLToolkit from 'url-toolkit';\n\nimport Fragment from './fragment';\nimport LevelKey from './level-key';\n\nimport AttrList from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport { isCodecType } from '../utils/codecs';\n\n/**\n * M3U8 parser\n * @module\n */\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\nconst MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nexport default class M3U8Parser {\n static 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\n static convertAVC1ToAVCOTI (codec) {\n let 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 static resolve (url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static 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 const attrs = level.attrs = new AttrList(result[1]);\n level.url = M3U8Parser.resolve(result[2], baseurl);\n\n const 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 = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n }\n return levels;\n }\n\n static 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 = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n media.lang = attrs.LANGUAGE;\n if (!media.name) {\n media.name = media.lang;\n }\n\n if (audioGroups.length) {\n const groupCodec = M3U8Parser.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 static parseLevelPlaylist (string, baseurl, id, type, levelUrlId) {\n let 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 || 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.urlId = levelUrlId;\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 if (level.programDateTime) {\n if (prevFrag) {\n if (frag.rawProgramDateTime) { // PDT discontinuity found\n frag.pdt = Date.parse(frag.rawProgramDateTime);\n } else { // Contiguous fragment\n frag.pdt = prevFrag.pdt + (prevFrag.duration * 1000);\n }\n } else { // First fragment\n frag.pdt = Date.parse(level.programDateTime);\n }\n frag.endPdt = frag.pdt + (frag.duration * 1000);\n }\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', 'SAMPLE-AES-CENC'].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\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\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every((frag) => MP4_REGEX_SUFFIX.test(frag.relurl))) {\n logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new Fragment();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n return level;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/m3u8-parser.js","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n constructor (attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (let 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\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\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\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\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList (input) {\n let match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let 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\n attrs[match[1]] = value;\n }\n return attrs;\n }\n}\n\nexport default AttrList;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/attr-list.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 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\n super.destroy();\n }\n\n onFragLoading (data) {\n const frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n let loader = loaders[type];\n if (loader) {\n logger.warn(`abort previous fragment loader for type: ${type}`);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader =\n config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n let start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (!isNaN(start) && !isNaN(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\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\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\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 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\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\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","/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment from '../loader/fragment';\nimport PlaylistLoader from '../loader/playlist-loader';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { alignDiscontinuities } from '../utils/discontinuities';\nimport TaskLoop from '../task-loop';\nimport { calculateNextPDT, findFragmentByPDT, findFragmentBySN, fragmentWithinToleranceTest } from './fragment-finders';\n\nexport const 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 TaskLoop {\n constructor (hls, fragmentTracker) {\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.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.stallReported = false;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n super.onHandlerDestroyed();\n }\n\n startLoad (startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n this.setInterval(100);\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 let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.clearInterval();\n this.state = State.STOPPED;\n this.forceStartLoad = false;\n }\n\n doTick () {\n switch (this.state) {\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\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log('mediaController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle () {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n // if 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\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\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 (!levelDetails || (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\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 } 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\n if (frag) {\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);\n this._loadKey(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 this._loadFragment(frag);\n }\n }\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\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 if (!levelDetails.programDateTime) { // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\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 } else { // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPDT(fragments, fragPrevious.endPdt + 1);\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 const fragBySN = () => findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n let frag;\n let foundFrag;\n\n if (bufferEnd < end) {\n if (!levelDetails.programDateTime) { // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n } else {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = findFragmentByPDT(fragments, calculateNextPDT(start, bufferEnd, levelDetails));\n if (!foundFrag || fragmentWithinToleranceTest(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) {\n // Fall back to SN order if finding by PDT returns a frag which won't fit within the stream\n // fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise\n logger.warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN');\n foundFrag = fragBySN();\n }\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 } 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 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 _loadKey (frag) {\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\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\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n this.hls.trigger(Event.FRAG_LOADING, { 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(this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\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 this.fragmentTracker.getBufferedFrag(position, PlaylistLoader.LevelType.MAIN);\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 let 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 > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\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 let 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\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 let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\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 const 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 /**\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 nextLevelSwitch () {\n const 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 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 let 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 let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\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\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached (data) {\n let 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 let 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 backtracked flag\n let levels = this.levels;\n if (levels) {\n levels.forEach(level => {\n if (level.details) {\n level.details.fragments.forEach(fragment => {\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\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\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\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\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\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 onManifestLoading () {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed (data) {\n let 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\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\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 let 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\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 let 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 const stats = data.stats;\n const currentLevel = this.levels[fragCurrent.level];\n const 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 = window.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 = window.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\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\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\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let 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\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n let 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 let 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 let 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 if (data.hasAudio === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.VIDEO);\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', frag.sn);\n } else {\n logger.warn('missing video frame(s), backtracking fragment', frag.sn);\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 this.fragmentTracker.removeFragment(frag);\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', frag.sn);\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 let 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 // 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 = window.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 let 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 let 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 onBufferCreated (data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for (let 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 this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = window.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\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 logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = window.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.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 return true;\n }\n return false;\n }\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n _checkBuffer () {\n const { config, media } = this;\n const stallDebounceInterval = 1000;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n const currentTime = media.currentTime;\n const mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n const buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n const expectedPlaying = !((media.paused && media.readyState > 1) || // not playing when media is paused and sufficiently buffered\n media.ended || // not playing when media is ended\n media.buffered.length === 0); // not playing if nothing buffered\n const tnow = window.performance.now();\n\n if (currentTime !== this.lastCurrentTime) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(tnow - this.stalled)}ms`);\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n } else if (expectedPlaying) {\n // The playhead isn't moving but it should be\n // Allow some slack time to for small stalls to resolve themselves\n const stalledDuration = tnow - this.stalled;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);\n if (!this.stalled) {\n this.stalled = tnow;\n return;\n } else if (stalledDuration >= stallDebounceInterval) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n this._tryFixBufferStall(bufferInfo, stalledDuration);\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 if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n this.fragmentTracker.detectEvictedFragments(Fragment.ElementaryStreamTypes.VIDEO, media.buffered);\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 /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDuration - The amount of time Hls.js has been stalling for.\n * @private\n */\n _tryFixBufferStall (bufferInfo, stalledDuration) {\n const { config, media } = this;\n const currentTime = media.currentTime;\n const jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end\n\n const partial = this.fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n this._trySkipBufferHole(partial);\n }\n\n if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n _reportStall (bufferLen) {\n const { hls, media, stallReported } = this;\n if (!stallReported) {\n // Report stalled error once\n this.stallReported = true;\n logger.warn(`Playback stalling at @${media.currentTime} due to low buffer`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n _trySkipBufferHole (partial) {\n const { hls, media } = this;\n const currentTime = media.currentTime;\n let lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (let i = 0; i < media.buffered.length; i++) {\n let startTime = media.buffered.start(i);\n if (currentTime >= lastEndTime && currentTime < startTime) {\n media.currentTime = Math.max(startTime, media.currentTime + 0.1);\n logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${media.currentTime}`);\n this.stalled = null;\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${media.currentTime}`,\n frag: partial\n });\n return;\n }\n lastEndTime = media.buffered.end(i);\n }\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n _tryNudgeBuffer () {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n const nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\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, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, raise fatal error`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n _seekToStartPos () {\n const { media } = this;\n const currentTime = media.currentTime;\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 const startPosition = media.seeking ? currentTime : this.startPosition;\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition) {\n // if startPosition not buffered, let's seek to buffered.start(0)\n logger.log(`target start position not buffered, seek to buffered.start(0) ${startPosition} from current time ${currentTime} `);\n media.currentTime = startPosition;\n }\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// WEBPACK FOOTER //\n// ./src/controller/stream-controller.js","import EventEmitter from 'events';\nimport work from 'webworkify-webpack';\n\nimport Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst MediaSource = getMediaSource();\n\nclass Demuxer {\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 let 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) {\n 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 };\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 global.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\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\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 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 global.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\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// WEBPACK FOOTER //\n// ./src/demux/demuxer.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\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\((\\/\\\\*.*?\\\\*\\/)?\\s?.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_modules__\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\\n'\n })\n\n src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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 = 30\n// module chunks = 0","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","// PKCS7\nexport function removePadding (buffer) {\n const outputBytes = buffer.byteLength;\n const paddingBytes = outputBytes && (new DataView(buffer)).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return buffer.slice(0, outputBytes - paddingBytes);\n } else {\n return buffer;\n }\n}\n\nclass 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\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, removePKCS7Padding) {\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 let 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 removePKCS7Padding ? removePadding(outputInt32.buffer) : 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","/**\n * AAC demuxer\n */\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport ID3 from '../demux/id3';\n\nclass AACDemuxer {\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\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 let 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\nexport default AACDemuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/aacdemuxer.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\nimport * as ADTS from './adts';\nimport MpegAudio from './mpegaudio';\nimport Event from '../events';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\n// import Hex from '../utils/hex';\nimport { logger } from '../utils/logger';\nimport { 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: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nclass TSDemuxer {\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\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 let start, len = data.length, stt, pid, atf, offset, pes,\n unknownPIDs = false;\n this.contiguous = contiguous;\n let 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)) && pes.pts !== undefined) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n parseID3PES(pes);\n }\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\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\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\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\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)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\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\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)) && pes.pts !== undefined) {\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 let 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\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\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\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 let 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\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 let 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\n if (debug) {\n avcSample.debug += 'NDR ';\n }\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\n if (debug) {\n avcSample.debug += 'IDR ';\n }\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\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 endOfCaptions = true;\n\n let countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n let providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n let userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n let userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n let firstByte = expGolombDecoder.readUByte();\n let secondByte = expGolombDecoder.readUByte();\n\n let totalCCs = 31 & firstByte;\n let 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 } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\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\n if (!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n let 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 let codecarray = unit.data.subarray(1, 4);\n let codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\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\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\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\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 let len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\n } else {\n for (let 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 } 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 let i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n let 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 let 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 let 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 let 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 let 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 let 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 let 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 let 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\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES (pes) {\n let data = pes.data;\n let length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let 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 * 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 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 let\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\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 let 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 let\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\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\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 let leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\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 let clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG () {\n let 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 this.readBits(1) === 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 let\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 let\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 let chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // 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 let 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();\n } // offset_for_ref_frame[ i ]\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);\n } // 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\nimport Decrypter from '../crypt/decrypter';\n\nclass SampleAesDecrypter {\n constructor (observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config, { removePKCS7Padding: false });\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\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\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\nexport default SampleAesDecrypter;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/sample-aes.js","/**\n * MP3 demuxer\n */\nimport ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport MpegAudio from './mpegaudio';\n\nclass MP3Demuxer {\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 let 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 timestamp = ID3.getTimeStamp(id3Data);\n let pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n let offset = id3Data.length;\n let length = data.length;\n let frameIndex = 0, stamp = 0;\n let 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 let 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 * fMP4 remuxer\n*/\n\nimport AAC from './aac-helper';\nimport MP4 from './mp4-generator';\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\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\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 // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED);\n }\n\n generateIS (audioTrack, videoTrack, timeOffset) {\n let 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\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 let 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 if (nbSamples === 0) {\n return;\n }\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 || (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\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\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 maxBufferHole.\n // 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 gapTolerance = Math.floor(maxBufferHole * 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 should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\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 // 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 hasAudio: false,\n hasVideo: true,\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 let 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 // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter(function (sample) {\n return sample.pts >= 0;\n });\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = timeOffset * inputTimeScale;\n }\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 if (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 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 } // eslint-disable-line brace-style\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 let 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 (let 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 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\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\n firstPTS = 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 let lastSampleDuration = 0;\n let 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\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 hasAudio: true,\n hasVideo: false,\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 (let i = 0; i < nbSamples; i++) {\n let 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 let 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 (let 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 let length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if (length) {\n for (let 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 let offset;\n if (reference === undefined) {\n return value;\n }\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\n return value;\n }\n}\n\nexport default MP4Remuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/remux/mp4-remuxer.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\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/remux/aac-helper.js","/**\n * Generate MP4 Box\n*/\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 let 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 let 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 let 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 let 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 let 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 let majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n let avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n let 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 let\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\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 let\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 let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\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 let\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 let\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 let 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\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\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\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n let 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\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 let 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 let 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 let 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\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 let 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 let 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 let 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 let 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\n let 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 * 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 let observer = this.observer;\n let streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\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","/* 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\nimport DemuxerInline from '../demux/demuxer-inline';\nimport Event from '../events';\nimport { enableLogs } from '../utils/logger';\nimport EventEmitter from 'events';\n\nlet DemuxerWorker = function (self) {\n // observer setup\n let 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 let forwardMessage = function (ev, data) {\n self.postMessage({ event: ev, data: data });\n };\n\n self.addEventListener('message', function (ev) {\n let 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// WEBPACK FOOTER //\n// ./src/demux/demuxer-worker.js","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r) {\n let log = '', len = r.length;\n for (let i = 0; i < len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n\n return log;\n }\n};\n\nexport default TimeRanges;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/time-ranges.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 && lastLevel.details.fragments && lastLevel.details.fragments.length) {\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","import EventHandler from './event-handler';\n\n/**\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\n\nexport default class TaskLoop extends EventHandler {\n constructor (hls, ...events) {\n super(hls, ...events);\n\n this._tickInterval = null;\n this._tickTimer = null;\n this._tickCallCount = 0;\n this._boundTick = this.tick.bind(this);\n }\n\n /**\n * @override\n */\n onHandlerDestroying () {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n /**\n * @returns {boolean}\n */\n hasInterval () {\n return !!this._tickInterval;\n }\n\n /**\n * @returns {boolean}\n */\n hasNextTick () {\n return !!this._tickTimer;\n }\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n */\n setInterval (millis) {\n if (!this._tickInterval) {\n this._tickInterval = setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n */\n clearInterval () {\n if (this._tickInterval) {\n clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n clearNextTick () {\n if (this._tickTimer) {\n clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n tick () {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.clearNextTick();\n this._tickTimer = setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n doTick () {}\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/task-loop.js","import BinarySearch from '../utils/binary-search';\n\n/**\n * Calculates the PDT of the next load position.\n * bufferEnd in this function is usually the position of the playhead.\n * @param {number} [start = 0] - The PTS of the first fragment within the level\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level\n * @returns {number} nextPdt - The computed PDT\n */\nexport function calculateNextPDT (start = 0, bufferEnd = 0, levelDetails) {\n let pdt = 0;\n if (levelDetails.programDateTime) {\n const parsedDateInt = Date.parse(levelDetails.programDateTime);\n if (!isNaN(parsedDateInt)) {\n pdt = (bufferEnd * 1000) + parsedDateInt - (1000 * start);\n }\n }\n return pdt;\n}\n\n/**\n * Finds the first fragment whose endPDT value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @returns {*|null} fragment - The best matching fragment\n */\nexport function findFragmentByPDT (fragments, PDTValue = null) {\n if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) {\n return null;\n }\n\n // if less than start\n let firstSegment = fragments[0];\n\n if (PDTValue < firstSegment.pdt) {\n return null;\n }\n\n let lastSegment = fragments[fragments.length - 1];\n\n if (PDTValue >= lastSegment.endPdt) {\n return null;\n }\n\n for (let seg = 0; seg < fragments.length; ++seg) {\n let frag = fragments[seg];\n if (PDTValue < frag.endPdt) {\n return frag;\n }\n }\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} [end = 0] - The computed end time of the stream\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nexport function findFragmentBySN (fragPrevious, fragments, bufferEnd = 0, end = 0, maxFragLookUpTolerance = 0) {\n let foundFrag;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n }\n }\n return foundFrag;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest (bufferEnd = 0, maxFragLookUpTolerance = 0, 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 } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fragment-finders.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';\nimport { addGroupId } from './level-helper';\n\nconst { performance } = window;\n\nexport default class LevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.FRAG_LOADED,\n Event.ERROR);\n\n this.canload = false;\n this.currentLevelIndex = null;\n this.manualLevelIndex = -1;\n this.timer = null;\n }\n\n onHandlerDestroying () {\n this.clearTimer();\n this.manualLevelIndex = -1;\n }\n\n clearTimer () {\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 !== null) {\n this.loadLevel();\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 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (level.attrs && level.attrs.AUDIO) {\n addGroupId(levelFromSet || level, 'audio', level.attrs.AUDIO);\n }\n\n if (level.attrs && level.attrs.SUBTITLES) {\n addGroupId(levelFromSet || level, 'text', level.attrs.SUBTITLES);\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\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 > 0) {\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, {\n levels,\n audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: audioTracks.length > 0 && videoCodecFound\n });\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.currentLevelIndex;\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.currentLevelIndex !== newLevel || !levels[newLevel].details) {\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.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this.currentLevelIndex = newLevel;\n const levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n const level = levels[newLevel];\n const levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n let 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, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n }\n\n get manualLevel () {\n return this.manualLevelIndex;\n }\n\n set manualLevel (newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel () {\n return this._firstLevel;\n }\n\n set firstLevel (newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel () {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel (newLevel) {\n this._startLevel = newLevel;\n }\n\n onError (data) {\n if (data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n let levelError = false, fragmentError = false;\n let levelIndex;\n\n // try to recover not fatal errors\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 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 levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {\n let { config } = this.hls;\n let { details: errorDetails } = errorEvent;\n let level = this._levels[levelIndex];\n let redundantLevels, delay, nextLevel;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(() => this.loadLevel(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`level controller, cannot recover from ${errorDetails} error`);\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;\n logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n logger.warn(`level controller, ${errorDetails}: reload a fragment`);\n this.currentLevelIndex = null;\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.currentLevelIndex) {\n return;\n }\n\n const 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) {\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 const targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration);\n let reloadInterval = targetdurationMs,\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 half of target duration\n reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval));\n logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);\n this.timer = setTimeout(() => this.loadLevel(), reloadInterval);\n } else {\n this.clearTimer();\n }\n }\n\n onAudioTrackSwitched (data) {\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n const urlId = currentLevel.audioGroupIds.findIndex((groupId) => groupId === audioGroupId);\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n loadLevel () {\n logger.debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n const levelObject = this._levels[this.currentLevelIndex];\n\n if (typeof levelObject === 'object' &&\n levelObject.url.length > 0) {\n const level = this.currentLevelIndex;\n const id = levelObject.urlId;\n const url = levelObject.url[id];\n\n logger.log(`Attempt loading level index ${level} with URL-id ${id}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });\n }\n }\n }\n\n get nextLoadLevel () {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel (nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n}\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';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\n\nclass ID3TrackController extends EventHandler {\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\n }\n }\n\n onMediaDetaching () {\n clearCurrentCues(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n getID3Track (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n let textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\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.getID3Track(this.media.textTracks);\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","\nexport function sendAddTrackEvent (track, videoEl) {\n let event = null;\n try {\n event = new window.Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n event.track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function clearCurrentCues (track) {\n if (track && track.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/texttrack-utils.js","import { getMediaSource } from './utils/mediasource-helper';\n\nexport function 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\n\n// WEBPACK FOOTER //\n// ./src/is-supported.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';\nimport EMEController from './controller/eme-controller';\n\nimport { requestMediaKeySystemAccess } from './utils/mediakeys-helper';\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\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 liveDurationInfinity: false, // used by buffer-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 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, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\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 emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n requestMediaKeySystemAccessFunc:\n requestMediaKeySystemAccess // used by eme-controller\n};\n\nif (__USE_SUBTITLES__) {\n hlsDefaultConfig.subtitleStreamController = SubtitleStreamController;\n hlsDefaultConfig.subtitleTrackController = SubtitleTrackController;\n hlsDefaultConfig.timelineController = TimelineController;\n hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller\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 (__USE_ALT_AUDIO__) {\n hlsDefaultConfig.audioStreamController = AudioStreamController;\n hlsDefaultConfig.audioTrackController = AudioTrackController;\n}\n\nif (__USE_EME_DRM__) {\n hlsDefaultConfig.emeController = EMEController;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/config.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 '../utils/buffer-helper';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\n\nconst { performance } = window;\n\nclass AbrController extends EventHandler {\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 const frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, 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 const hls = this.hls;\n const config = hls.config;\n const level = frag.level;\n const isLive = hls.levels[level].details.live;\n\n let ewmaFast, ewmaSlow;\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 }\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 const hls = this.hls;\n const video = hls.media;\n const frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n const loader = frag.loader;\n const 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 // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\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 (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {\n let requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(video.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 = video.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (BufferHelper.bufferInfo(video, 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 const 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 const stats = data.stats;\n const 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.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\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\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel () {\n let hls = this.hls, maxAutoLevel = hls.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = hls.minAutoLevel;\n const video = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = (video ? video.currentTime : 0),\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.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(video, 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\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// WEBPACK FOOTER //\n// ./src/controller/abr-controller.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\nclass EwmaBandWidthEstimator {\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 let 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 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// WEBPACK FOOTER //\n// ./src/utils/ewma-bandwidth-estimator.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 // 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 let 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 let 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 * 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 '../utils/mediasource-helper';\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\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 // current stream state: true - for live broadcast, false - for VoD content\n this._live = null;\n // cache the self generated object url to detect hijack of video tag\n this._objectUrl = 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.altAudio),\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 let 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 = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n }\n\n onMediaDetaching () {\n logger.log('media source detaching');\n let 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 window.URL.revokeObjectURL(this._objectUrl);\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n logger.warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = 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 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\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\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n let timeRanges = {};\n const sourceBuffer = this.sourceBuffer;\n for (let streamType in sourceBuffer) {\n timeRanges[streamType] = sourceBuffer[streamType].buffered;\n }\n\n this.hls.trigger(Event.BUFFER_APPENDED, { parent, pending, timeRanges });\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 let sourceBuffer = this.sourceBuffer;\n for (let type in sourceBuffer) {\n let 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 (let 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 createSourceBuffers (tracks) {\n let 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\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 let 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 let 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\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 onBufferFlushing (data) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n onLevelUpdated ({ details }) {\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n updateMediaElementDuration () {\n let { config } = this.hls;\n let duration;\n\n if (this._levelDuration === null ||\n !this.media ||\n !this.mediaSource ||\n !this.sourceBuffer ||\n this.media.readyState === 0 ||\n this.mediaSource.readyState !== 'open') {\n return;\n }\n\n for (let type in this.sourceBuffer) {\n if (this.sourceBuffer[type].updating === true) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n\n duration = this.media.duration;\n // initialise to the value that the media source is reporting\n if (this._msDuration === null) {\n this._msDuration = this.mediaSource.duration;\n }\n\n if (this._live === true && config.liveDurationInfinity === true) {\n // Override duration to Infinity\n logger.log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if ((this._levelDuration > this._msDuration && this._levelDuration > duration) ||\n (duration === Infinity || isNaN(duration))) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(`Updating Media Source duration to ${this._levelDuration.toFixed(3)}`);\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n }\n\n doFlush () {\n // loop through all buffer ranges to flush\n while (this.flushRange.length) {\n let 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 let appended = 0;\n let sourceBuffer = this.sourceBuffer;\n try {\n for (let 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 let 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 let 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\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 } 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 }\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 let 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 (let 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\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 constructor (hls) {\n super(hls,\n Event.FPS_DROP_LEVEL_CAPPING,\n Event.MEDIA_ATTACHING,\n Event.MANIFEST_PARSED,\n Event.BUFFER_CODECS);\n\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = null;\n this.levels = [];\n this.media = null;\n this.restrictedLevels = [];\n this.timer = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this._stopCapping();\n }\n }\n\n onFpsDropLevelCapping (data) {\n // 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 onMediaAttaching (data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed (data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && (data.video || (data.levels.length && data.altAudio))) {\n // Start capping immediately if the manifest has signaled video codecs\n this._startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs (data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this._startCapping();\n }\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\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 _startCapping () {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n _stopCapping () {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\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\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\nconst { performance } = window;\n\nclass FPSController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy () {\n if (this.timer) {\n clearInterval(this.timer);\n }\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 window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\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// WEBPACK FOOTER //\n// ./src/controller/fps-controller.js","/**\n * XHR based logger\n*/\n\nimport { logger } from '../utils/logger';\n\nconst { performance, XMLHttpRequest } = window;\n\nclass XhrLoader {\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 let 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 let 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\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 let 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\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 let xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\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","const requestMediaKeySystemAccess = (function () {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {\n return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);\n } else {\n return null;\n }\n})();\n\nexport {\n requestMediaKeySystemAccess\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/mediakeys-helper.js","/*! http://mths.be/endswith v0.2.0 by @mathias */\nif (!String.prototype.endsWith) {\n\t(function() {\n\t\t'use strict'; // needed to support `apply`/`call` with `undefined`/`null`\n\t\tvar defineProperty = (function() {\n\t\t\t// IE 8 only supports `Object.defineProperty` on DOM elements\n\t\t\ttry {\n\t\t\t\tvar object = {};\n\t\t\t\tvar $defineProperty = Object.defineProperty;\n\t\t\t\tvar result = $defineProperty(object, object, object) && $defineProperty;\n\t\t\t} catch(error) {}\n\t\t\treturn result;\n\t\t}());\n\t\tvar toString = {}.toString;\n\t\tvar endsWith = function(search) {\n\t\t\tif (this == null) {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar string = String(this);\n\t\t\tif (search && toString.call(search) == '[object RegExp]') {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar stringLength = string.length;\n\t\t\tvar searchString = String(search);\n\t\t\tvar searchLength = searchString.length;\n\t\t\tvar pos = stringLength;\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tvar position = arguments[1];\n\t\t\t\tif (position !== undefined) {\n\t\t\t\t\t// `ToInteger`\n\t\t\t\t\tpos = position ? Number(position) : 0;\n\t\t\t\t\tif (pos != pos) { // better `isNaN`\n\t\t\t\t\t\tpos = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar end = Math.min(Math.max(pos, 0), stringLength);\n\t\t\tvar start = end - searchLength;\n\t\t\tif (start < 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar index = -1;\n\t\t\twhile (++index < searchLength) {\n\t\t\t\tif (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\tif (defineProperty) {\n\t\t\tdefineProperty(String.prototype, 'endsWith', {\n\t\t\t\t'value': endsWith,\n\t\t\t\t'configurable': true,\n\t\t\t\t'writable': true\n\t\t\t});\n\t\t} else {\n\t\t\tString.prototype.endsWith = endsWith;\n\t\t}\n\t}());\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/string.prototype.endswith/endswith.js\n// module id = 61\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls.min.js b/grails-app/assets/bower/hls.js/dist/hls.min.js new file mode 100644 index 000000000..bd74c923b --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls.min.js @@ -0,0 +1,3 @@ +!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=28)}([function(t,e,r){"use strict";function i(){}function a(t,e){return e="["+t+"] > "+e}function n(t){var e=c.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(c.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){d[e]=t[e]?t[e].bind(t):n(e)})}r.d(e,"a",function(){return h}),r.d(e,"b",function(){return f});var s=r(4),l="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},u={trace:i,debug:i,log:i,warn:i,info:i,error:i},d=u,c=Object(s.a)(),h=function(t){if(!0===t||"object"===(void 0===t?"undefined":l(t))){o(t,"debug","log","info","warn","error");try{d.log()}catch(t){d=u}}else d=u},f=d},function(t,e,r){"use strict";var i={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_SWITCHING:"hlsLevelSwitching",LEVEL_SWITCHED:"hlsLevelSwitched",LEVEL_LOADING:"hlsLevelLoading",LEVEL_LOADED:"hlsLevelLoaded",LEVEL_UPDATED:"hlsLevelUpdated",LEVEL_PTS_UPDATED:"hlsLevelPtsUpdated",AUDIO_TRACKS_UPDATED:"hlsAudioTracksUpdated",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"};e.a=i},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",KEY_SYSTEM_ERROR:"keySystemError",MUX_ERROR:"muxError",OTHER_ERROR:"otherError"},a={KEY_SYSTEM_NO_KEYS:"keySystemNoKeys",KEY_SYSTEM_NO_ACCESS:"keySystemNoAccess",KEY_SYSTEM_NO_SESSION:"keySystemNoSession",KEY_SYSTEM_LICENSE_REQUEST_FAILED:"keySystemLicenseRequestFailed",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_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")}var a=r(0),n=r(2),o=r(1),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=new Set(["hlsEventGeneric","hlsHandlerDestroying","hlsHandlerDestroyed"]),u=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.onHandlerDestroying(),this.unregisterListeners(),this.onHandlerDestroyed()},t.prototype.onHandlerDestroying=function(){},t.prototype.onHandlerDestroyed=function(){},t.prototype.isEventHandler=function(){return"object"===s(this.handledEvents)&&this.handledEvents.length&&"function"==typeof this.onEvent},t.prototype.registerListeners=function(){this.isEventHandler()&&this.handledEvents.forEach(function(t){if(l.has(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){a.b.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),this.hls.trigger(o.a.ERROR,{type:n.b.OTHER_ERROR,details:n.a.INTERNAL_EXCEPTION,fatal:!1,event:t,err:e})}},t}();e.a=u},function(t,e,r){"use strict";function i(){return"undefined"==typeof window?self:window}e.a=i},function(t,e,r){!function(e){var r=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/,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,c=d.substring(0,d.lastIndexOf("/")+1)+n.path;u.path=o.normalizePath(c)}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";var i={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}};e.a=i},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,!0),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=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t.length,i=void 0,a=void 0,n=void 0,o="",s=0;s<r;){if(0===(i=t[s++])&&e)return o;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:a=t[s++],o+=String.fromCharCode((31&i)<<6|63&a);break;case 14:a=t[s++],n=t[s++],o+=String.fromCharCode((15&i)<<12|(63&a)<<6|(63&n)<<0)}}return o},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)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)}var o=r(3),s=function(t){function e(r){i(this,e);for(var n=arguments.length,o=Array(n>1?n-1:0),s=1;s<n;s++)o[s-1]=arguments[s];var l=a(this,t.call.apply(t,[this,r].concat(o)));return l._tickInterval=null,l._tickTimer=null,l._tickCallCount=0,l._boundTick=l.tick.bind(l),l}return n(e,t),e.prototype.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.prototype.hasInterval=function(){return!!this._tickInterval},e.prototype.hasNextTick=function(){return!!this._tickTimer},e.prototype.setInterval=function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(t){return!this._tickInterval&&(this._tickInterval=setInterval(this._boundTick,t),!0)}),e.prototype.clearInterval=function(t){function e(){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(){return!!this._tickInterval&&(clearInterval(this._tickInterval),this._tickInterval=null,!0)}),e.prototype.clearNextTick=function(){return!!this._tickTimer&&(clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.prototype.tick=function(){1===++this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&(this.clearNextTick(),this._tickTimer=setTimeout(this._boundTick,0)),this._tickCallCount=0)},e.prototype.doTick=function(){},e}(o.a);e.a=s},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(5),n=r.n(a),o=r(18),s=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}}(),l=function(){function t(){var e;i(this,t),this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this._elementaryStreams=(e={},e[t.ElementaryStreamTypes.AUDIO]=!1,e[t.ElementaryStreamTypes.VIDEO]=!1,e)}return t.prototype.addElementaryStream=function(t){this._elementaryStreams[t]=!0},t.prototype.hasElementaryStream=function(t){return!0===this._elementaryStreams[t]},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 o.a,r.method=t.method,r.baseuri=t.baseuri,r.reluri=t.reluri,r.iv=this.createInitializationVector(e)),r},s(t,[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=n.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&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;var t=[];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],this._byteRange=t}return t}},{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}},{key:"encrypted",get:function(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}}],[{key:"ElementaryStreamTypes",get:function(){return{AUDIO:"audio",VIDEO:"video"}}}]),t}();e.a=l},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)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)}r.d(e,"a",function(){return l}),r.d(e,"b",function(){return u});var o=r(3),s=r(1),l={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},u=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,s.a.BUFFER_APPENDED,s.a.FRAG_BUFFERED,s.a.FRAG_LOADED));return n.bufferPadding=.2,n.fragments=Object.create(null),n.timeRanges=Object.create(null),n.config=r.config,n}return n(e,t),e.prototype.destroy=function(){this.fragments=null,this.timeRanges=null,this.config=null,o.a.prototype.destroy.call(this),t.prototype.destroy.call(this)},e.prototype.getBufferedFrag=function(t,e){var r=this.fragments,i=Object.keys(r).filter(function(i){var a=r[i];if(a.body.type!==e)return!1;if(!a.buffered)return!1;var n=a.body;return n.startPTS<=t&&t<=n.endPTS});if(0===i.length)return null;var a=i.pop();return r[a].body},e.prototype.detectEvictedFragments=function(t,e){var r=this,i=void 0,a=void 0;Object.keys(this.fragments).forEach(function(n){var o=r.fragments[n];if(!0===o.buffered){var s=o.range[t];if(s){i=s.time;for(var l=0;l<i.length;l++)if(a=i[l],!1===r.isTimeBuffered(a.startPTS,a.endPTS,e)){r.removeFragment(o.body);break}}}})},e.prototype.detectPartialFragments=function(t){var e=this,r=this.getFragmentKey(t),i=this.fragments[r];i&&(i.buffered=!0,Object.keys(this.timeRanges).forEach(function(r){if(!0===t.hasElementaryStream(r)){var a=e.timeRanges[r];i.range[r]=e.getBufferedTimes(t.startPTS,t.endPTS,a)}}))},e.prototype.getBufferedTimes=function(t,e,r){for(var i=[],a=void 0,n=void 0,o=!1,s=0;s<r.length;s++){if(a=r.start(s)-this.bufferPadding,n=r.end(s)+this.bufferPadding,t>=a&&e<=n){i.push({startPTS:Math.max(t,r.start(s)),endPTS:Math.min(e,r.end(s))});break}if(t<n&&e>a)i.push({startPTS:Math.max(t,r.start(s)),endPTS:Math.min(e,r.end(s))}),o=!0;else if(e<=a)break}return{time:i,partial:o}},e.prototype.getFragmentKey=function(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn},e.prototype.getPartialFragment=function(t){var e=this,r=void 0,i=void 0,a=void 0,n=null,o=0;return Object.keys(this.fragments).forEach(function(s){var l=e.fragments[s];e.isPartial(l)&&(i=l.body.startPTS-e.bufferPadding,a=l.body.endPTS+e.bufferPadding,t>=i&&t<=a&&(r=Math.min(t-i,a-t),o<=r&&(n=l.body,o=r)))}),n},e.prototype.getState=function(t){var e=this.getFragmentKey(t),r=this.fragments[e],i=l.NOT_LOADED;return void 0!==r&&(i=r.buffered?!0===this.isPartial(r)?l.PARTIAL:l.OK:l.APPENDING),i},e.prototype.isPartial=function(t){return!0===t.buffered&&(void 0!==t.range.video&&!0===t.range.video.partial||void 0!==t.range.audio&&!0===t.range.audio.partial)},e.prototype.isTimeBuffered=function(t,e,r){for(var i=void 0,a=void 0,n=0;n<r.length;n++){if(i=r.start(n)-this.bufferPadding,a=r.end(n)+this.bufferPadding,t>=i&&e<=a)return!0;if(e<=i)return!1}return!1},e.prototype.onFragLoaded=function(t){var e=t.frag;if(!isNaN(e.sn)&&!e.bitrateTest){var r=this.getFragmentKey(e),i={body:e,range:Object.create(null),buffered:!1};this.fragments[r]=i}},e.prototype.onBufferAppended=function(t){var e=this;this.timeRanges=t.timeRanges,Object.keys(this.timeRanges).forEach(function(t){var r=e.timeRanges[t];e.detectEvictedFragments(t,r)})},e.prototype.onFragBuffered=function(t){this.detectPartialFragments(t.frag)},e.prototype.hasFragment=function(t){var e=this.getFragmentKey(t);return void 0!==this.fragments[e]},e.prototype.removeFragment=function(t){var e=this.getFragmentKey(t);delete this.fragments[e]},e.prototype.removeAllFragments=function(){this.fragments=Object.create(null)},e}(o.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")}r.d(e,"a",function(){return a});var a=function(){function t(){i(this,t)}return t.isBuffered=function(t,e){try{if(t)for(var r=t.buffered,i=0;i<r.length;i++)if(e>=r.start(i)&&e<=r.end(i))return!0}catch(t){}return!1},t.bufferInfo=function(t,e,r){try{if(t){var i=t.buffered,a=[],n=void 0;for(n=0;n<i.length;n++)a.push({start:i.start(n),end:i.end(n)});return this.bufferedInfo(a,e,r)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}},t.bufferedInfo=function(t,e,r){var i=[],a=void 0,n=void 0,o=void 0,s=void 0,l=void 0;for(t.sort(function(t,e){var r=t.start-e.start;return r||e.end-t.end}),l=0;l<t.length;l++){var u=i.length;if(u){var d=i[u-1].end;t[l].start-d<r?t[l].end>d&&(i[u-1].end=t[l].end):i.push(t[l])}else i.push(t[l])}for(l=0,a=0,n=o=e;l<i.length;l++){var c=i[l].start,h=i[l].end;if(e+r>=c&&e<h)n=c,o=h,a=o-e;else if(e+r<c){s=c;break}}return{len:a,start:n,end:o,nextStart:s}},t}()},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){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(35),n=r(36),o=r(37),s=r(2),l=r(0),u=r(1),d=r(4),c=Object(d.a)(),h=function(){function t(e,r){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=a.removePKCS7Padding,o=void 0===n||n;if(i(this,t),this.logEnabled=!0,this.observer=e,this.config=r,this.removePKCS7Padding=o,o)try{var s=c.crypto;s&&(this.subtle=s.subtle||s.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 s=this;if(this.disableWebCrypto&&this.config.enableSoftwareAES){this.logEnabled&&(l.b.log("JS AES decrypt"),this.logEnabled=!1);var u=this.decryptor;u||(this.decryptor=u=new o.a),u.expandKey(e),i(u.decrypt(t,0,r,this.removePKCS7Padding))}else{this.logEnabled&&(l.b.log("WebCrypto AES decrypt"),this.logEnabled=!1);var d=this.subtle;this.key!==e&&(this.key=e,this.fastAesKey=new n.a(d,e)),this.fastAesKey.expandKey().then(function(n){new a.a(d,r).decrypt(t,n).catch(function(a){s.onWebCryptoError(a,t,e,r,i)}).then(function(t){i(t)})}).catch(function(a){s.onWebCryptoError(a,t,e,r,i)})}},t.prototype.onWebCryptoError=function(t,e,r,i,a){this.config.enableSoftwareAES?(l.b.log("WebCrypto Error, disable WebCrypto API"),this.disableWebCrypto=!0,this.logEnabled=!0,this.decrypt(e,r,i,a)):(l.b.error("decrypting error : "+t.message),this.observer.trigger(u.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.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=h},function(t,e,r){"use strict";function i(){if("undefined"!=typeof window)return window.MediaSource||window.WebKitMediaSource}e.a=i},function(t,e,r){"use strict";function i(t,e,r){switch(e){case"audio":t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds.push(r);break;case"text":t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds.push(r)}}function a(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&&s.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&&s.b.warn("negative duration computed for frag "+a.sn+",level "+a.level+", there should be some duration drift between playlist and fragment!"))}function n(t,e,r,i,n,o){var s=r;if(!isNaN(e.startPTS)){var l=Math.abs(e.startPTS-r);isNaN(e.deltaPTS)?e.deltaPTS=l:e.deltaPTS=Math.max(l,e.deltaPTS),s=Math.max(r,e.startPTS),r=Math.min(r,e.startPTS),i=Math.max(i,e.endPTS),n=Math.min(n,e.startDTS),o=Math.max(o,e.endDTS)}var u=r-e.start;e.start=e.startPTS=r,e.maxStartPTS=s,e.endPTS=i,e.startDTS=n,e.endDTS=o,e.duration=i-r;var d=e.sn;if(!t||d<t.startSN||d>t.endSN)return 0;var c=void 0,h=void 0,f=void 0;for(c=d-t.startSN,h=t.fragments,h[c]=e,f=c;f>0;f--)a(h,f,f-1);for(f=c;f<h.length-1;f++)a(h,f,f+1);return t.PTSKnown=!0,u}function o(t,e){var r=Math.max(t.startSN,e.startSN)-e.startSN,i=Math.min(t.endSN,e.endSN)-e.startSN,a=e.startSN-t.startSN,o=t.fragments,l=e.fragments,u=0,d=void 0;if(e.initSegment&&t.initSegment&&(e.initSegment=t.initSegment),i<r)return void(e.PTSKnown=!1);for(var c=r;c<=i;c++){var h=o[a+c],f=l[c];f&&h&&(u=h.cc-f.cc,isNaN(h.startPTS)||(f.start=f.startPTS=h.startPTS,f.endPTS=h.endPTS,f.duration=h.duration,f.backtracked=h.backtracked,f.dropped=h.dropped,d=f))}if(u)for(s.b.log("discontinuity sliding from playlist, take drift into account"),c=0;c<l.length;c++)l[c].cc+=u;if(d)n(e,d,d.startPTS,d.endPTS,d.startDTS,d.endDTS);else if(a>=0&&a<o.length){var p=o[a].start;for(c=0;c<l.length;c++)l[c].start+=p}e.PTSKnown=t.PTSKnown}e.a=i,e.c=n,e.b=o;var s=r(0)},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)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)}var o=r(1),s=r(3),l=r(2),u=r(0),d=r(17),c=r(29),h=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}}(),f=window,p=f.performance,v={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},g={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},y=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MANIFEST_LOADING,o.a.LEVEL_LOADING,o.a.AUDIO_TRACK_LOADING,o.a.SUBTITLE_TRACK_LOADING));return n.loaders={},n}return n(e,t),e.canHaveQualityLevels=function(t){return t!==v.AUDIO_TRACK&&t!==v.SUBTITLE_TRACK},e.mapContextToLevelType=function(t){switch(t.type){case v.AUDIO_TRACK:return g.AUDIO;case v.SUBTITLE_TRACK:return g.SUBTITLE;default:return g.MAIN}},e.getResponseUrl=function(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r},e.prototype.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,a=r||i,n=new a(e);return t.loader=n,this.loaders[t.type]=n,n},e.prototype.getInternalLoader=function(t){return this.loaders[t.type]},e.prototype.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.prototype.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.prototype.destroy=function(){this.destroyInternalLoaders(),t.prototype.destroy.call(this)},e.prototype.onManifestLoading=function(t){this.load(t.url,{type:v.MANIFEST,level:0,id:null})},e.prototype.onLevelLoading=function(t){this.load(t.url,{type:v.LEVEL,level:t.level,id:t.id})},e.prototype.onAudioTrackLoading=function(t){this.load(t.url,{type:v.AUDIO_TRACK,level:0,id:t.id})},e.prototype.onSubtitleTrackLoading=function(t){this.load(t.url,{type:v.SUBTITLE_TRACK,level:0,id:t.id})},e.prototype.load=function(t,e){var r=this.hls.config;u.b.debug("Loading playlist of type "+e.type+", level: "+e.level+", id: "+e.id);var i=this.getInternalLoader(e);if(i){var a=i.context;if(a&&a.url===t)return u.b.trace("playlist request ongoing"),!1;u.b.warn("aborting previous loader for type: "+e.type),i.abort()}var n=void 0,o=void 0,s=void 0,l=void 0;switch(e.type){case v.MANIFEST:n=r.manifestLoadingMaxRetry,o=r.manifestLoadingTimeOut,s=r.manifestLoadingRetryDelay,l=r.manifestLoadingMaxRetryTimeout;break;case v.LEVEL:n=0,o=r.levelLoadingTimeOut;break;default:n=r.levelLoadingMaxRetry,o=r.levelLoadingTimeOut,s=r.levelLoadingRetryDelay,l=r.levelLoadingMaxRetryTimeout}i=this.createInternalLoader(e),e.url=t,e.responseType=e.responseType||"";var d={timeout:o,maxRetry:n,retryDelay:s,maxRetryDelay:l},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};return u.b.debug("Calling internal loader delegate for URL: "+t),i.load(e,d,c),!0},e.prototype.loadsuccess=function(t,e,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(r.isSidxRequest)return this._handleSidxRequest(t,r),void this._handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var a=t.data;if(e.tload=p.now(),0!==a.indexOf("#EXTM3U"))return void this._handleManifestParsingError(t,r,"no EXTM3U delimiter",i);a.indexOf("#EXTINF:")>0||a.indexOf("#EXT-X-TARGETDURATION:")>0?this._handleTrackOrLevelPlaylist(t,e,r,i):this._handleMasterPlaylist(t,e,r,i)},e.prototype.loaderror=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this._handleNetworkError(e,r)},e.prototype.loadtimeout=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this._handleNetworkError(e,r,!0)},e.prototype._handleMasterPlaylist=function(t,r,i,a){var n=this.hls,s=t.data,l=e.getResponseUrl(t,i),d=c.a.parseMasterPlaylist(s,l);if(!d.length)return void this._handleManifestParsingError(t,i,"no level found in manifest",a);var h=d.map(function(t){return{id:t.attrs.AUDIO,codec:t.audioCodec}}),f=c.a.parseMasterPlaylistMedia(s,l,"AUDIO",h),p=c.a.parseMasterPlaylistMedia(s,l,"SUBTITLES");if(f.length){var v=!1;f.forEach(function(t){t.url||(v=!0)}),!1===v&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(u.b.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),f.unshift({type:"main",name:"main"}))}n.trigger(o.a.MANIFEST_LOADED,{levels:d,audioTracks:f,subtitles:p,url:l,stats:r,networkDetails:a})},e.prototype._handleTrackOrLevelPlaylist=function(t,r,i,a){var n=this.hls,s=i.id,l=i.level,u=i.type,d=e.getResponseUrl(t,i),h=isNaN(s)?0:s,f=isNaN(l)?h:l,g=e.mapContextToLevelType(i),y=c.a.parseLevelPlaylist(t.data,d,f,g,h);if(y.tload=r.tload,u===v.MANIFEST){var m={url:d,details:y};n.trigger(o.a.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:d,stats:r,networkDetails:a})}if(r.tparsed=p.now(),y.needSidxRanges){var b=y.initSegment.url;return void this.load(b,{isSidxRequest:!0,type:u,level:l,levelDetails:y,id:s,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer"})}i.levelDetails=y,this._handlePlaylistLoaded(t,r,i,a)},e.prototype._handleSidxRequest=function(t,e){var r=d.a.parseSegmentIndex(new Uint8Array(t.data));r.references.forEach(function(t,r){var i=t.info,a=e.levelDetails.fragments[r];0===a.byteRange.length&&(a.rawByteRange=String(1+i.end-i.start)+"@"+String(i.start))}),e.levelDetails.initSegment.rawByteRange=String(r.moovEndOffset)+"@0"},e.prototype._handleManifestParsingError=function(t,e,r,i){this.hls.trigger(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.a.MANIFEST_PARSING_ERROR,fatal:!0,url:t.url,reason:r,networkDetails:i})},e.prototype._handleNetworkError=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];u.b.info("A network error occured while loading a "+t.type+"-type playlist");var i=void 0,a=void 0,n=this.getInternalLoader(t);switch(t.type){case v.MANIFEST:i=r?l.a.MANIFEST_LOAD_TIMEOUT:l.a.MANIFEST_LOAD_ERROR,a=!0;break;case v.LEVEL:i=r?l.a.LEVEL_LOAD_TIMEOUT:l.a.LEVEL_LOAD_ERROR,a=!1;break;case v.AUDIO_TRACK:i=r?l.a.AUDIO_TRACK_LOAD_TIMEOUT:l.a.AUDIO_TRACK_LOAD_ERROR,a=!1;break;default:a=!1}n&&(n.abort(),this.resetInternalLoader(t.type)),this.hls.trigger(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:i,fatal:a,url:n.url,loader:n,context:t,networkDetails:e})},e.prototype._handlePlaylistLoaded=function(t,r,i,a){var n=i.type,s=i.level,l=i.id,u=i.levelDetails;if(!u.targetduration)return void this._handleManifestParsingError(t,i,"invalid target duration",a);if(e.canHaveQualityLevels(i.type))this.hls.trigger(o.a.LEVEL_LOADED,{details:u,level:s||0,id:l||0,stats:r,networkDetails:a});else switch(n){case v.AUDIO_TRACK:this.hls.trigger(o.a.AUDIO_TRACK_LOADED,{details:u,id:l,stats:r,networkDetails:a});break;case v.SUBTITLE_TRACK:this.hls.trigger(o.a.SUBTITLE_TRACK_LOADED,{details:u,id:l,stats:r,networkDetails:a})}},h(e,null,[{key:"ContextType",get:function(){return v}},{key:"LevelType",get:function(){return g}}]),e}(s.a);e.a=y},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(0),n=r(1),o=Math.pow(2,32)-1,s=function(){function t(e,r){i(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 o=this.initData=t.parseInitSegment(e);null==r&&(r="mp4a.40.5"),null==i&&(i="avc1.42e01e");var s={};o.audio&&o.video?s.audiovideo={container:"video/mp4",codec:r+","+i,initSegment:a?e:null}:(o.audio&&(s.audio={container:"audio/mp4",codec:r,initSegment:a?e:null}),o.video&&(s.video={container:"video/mp4",codec:i,initSegment:a?e:null})),this.observer.trigger(n.a.FRAG_PARSING_INIT_SEGMENT,{tracks:s})}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.readUint16=function(t,e){t.data&&(e+=t.start,t=t.data);var r=t[e]<<8|t[e+1];return r<0?65536+r:r},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=void 0,n=void 0,o=void 0,s=void 0,l=void 0,u=void 0,d=void 0;if(e.data?(u=e.start,s=e.end,e=e.data):(u=0,s=e.byteLength),!r.length)return null;for(a=u;a<s;)n=t.readUint32(e,a),o=t.bin2str(e.subarray(a+4,a+8)),d=n>1?a+n:s,o===r[0]&&(1===r.length?i.push({data:e,start:a+8,end:d}):(l=t.findBox({data:e,start:a+8,end:d},r.slice(1)),l.length&&(i=i.concat(l)))),a=d;return i},t.parseSegmentIndex=function(e){var r=t.findBox(e,["moov"])[0],i=r?r.end:null,a=0,n=t.findBox(e,["sidx"]),o=void 0;if(!n||!n[0])return null;o=[],n=n[0];var s=n.data[0];a=0===s?8:16;var l=t.readUint32(n,a);a+=4;a+=0===s?8:16,a+=2;var u=n.end+0,d=t.readUint16(n,a);a+=2;for(var c=0;c<d;c++){var h=a,f=t.readUint32(n,h);h+=4;var p=2147483647&f;if(1===(2147483648&f)>>>31)return void console.warn("SIDX has hierarchical references (not supported)");var v=t.readUint32(n,h);h+=4,o.push({referenceSize:p,subsegmentDuration:v,info:{duration:v/l,start:u,end:u+p-1}}),u+=p,h+=4,a=h}return{earliestPresentationTime:0,timescale:l,version:s,referencesCount:d,references:o,moovEndOffset:i}},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 n=i.data[i.start],o=0===n?12:20,s=t.readUint32(i,o),l=t.findBox(e,["mdia","mdhd"])[0];if(l){n=l.data[l.start],o=0===n?12:20;var u=t.readUint32(l,o),d=t.findBox(e,["mdia","hdlr"])[0];if(d){var c=t.bin2str(d.data.subarray(d.start+8,d.start+12)),h={soun:"audio",vide:"video"}[c];if(h){var f=t.findBox(e,["mdia","minf","stbl","stsd"]);if(f.length){f=f[0];var p=t.bin2str(f.data.subarray(f.start+12,f.start+16));a.b.log("MP4Demuxer:"+h+":"+p+" found")}r[s]={timescale:u,type:h},r[h]={timescale:u,id:s}}}}}}),r},t.getStartDTS=function(e,r){var i=void 0,a=void 0,n=void 0;return i=t.findBox(r,["moof","traf"]),a=[].concat.apply([],i.map(function(r){return t.findBox(r,["tfhd"]).map(function(i){var a=void 0,n=void 0;return a=t.readUint32(i,4),n=e[a].timescale||9e4,t.findBox(r,["tfdt"]).map(function(e){var r=void 0,i=void 0;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),s=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*s);else{a*=Math.pow(2,32),a+=t.readUint32(e,8),a-=i*s,a=Math.max(a,0);var n=Math.floor(a/(o+1)),l=Math.floor(a%(o+1));t.writeUint32(e,4,n),t.writeUint32(e,8,l)}})})})},t.prototype.append=function(e,r,i,a){var o=this.initData;o||(this.resetInitSegment(e,this.audioCodec,this.videoCodec,!1),o=this.initData);var s=void 0,l=this.initPTS;if(void 0===l){var u=t.getStartDTS(o,e);this.initPTS=l=u-r,this.observer.trigger(n.a.INIT_PTS_FOUND,{initPTS:l})}t.offsetStartDTS(o,e,l),s=t.getStartDTS(o,e),this.remuxer.remux(o.audio,o.video,null,null,s,i,a,e)},t.prototype.destroy=function(){},t}();e.a=s},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(5),n=r.n(a),o=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}}(),s=function(){function t(){i(this,t),this.method=null,this.key=null,this.iv=null,this._uri=null}return o(t,[{key:"uri",get:function(){return!this._uri&&this.reluri&&(this._uri=n.a.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}]),t}();e.a=s},function(t,e,r){"use strict";function i(t,e){var r=n[e];return!!r&&!0===r[t.slice(0,4)]}function a(t,e){return window.MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}r.d(e,"b",function(){return i}),r.d(e,"a",function(){return a});var n={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}}},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(12),n=r.n(a),o=r(34),s=r.n(o),l=r(1),u=r(21),d=r(0),c=r(2),h=r(14),f=r(4),p=Object(f.a)(),v=Object(h.a)(),g=function(){function t(e,r){i(this,t),this.hls=e,this.id=r;var a=this.observer=new n.a,o=e.config;a.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];a.emit.apply(a,[t,t].concat(r))},a.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];a.removeListener.apply(a,[t].concat(r))};var h=function(t,r){r=r||{},r.frag=this.frag,r.id=this.id,e.trigger(t,r)}.bind(this);a.on(l.a.FRAG_DECRYPTED,h),a.on(l.a.FRAG_PARSING_INIT_SEGMENT,h),a.on(l.a.FRAG_PARSING_DATA,h),a.on(l.a.FRAG_PARSED,h),a.on(l.a.ERROR,h),a.on(l.a.FRAG_PARSING_METADATA,h),a.on(l.a.FRAG_PARSING_USERDATA,h),a.on(l.a.INIT_PTS_FOUND,h);var f={mp4:v.isTypeSupported("video/mp4"),mpeg:v.isTypeSupported("audio/mpeg"),mp3:v.isTypeSupported('audio/mp4; codecs="mp3"')},g=navigator.vendor;if(o.enableWorker&&"undefined"!=typeof Worker){d.b.log("demuxing in webworker");var y=void 0;try{y=this.w=s()(47),this.onwmsg=this.onWorkerMessage.bind(this),y.addEventListener("message",this.onwmsg),y.onerror=function(t){e.trigger(l.a.ERROR,{type:c.b.OTHER_ERROR,details:c.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",err:{message:t.message+" ("+t.filename+":"+t.lineno+")"}})},y.postMessage({cmd:"init",typeSupported:f,vendor:g,id:r,config:JSON.stringify(o)})}catch(t){d.b.error("error while initializing DemuxerWorker, fallback on DemuxerInline"),y&&p.URL.revokeObjectURL(y.objectURL),this.demuxer=new u.a(a,f,o,g),this.w=void 0}}else this.demuxer=new u.a(a,f,o,g)}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,c=a.decryptdata,h=this.frag,f=!(h&&a.cc===h.cc),p=!(h&&a.level===h.level),v=h&&a.sn===h.sn+1,g=!p&&v;if(f&&d.b.log(this.id+":discontinuity detected"),p&&d.b.log(this.id+":switch detected"),this.frag=a,l)l.postMessage({cmd:"demux",data:t,decryptdata:c,initSegment:e,audioCodec:r,videoCodec:i,timeOffset:u,discontinuity:f,trackSwitch:p,contiguous:g,duration:n,accurateTimeOffset:o,defaultInitPTS:s},t instanceof ArrayBuffer?[t]:[]);else{var y=this.demuxer;y&&y.push(t,c,e,r,i,u,f,p,g,n,o,s)}},t.prototype.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":p.URL.revokeObjectURL(this.w.objectURL);break;case l.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}();e.a=g},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(1),n=r(2),o=r(13),s=r(38),l=r(17),u=r(39),d=r(42),c=r(43),h=r(46),f=r(4),p=Object(f.a)(),v=p,g=function(){function t(e,r,a,n){i(this,t),this.observer=e,this.typeSupported=r,this.config=a,this.vendor=n}return t.prototype.destroy=function(){var t=this.demuxer;t&&t.destroy()},t.prototype.push=function(t,e,r,i,n,s,l,u,d,c,h,f){if(t.byteLength>0&&null!=e&&null!=e.key&&"AES-128"===e.method){var p=this.decrypter;null==p&&(p=this.decrypter=new o.a(this.observer,this.config));var g=this,y=void 0;try{y=v.now()}catch(t){y=Date.now()}p.decrypt(t,e.key.buffer,e.iv.buffer,function(t){var o=void 0;try{o=v.now()}catch(t){o=Date.now()}g.observer.trigger(a.a.FRAG_DECRYPTED,{stats:{tstart:y,tdecrypt:o}}),g.pushDecrypted(new Uint8Array(t),e,new Uint8Array(r),i,n,s,l,u,d,c,h,f)})}else this.pushDecrypted(new Uint8Array(t),e,new Uint8Array(r),i,n,s,l,u,d,c,h,f)},t.prototype.pushDecrypted=function(t,e,r,i,o,f,p,v,g,y,m,b){var E=this.demuxer;if(!E||(p||v)&&!this.probe(t)){for(var T=this.observer,S=this.typeSupported,R=this.config,A=[{demux:u.a,remux:c.a},{demux:l.a,remux:h.a},{demux:s.a,remux:c.a},{demux:d.a,remux:c.a}],_=0,w=A.length;_<w;_++){var L=A[_],D=L.demux.probe;if(D(t)){var I=this.remuxer=new L.remux(T,R,S,this.vendor);E=new L.demux(T,I,R,S),this.probe=D;break}}if(!E)return void T.trigger(a.a.ERROR,{type:n.b.MEDIA_ERROR,details:n.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"});this.demuxer=E}var k=this.remuxer;(p||v)&&(E.resetInitSegment(r,i,o,y),k.resetInitSegment()),p&&(E.resetTimeStamp(b),k.resetTimeStamp(b)),"function"==typeof E.setDecryptData&&E.setDecryptData(e),E.append(t,f,g,m)},t}();e.a=g},function(t,e,r){"use strict";function i(t,e,r,i){var a=void 0,n=void 0,o=void 0,s=void 0,l=void 0,u=navigator.userAgent.toLowerCase(),d=i,c=[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)>c.length-1?void t.trigger(v.a.ERROR,{type:p.b.MEDIA_ERROR,details:p.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+n}):(s=(1&e[r+2])<<2,s|=(192&e[r+3])>>>6,f.b.log("manifest codec:"+i+",ADTS data:type:"+a+",sampleingIndex:"+n+"["+c[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:c[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,f.b.log("parsed codec:"+t.codec+",rate:"+o.samplerate+",nb channel:"+o.channelCount)}}function d(t){return 9216e4/t}function c(t,e,r,i,a){var s=void 0,l=void 0,u=void 0,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 h(t,e,r,i,a){var n=d(t.samplerate),o=c(e,r,i,a,n);if(o){var s=o.stamp,l=o.headerLength,u=o.frameLength,h={unit:e.subarray(r+l,r+l+u),pts:s,dts:s};return t.samples.push(h),t.len+=u,{sample:h,length:u+l}}}e.d=s,e.e=l,e.c=u,e.b=d,e.a=h;var f=r(0),p=r(2),v=r(1);r(4)},function(t,e,r){"use strict";var i={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],SamplesCoefficients:[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot:[0,1,1,4],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=9e4*n.samplesPerFrame/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,a=t[e+1]>>1&3,n=t[e+2]>>4&15,o=t[e+2]>>2&3,s=t[e+2]>>1&1;if(1!==r&&0!==n&&15!==n&&3!==o){var l=3===r?3-a:3===a?3:4,u=1e3*i.BitratesMap[14*l+n-1],d=3===r?0:2===r?1:2,c=i.SamplingRateMap[3*d+o],h=t[e+3]>>6==3?1:2,f=i.SamplesCoefficients[r][a],p=i.BytesInSlot[a],v=8*f*p;return{sampleRate:c,channelCount:h,frameLength:parseInt(f*u/c+s,10)*p,samplesPerFrame:v}}},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}};e.a=i},function(t,e,r){"use strict";var i={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}};e.a=i},function(t,e,r){"use strict";function i(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 u.a.search(t,function(t){return t.cc<e?1:t.cc>e?-1:0})}function n(t,e,r){var i=!1;return e&&e.details&&r&&(r.endCC>r.startCC||t&&t.cc<r.startCC)&&(i=!0),i}function o(t,e){var r=t.fragments,a=e.fragments;if(!a.length||!r.length)return void d.b.log("No fragments to align");var n=i(r,a[0].cc);return!n||n&&!n.startPTS?void d.b.log("No frag in previous level to align on"):n}function s(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 l(t,e,r){if(n(t,e,r)){var i=o(e.details,r);i&&(d.b.log("Adjusting PTS using last level due to CC increase within current level"),s(i.start,r))}if(!1===r.PTSKnown&&e&&e.details&&e.details.fragments&&e.details.fragments.length){var a=e.details.programDateTime,l=r.programDateTime,u=(l-a)/1e3+e.details.fragments[0].start;isNaN(u)||(d.b.log("adjusting PTS using programDateTime delta, sliding:"+u.toFixed(3)),s(u,r))}}e.b=a,e.a=l;var u=r(6),d=r(0)},function(t,e,r){"use strict";function i(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)}function a(t){if(t&&t.cues)for(;t.cues.length>0;)t.removeCue(t.cues[0])}e.b=i,e.a=a},function(t,e,r){"use strict";function i(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new d,this.regionList=[]}function a(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 n(){this.values=Object.create(null)}function o(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 s(t,e,r){function i(){var e=a(t);if(null===e)throw new Error("Malformed timestamp: "+l);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function s(){t=t.replace(/^\s+/,"")}var l=t;if(s(),e.startTime=i(),s(),"--\x3e"!==t.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+l);t=t.substr(3),s(),e.endTime=i(),s(),function(t,e){var i=new n;o(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",h,"end"]);break;case"position":n=e.split(","),i.percent(t,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",h,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",h,"end","left","right"])}},/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");var a=i.get("line","auto");"auto"===a&&-1===c.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",h);var s=i.get("position","auto");"auto"===s&&50===c.position&&(s="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=s}(t,e)}function l(t){return t.replace(/<br(?: \/)?>/gi,"\n")}r.d(e,"b",function(){return l});var u=r(63),d=function(){return{decode:function(t){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}};n.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 c=new u.a(0,0,0),h="middle"===c.align?"middle":"center";i.prototype={parse:function(t){function e(){var t=r.buffer,e=0;for(t=l(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=void 0;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){o(t,function(t,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 u.a(0,0,""),r.state="CUE",-1===i.indexOf("--\x3e")){r.cue.id=i;continue}case"CUE":try{s(i,r.cue,r.regionList)}catch(t){r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":var d=-1!==i.indexOf("--\x3e");if(!i||d&&(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}},e.a=i},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var a=r(5),n=r.n(a),o=r(2),s=r(16),l=r(31),u=r(32),d=r(10),c=r(33),h=r(49),f=r(50),p=r(51),v=r(0),g=r(52),y=r(1),m=r(12),b=r.n(m),E=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}}();r(72);var T=function(){function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(this,t);var a=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 n in a)n in r||(r[n]=a[n]);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(v.a)(r.debug),this.config=r,this._autoLevelCapping=-1;var o=this.observer=new b.a;o.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];o.emit.apply(o,[t,t].concat(r))},o.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];o.removeListener.apply(o,[t].concat(r))},this.on=o.on.bind(o),this.off=o.off.bind(o),this.once=o.once.bind(o),this.trigger=o.trigger.bind(o);var p=this.abrController=new r.abrController(this),g=new r.bufferController(this),y=new r.capLevelController(this),m=new r.fpsController(this),E=new s.a(this),T=new l.a(this),S=new u.a(this),R=new f.a(this),A=this.levelController=new h.a(this),_=new d.b(this),w=this.streamController=new c.a(this,_),L=[A,w],D=r.audioStreamController;D&&L.push(new D(this,_)),this.networkControllers=L;var I=[E,T,S,p,g,y,m,R,_];if(D=r.audioTrackController){var k=new D(this);this.audioTrackController=k,I.push(k)}if(D=r.subtitleTrackController){var O=new D(this);this.subtitleTrackController=O,I.push(O)}if(D=r.emeController){var C=new D(this);this.emeController=C,I.push(C)}[r.subtitleStreamController,r.timelineController].forEach(function(t){t&&I.push(new t(e))}),this.coreComponents=I}return t.isSupported=function(){return Object(p.a)()},E(t,null,[{key:"version",get:function(){return"0.10.0"}},{key:"Events",get:function(){return y.a}},{key:"ErrorTypes",get:function(){return o.b}},{key:"ErrorDetails",get:function(){return o.a}},{key:"DefaultConfig",get:function(){return t.defaultConfig?t.defaultConfig:g.a},set:function(e){t.defaultConfig=e}}]),t.prototype.destroy=function(){v.b.log("destroy"),this.trigger(y.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){v.b.log("attachMedia"),this.media=t,this.trigger(y.a.MEDIA_ATTACHING,{media:t})},t.prototype.detachMedia=function(){v.b.log("detachMedia"),this.trigger(y.a.MEDIA_DETACHING),this.media=null},t.prototype.loadSource=function(t){t=n.a.buildAbsoluteURL(window.location.href,t,{alwaysNormalize:!0}),v.b.log("loadSource:"+t),this.url=t,this.trigger(y.a.MANIFEST_LOADING,{url:t})},t.prototype.startLoad=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;v.b.log("startLoad("+t+")"),this.networkControllers.forEach(function(e){e.startLoad(t)})},t.prototype.stopLoad=function(){v.b.log("stopLoad"),this.networkControllers.forEach(function(t){t.stopLoad()})},t.prototype.swapAudioCodec=function(){v.b.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.prototype.recoverMediaError=function(){v.b.log("recoverMediaError");var t=this.media;this.detachMedia(),this.attachMedia(t)},E(t,[{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){v.b.log("set currentLevel:"+t),this.loadLevel=t,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){v.b.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){v.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){v.b.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(t){v.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){v.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=T},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(5),n=r.n(a),o=r(9),s=r(18),l=r(30),u=r(0),d=r(19),c=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,h=/#EXT-X-MEDIA:(.*)/g,f=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)(\S+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),p=/(?:(?:#(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?/,v=/\.(mp4|m4s|m4v|m4a)$/i,g=function(){function t(){i(this,t)}return t.findGroup=function(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},t.convertAVC1ToAVCOTI=function(t){var e=void 0,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},t.resolve=function(t,e){return n.a.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i=[],a=void 0;for(c.lastIndex=0;null!=(a=c.exec(e));){var n={},o=n.attrs=new l.a(a[1]);n.url=t.resolve(a[2],r);var s=o.decimalResolution("RESOLUTION");s&&(n.width=s.width,n.height=s.height),n.bitrate=o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),n.name=o.NAME,function(t,e){["video","audio"].forEach(function(r){var i=t.filter(function(t){return Object(d.b)(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(/[ ,]+/)),n),n.videoCodec&&-1!==n.videoCodec.indexOf("avc1")&&(n.videoCodec=t.convertAVC1ToAVCOTI(n.videoCodec)),i.push(n)}return i},t.parseMasterPlaylistMedia=function(e,r,i){var a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],n=void 0,o=[],s=0;for(h.lastIndex=0;null!==(n=h.exec(e));){var u={},d=new l.a(n[1]);if(d.TYPE===i){if(u.groupId=d["GROUP-ID"],u.name=d.NAME,u.type=i,u.default="YES"===d.DEFAULT,u.autoselect="YES"===d.AUTOSELECT,u.forced="YES"===d.FORCED,d.URI&&(u.url=t.resolve(d.URI,r)),u.lang=d.LANGUAGE,u.name||(u.name=u.lang),a.length){var c=t.findGroup(a,u.groupId);u.audioCodec=c?c.codec:a[0].codec}u.id=s++,o.push(u)}}return o},t.parseLevelPlaylist=function(t,e,r,i,a){var n=0,d=0,c={type:null,version:null,url:e,fragments:[],live:!0,startSN:0},h=new s.a,g=0,y=null,m=new o.a,b=void 0,E=void 0;for(f.lastIndex=0;null!==(b=f.exec(t));){var T=b[1];if(T){m.duration=parseFloat(T);var S=(" "+b[2]).slice(1);m.title=S||null,m.tagList.push(S?["INF",T,S]:["INF",T])}else if(b[3]){if(!isNaN(m.duration)){var R=n++;m.type=i,m.start=d,m.levelkey=h,m.sn=R,m.level=r,m.cc=g,m.urlId=a,m.baseurl=e,m.relurl=(" "+b[3]).slice(1),c.programDateTime&&(y?m.rawProgramDateTime?m.pdt=Date.parse(m.rawProgramDateTime):m.pdt=y.pdt+1e3*y.duration:m.pdt=Date.parse(c.programDateTime),m.endPdt=m.pdt+1e3*m.duration),c.fragments.push(m),y=m,d+=m.duration,m=new o.a}}else if(b[4]){if(m.rawByteRange=(" "+b[4]).slice(1),y){var A=y.byteRangeEndOffset;A&&(m.lastByteRangeEndOffset=A)}}else if(b[5])m.rawProgramDateTime=(" "+b[5]).slice(1),m.tagList.push(["PROGRAM-DATE-TIME",m.rawProgramDateTime]),void 0===c.programDateTime&&(c.programDateTime=new Date(new Date(Date.parse(b[5]))-1e3*d));else{for(b=b[0].match(p),E=1;E<b.length&&void 0===b[E];E++);var _=(" "+b[E+1]).slice(1),w=(" "+b[E+2]).slice(1);switch(b[E]){case"#":m.tagList.push(w?[_,w]:[_]);break;case"PLAYLIST-TYPE":c.type=_.toUpperCase();break;case"MEDIA-SEQUENCE":n=c.startSN=parseInt(_);break;case"TARGETDURATION":c.targetduration=parseFloat(_);break;case"VERSION":c.version=parseInt(_);break;case"EXTM3U":break;case"ENDLIST":c.live=!1;break;case"DIS":g++,m.tagList.push(["DIS"]);break;case"DISCONTINUITY-SEQ":g=parseInt(_);break;case"KEY":var L=_,D=new l.a(L),I=D.enumeratedString("METHOD"),k=D.URI,O=D.hexadecimalInteger("IV");I&&(h=new s.a,k&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(I)>=0&&(h.method=I,h.baseuri=e,h.reluri=k,h.key=null,h.iv=O));break;case"START":var C=_,P=new l.a(C),x=P.decimalFloatingPoint("TIME-OFFSET");isNaN(x)||(c.startTimeOffset=x);break;case"MAP":var F=new l.a(_);m.relurl=F.URI,m.rawByteRange=F.BYTERANGE,m.baseurl=e,m.level=r,m.type=i,m.sn="initSegment",c.initSegment=m,m=new o.a;break;default:u.b.warn("line parsed but not handled: "+b)}}}return m=y,m&&!m.relurl&&(c.fragments.pop(),d-=m.duration),c.totalduration=d,c.averagetargetduration=d/c.fragments.length,c.endSN=n-1,c.startCC=c.fragments[0]?c.fragments[0].cc:0,c.endCC=g,!c.initSegment&&c.fragments.length&&c.fragments.every(function(t){return v.test(t.relurl)})&&(u.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),m=new o.a,m.relurl=c.fragments[0].relurl,m.baseurl=e,m.level=r,m.type=i,m.sn="initSegment",c.initSegment=m,c.needSidxRanges=!0),c},t}();e.a=g},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=/^(\d+)x(\d+)$/,n=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,o=function(){function t(e){i(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=a.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e=void 0,r={};for(n.lastIndex=0;null!==(e=n.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}();e.a=o},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)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)}var o=r(1),s=r(3),l=r(2),u=r(0),d=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.FRAG_LOADING));return n.loaders={},n}return n(e,t),e.prototype.destroy=function(){var e=this.loaders;for(var r in e){var i=e[r];i&&i.destroy()}this.loaders={},t.prototype.destroy.call(this)},e.prototype.onFragLoading=function(t){var e=t.frag,r=e.type,i=this.loaders,a=this.hls.config,n=a.fLoader,o=a.loader;e.loaded=0;var s=i[r];s&&(u.b.warn("abort previous fragment loader for type: "+r),s.abort()),s=i[r]=e.loader=a.fLoader?new n(a):new o(a);var l=void 0,d=void 0,c=void 0;l={url:e.url,frag:e,responseType:"arraybuffer",progressData:!1};var h=e.byteRangeStartOffset,f=e.byteRangeEndOffset;isNaN(h)||isNaN(f)||(l.rangeStart=h,l.rangeEnd=f),d={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},s.load(l,d,c)},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(o.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(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.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(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.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(o.a.FRAG_LOAD_PROGRESS,{frag:a,stats:t,networkDetails:i})},e}(s.a);e.a=d},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)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)}var o=r(1),s=r(3),l=r(2),u=r(0),d=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.KEY_LOADING));return n.loaders={},n.decryptkey=null,n.decrypturl=null,n}return n(e,t),e.prototype.destroy=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={},s.a.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 s=this.hls.config;i&&(u.b.warn("abort previous key loader for type:"+r),i.abort()),e.loader=this.loaders[r]=new s.loader(s),this.decrypturl=n,this.decryptkey=null;var l=void 0,d=void 0,c=void 0;l={url:n,frag:e,responseType:"arraybuffer"},d={timeout:s.fragLoadingTimeOut,maxRetry:s.fragLoadingMaxRetry,retryDelay:s.fragLoadingRetryDelay,maxRetryDelay:s.fragLoadingMaxRetryTimeout},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)},e.loader.load(l,d,c)}else this.decryptkey&&(a.key=this.decryptkey,this.hls.trigger(o.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(o.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(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.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(o.a.ERROR,{type:l.b.NETWORK_ERROR,details:l.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},e}(s.a);e.a=d},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)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)}var o=r(6),s=r(11),l=r(20),u=r(1),d=r(10),c=r(9),h=r(16),f=r(15),p=r(24),v=r(2),g=r(0),y=r(25),m=r(8),b=r(48),E=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}}(),T={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"},S=function(t){function e(r,n){i(this,e);var o=a(this,t.call(this,r,u.a.MEDIA_ATTACHED,u.a.MEDIA_DETACHING,u.a.MANIFEST_LOADING,u.a.MANIFEST_PARSED,u.a.LEVEL_LOADED,u.a.KEY_LOADED,u.a.FRAG_LOADED,u.a.FRAG_LOAD_EMERGENCY_ABORTED,u.a.FRAG_PARSING_INIT_SEGMENT,u.a.FRAG_PARSING_DATA,u.a.FRAG_PARSED,u.a.ERROR,u.a.AUDIO_TRACK_SWITCHING,u.a.AUDIO_TRACK_SWITCHED,u.a.BUFFER_CREATED,u.a.BUFFER_APPENDED,u.a.BUFFER_FLUSHED));return o.fragmentTracker=n,o.config=r.config,o.audioCodecSwap=!1,o._state=T.STOPPED,o.stallReported=!1,o}return n(e,t),e.prototype.onHandlerDestroying=function(){this.stopLoad(),t.prototype.onHandlerDestroying.call(this)},e.prototype.onHandlerDestroyed=function(){this.state=T.STOPPED,this.fragmentTracker=null,t.prototype.onHandlerDestroyed.call(this)},e.prototype.startLoad=function(t){if(this.levels){var e=this.lastCurrentTime,r=this.hls;if(this.stopLoad(),this.setInterval(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&&(g.b.log("override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=T.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this.forceStartLoad=!0,this.state=T.STOPPED},e.prototype.stopLoad=function(){var t=this.fragCurrent;t&&(t.loader&&t.loader.abort(),this.fragmentTracker.removeFragment(t),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.clearInterval(),this.state=T.STOPPED,this.forceStartLoad=!1},e.prototype.doTick=function(){switch(this.state){case T.BUFFER_FLUSHING:this.fragLoadError=0;break;case T.IDLE:this._doTickIdle();break;case T.WAITING_LEVEL:var t=this.levels[this.level];t&&t.details&&(this.state=T.IDLE);break;case T.FRAG_LOADING_WAITING_RETRY:var e=window.performance.now(),r=this.retryDate;(!r||e>=r||this.media&&this.media.seeking)&&(g.b.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=T.IDLE);break;case T.ERROR:case T.STOPPED:case T.FRAG_LOADING:case T.PARSING:case T.PARSED:case T.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,l=void 0;l=o?Math.max(8*e.maxBufferSize/o,e.maxBufferLength):e.maxBufferLength,l=Math.min(l,e.maxMaxBufferLength);var d=s.a.bufferInfo(this.mediaBuffer?this.mediaBuffer:r,i,e.maxBufferHole),c=d.len;if(!(c>=l)){g.b.trace("buffer length of "+c.toFixed(3)+" is below max of "+l.toFixed(3)+". checking for more payload ..."),this.level=t.nextLoadLevel=a;var h=n.details;if(!h||h.live&&this.levelLastLoaded!==a)return void(this.state=T.WAITING_LEVEL);var f=this.fragPrevious;if(!h.live&&f&&!f.backtracked&&f.sn===h.endSN&&!d.nextStart){if(Math.min(r.duration,f.start+f.duration)-Math.max(d.end,f.start)<=Math.max(.2,f.duration)){var p={};return this.altAudio&&(p.type="video"),this.hls.trigger(u.a.BUFFER_EOS,p),void(this.state=T.ENDED)}}this._fetchPayloadOrEos(i,d,h)}}}},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 c=this.config.initialLiveManifestSize;if(o<c)return void g.b.warn("Can not start playback of a level, reason: not enough fragments "+o+" < "+c);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&&(d.encrypted?(g.b.log("Loading key for "+d.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+a),this._loadKey(d)):(g.b.log("Loading "+d.sn+" of ["+r.startSN+" ,"+r.endSN+"],level "+a+", currentTime:"+t.toFixed(3)+",bufferEnd:"+u.toFixed(3)),this._loadFragment(d)))}},e.prototype._ensureFragmentAtLivePoint=function(t,e,r,i,a,n,s){var l=this.hls.config,u=this.media,d=void 0,c=void 0!==l.liveMaxLatencyDuration?l.liveMaxLatencyDuration:l.liveMaxLatencyDurationCount*t.targetduration;if(e<Math.max(r-l.maxFragLookUpTolerance,i-c)){var h=this.liveSyncPosition=this.computeLivePosition(r,t);g.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,u&&u.readyState&&u.duration>h&&(u.currentTime=h),this.nextLoadPosition=h}if(t.PTSKnown&&e>i&&u&&u.readyState)return null;if(this.startFragRequested&&!t.PTSKnown){if(a)if(t.programDateTime)d=Object(b.b)(n,a.endPdt+1);else{var f=a.sn+1;if(f>=t.startSN&&f<=t.endSN){var p=n[f-t.startSN];a.cc===p.cc&&(d=p,g.b.log("live playlist, switching playlist, load frag with next SN: "+d.sn))}d||(d=o.a.search(n,function(t){return a.cc-t.cc}))&&g.b.log("live playlist, switching playlist, load frag with same CC: "+d.sn)}d||(d=n[Math.min(s-1,Math.round(s/2))],g.b.log("live playlist, switching playlist, unknown, load middle frag : "+d.sn))}return d},e.prototype._findFragment=function(t,e,r,i,a,n,o){var s=this.hls.config,l=void 0,u=void 0;if(a<n?o.programDateTime?(u=Object(b.b)(i,Object(b.a)(t,a,o)))&&!Object(b.d)(a,s.maxFragLookUpTolerance,u)||(g.b.warn("Frag found by PDT search did not fit within tolerance; falling back to finding by SN"),u=function(){return Object(b.c)(e,i,a,n,s.maxFragLookUpTolerance)}()):u=Object(b.c)(e,i,a,n,s.maxFragLookUpTolerance):u=i[r-1],u){l=u;var d=l.sn-o.startSN,c=e&&l.level===e.level,h=i[d-1],f=i[d+1];if(e&&l.sn===e.sn)if(c&&!l.backtracked)if(l.sn<o.endSN){var p=e.deltaPTS;p&&p>s.maxBufferHole&&e.dropped&&d?(l=h,g.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")):(l=f,g.b.log("SN just loaded, load next one: "+l.sn))}else l=null;else l.backtracked&&(f&&f.backtracked?(g.b.warn("Already backtracked from fragment "+f.sn+", will not backtrack to fragment "+l.sn+". Loading fragment "+f.sn),l=f):(g.b.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),l.dropped=0,h?(l=h,l.backtracked=!0):d&&(l=null)))}return l},e.prototype._loadKey=function(t){this.state=T.KEY_LOADING,this.hls.trigger(u.a.KEY_LOADING,{frag:t})},e.prototype._loadFragment=function(t){var e=this.fragmentTracker.getState(t);this.fragCurrent=t,this.startFragRequested=!0,isNaN(t.sn)||t.bitrateTest||(this.nextLoadPosition=t.start+t.duration),t.backtracked||e===d.a.NOT_LOADED||e===d.a.PARTIAL?(t.autoLevel=this.hls.autoLevelEnabled,t.bitrateTest=this.bitrateTest,this.hls.trigger(u.a.FRAG_LOADING,{frag:t}),this.demuxer||(this.demuxer=new l.a(this.hls,"main")),this.state=T.FRAG_LOADING):e===d.a.APPENDING&&this._reduceMaxBufferLength(t.duration)&&this.fragmentTracker.removeFragment(t)},e.prototype.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,h.a.LevelType.MAIN)},e.prototype.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.endPTS+.5):null},e.prototype._checkFragmentChanged=function(){var t=void 0,e=void 0,r=this.media;if(r&&r.readyState&&!1===r.seeking&&(e=r.currentTime,e>this.lastCurrentTime&&(this.lastCurrentTime=e),s.a.isBuffered(r,e)?t=this.getBufferedFrag(e):s.a.isBuffered(r,e+.1)&&(t=this.getBufferedFrag(e+.1)),t)){var i=t;if(i!==this.fragPlaying){this.hls.trigger(u.a.FRAG_CHANGED,{frag:i});var a=i.level;this.fragPlaying&&this.fragPlaying.level===a||this.hls.trigger(u.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=i}}},e.prototype.immediateLevelSwitch=function(){if(g.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,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},e.prototype.immediateLevelSwitchEnd=function(){var t=this.media;t&&t.buffered.length&&(this.immediateSwitch=!1,s.a.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(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=T.BUFFER_FLUSHING;var r={startOffset:t,endOffset:e};this.altAudio&&(r.type="video"),this.hls.trigger(u.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&&(g.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.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)||g.b.log("media seeking to "+e.toFixed(3));var i=this.mediaBuffer?this.mediaBuffer:t,a=s.a.bufferInfo(i,e,this.config.maxBufferHole);if(this.state===T.FRAG_LOADING){var n=this.fragCurrent;if(0===a.len&&n){var o=r.maxFragLookUpTolerance,l=n.start-o,u=n.start+n.duration+o;e<l||e>u?(n.loader&&(g.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=T.IDLE):g.b.log("seeking outside of buffer but within currently loaded fragment range")}}else this.state===T.ENDED&&(0===a.len&&(this.fragPrevious=0),this.state=T.IDLE);t&&(this.lastCurrentTime=e),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)||g.b.log("media seeked to "+e.toFixed(3)),this.tick()},e.prototype.onMediaEnded=function(){g.b.log("media ended"),this.startPosition=this.lastCurrentTime=0},e.prototype.onManifestLoading=function(){g.b.log("trigger BUFFER_RESET"),this.hls.trigger(u.a.BUFFER_RESET),this.fragmentTracker.removeAllFragments(),this.stalled=!1,this.startPosition=this.lastCurrentTime=0},e.prototype.onManifestParsed=function(t){var e=!1,r=!1,i=void 0;t.levels.forEach(function(t){(i=t.audioCodec)&&(-1!==i.indexOf("mp4a.40.2")&&(e=!0),-1!==i.indexOf("mp4a.40.5")&&(r=!0))}),this.audioCodecSwitch=e&&r,this.audioCodecSwitch&&g.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(g.b.log("level "+r+" loaded ["+e.startSN+","+e.endSN+"],duration:"+n),e.live){var s=a.details;s&&e.fragments.length>0?(f.b(s,e),o=e.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(o,s),e.PTSKnown&&!isNaN(o)?g.b.log("live playlist sliding:"+o.toFixed(3)):(g.b.log("live playlist - outdated PTS, unknown sliding"),Object(y.a)(this.fragPrevious,i,e))):(g.b.log("live playlist - first load, unknown sliding"),e.PTSKnown=!1,Object(y.a)(this.fragPrevious,i,e))}else e.PTSKnown=!1;if(a.details=e,this.levelLastLoaded=r,this.hls.trigger(u.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),g.b.log("configure startPosition to "+this.startPosition)):this.startPosition=0:(l<0&&(g.b.log("negative start time offset "+l+", count from end of last fragment"),l=o+n+l),g.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===T.WAITING_LEVEL&&(this.state=T.IDLE),this.tick()},e.prototype.onKeyLoaded=function(){this.state===T.KEY_LOADING&&(this.state=T.IDLE,this.tick())},e.prototype.onFragLoaded=function(t){var e=this.fragCurrent,r=t.frag;if(this.state===T.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(g.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=T.IDLE,this.startFragRequested=!1,i.tparsed=i.tbuffered=window.performance.now(),this.hls.trigger(u.a.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.tick();else if("initSegment"===r.sn)this.state=T.IDLE,i.tparsed=i.tbuffered=window.performance.now(),n.initSegment.data=t.payload,this.hls.trigger(u.a.FRAG_BUFFERED,{stats:i,frag:e,id:"main"}),this.tick();else{this.state=T.PARSING;var o=n.totalduration,s=e.level,d=e.sn,c=this.config.defaultAudioCodec||a.audioCodec;this.audioCodecSwap&&(g.b.log("swapping playlist audio codec"),void 0===c&&(c=this.lastAudioCodec),c&&(c=-1!==c.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),this.pendingBuffering=!0,this.appended=!1,g.b.log("Parsing "+d+" of ["+n.startSN+" ,"+n.endSN+"],level "+s+", cc "+e.cc);var h=this.demuxer;h||(h=this.demuxer=new l.a(this.hls,"main"));var f=this.media,p=f&&f.seeking,v=!p&&(n.PTSKnown||!n.live),y=n.initSegment?n.initSegment.data:[];h.push(t.payload,y,c,a.videoCodec,e,o,v,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===T.PARSING){var i=t.tracks,a=void 0,n=void 0;if(i.audio&&this.altAudio&&delete i.audio,n=i.audio){var o=this.levels[this.level].audioCodec,s=navigator.userAgent.toLowerCase();o&&this.audioCodecSwap&&(g.b.log("swapping playlist audio codec"),o=-1!==o.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==n.metadata.channelCount&&-1===s.indexOf("firefox")&&(o="mp4a.40.5"),-1!==s.indexOf("android")&&"audio/mpeg"!==n.container&&(o="mp4a.40.2",g.b.log("Android: force audio codec to "+o)),n.levelCodec=o,n.id=t.id}n=i.video,n&&(n.levelCodec=this.levels[this.level].videoCodec,n.id=t.id),this.hls.trigger(u.a.BUFFER_CODECS,i);for(a in i){n=i[a],g.b.log("main track:"+a+",container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var l=n.initSegment;l&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(u.a.BUFFER_APPENDING,{type:a,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===T.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),!0===t.hasAudio&&n.addElementaryStream(c.a.ElementaryStreamTypes.AUDIO),!0===t.hasVideo&&n.addElementaryStream(c.a.ElementaryStreamTypes.VIDEO),g.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)g.b.warn("Already backtracked on this fragment, appending with the gap",n.sn);else{var o=a.details;if(!o||n.sn!==o.startSN)return g.b.warn("missing video frame(s), backtracking fragment",n.sn),this.fragmentTracker.removeFragment(n),n.backtracked=!0,this.nextLoadPosition=t.startPTS,this.state=T.IDLE,this.fragPrevious=n,void this.tick();g.b.warn("missing video frame(s) on first frag, appending with gap",n.sn)}else n.backtracked=!1;var s=f.c(a.details,n,t.startPTS,t.endPTS,t.startDTS,t.endDTS),l=this.hls;l.trigger(u.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===T.PARSING&&(e.appended=!0,e.pendingBuffering=!0,l.trigger(u.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===T.PARSING&&(this.stats.tparsed=window.performance.now(),this.state=T.PARSED,this._checkAppendedParsed())},e.prototype.onAudioTrackSwitching=function(t){var e=!!t.url,r=t.id;if(!e){if(this.mediaBuffer!==this.media){g.b.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i.loader&&(g.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=T.IDLE}var a=this.hls;a.trigger(u.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),a.trigger(u.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&&(g.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?(g.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!==T.PARSING&&e!==T.PARSED||(this.pendingBuffering=t.pending>0,this._checkAppendedParsed())}},e.prototype._checkAppendedParsed=function(){if(!(this.state!==T.PARSED||this.appended&&this.pendingBuffering)){var t=this.fragCurrent;if(t){var e=this.mediaBuffer?this.mediaBuffer:this.media;g.b.log("main buffered : "+p.a.toString(e.buffered)),this.fragPrevious=t;var r=this.stats;r.tbuffered=window.performance.now(),this.fragLastKbps=Math.round(8*r.total/(r.tbuffered-r.tfirst)),this.hls.trigger(u.a.FRAG_BUFFERED,{stats:r,frag:t,id:"main"}),this.state=T.IDLE}this.tick()}},e.prototype.onError=function(t){var e=t.frag||this.fragCurrent;if(!e||"main"===e.type){var r=!!this.media&&s.a.isBuffered(this.media,this.media.currentTime)&&s.a.isBuffered(this.media,this.media.currentTime+.5);switch(t.details){case v.a.FRAG_LOAD_ERROR:case v.a.FRAG_LOAD_TIMEOUT:case v.a.KEY_LOAD_ERROR:case v.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);g.b.warn("mediaController: frag loading failed, retry in "+i+" ms"),this.retryDate=window.performance.now()+i,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=T.FRAG_LOADING_WAITING_RETRY}else g.b.error("mediaController: "+t.details+" reaches max retry, redispatch as fatal ..."),t.fatal=!0,this.state=T.ERROR;break;case v.a.LEVEL_LOAD_ERROR:case v.a.LEVEL_LOAD_TIMEOUT:this.state!==T.ERROR&&(t.fatal?(this.state=T.ERROR,g.b.warn("streamController: "+t.details+",switch to "+this.state+" state ...")):t.levelRetry||this.state!==T.WAITING_LEVEL||(this.state=T.IDLE));break;case v.a.BUFFER_FULL_ERROR:"main"!==t.parent||this.state!==T.PARSING&&this.state!==T.PARSED||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=T.IDLE):(g.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;return e.maxMaxBufferLength>=t&&(e.maxMaxBufferLength/=2,g.b.warn("main:reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},e.prototype._checkBuffer=function(){var t=this.config,e=this.media;if(e&&0!==e.readyState){var r=e.currentTime,i=this.mediaBuffer?this.mediaBuffer:e,a=i.buffered;if(!this.loadedmetadata&&a.length)this.loadedmetadata=!0,this._seekToStartPos();else if(this.immediateSwitch)this.immediateLevelSwitchEnd();else{var n=!(e.paused&&e.readyState>1||e.ended||0===e.buffered.length),o=window.performance.now();if(r!==this.lastCurrentTime)this.stallReported&&(g.b.warn("playback not stuck anymore @"+r+", after "+Math.round(o-this.stalled)+"ms"),this.stallReported=!1),this.stalled=null,this.nudgeRetry=0;else if(n){var l=o-this.stalled,u=s.a.bufferInfo(e,r,t.maxBufferHole);if(!this.stalled)return void(this.stalled=o);l>=1e3&&this._reportStall(u.len),this._tryFixBufferStall(u,l)}}}},e.prototype.onFragLoadEmergencyAborted=function(){this.state=T.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},e.prototype.onBufferFlushed=function(){var t=this.mediaBuffer?this.mediaBuffer:this.media;t&&this.fragmentTracker.detectEvictedFragments(c.a.ElementaryStreamTypes.VIDEO,t.buffered),this.state=T.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)},e.prototype._tryFixBufferStall=function(t,e){var r=this.config,i=this.media,a=i.currentTime,n=this.fragmentTracker.getPartialFragment(a);n&&this._trySkipBufferHole(n),t.len>.5&&e>1e3*r.highBufferWatchdogPeriod&&(this.stalled=null,this._tryNudgeBuffer())},e.prototype._reportStall=function(t){var e=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,g.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer"),e.trigger(u.a.ERROR,{type:v.b.MEDIA_ERROR,details:v.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:t}))},e.prototype._trySkipBufferHole=function(t){for(var e=this.hls,r=this.media,i=r.currentTime,a=0,n=0;n<r.buffered.length;n++){var o=r.buffered.start(n);if(i>=a&&i<o)return r.currentTime=Math.max(o,r.currentTime+.1),g.b.warn("skipping hole, adjusting currentTime from "+i+" to "+r.currentTime),this.stalled=null,void e.trigger(u.a.ERROR,{type:v.b.MEDIA_ERROR,details:v.a.BUFFER_SEEK_OVER_HOLE,fatal:!1,reason:"fragment loaded with buffer holes, seeking from "+i+" to "+r.currentTime,frag:t});a=r.buffered.end(n)}},e.prototype._tryNudgeBuffer=function(){var t=this.config,e=this.hls,r=this.media,i=r.currentTime,a=(this.nudgeRetry||0)+1;if(this.nudgeRetry=a,a<t.nudgeMaxRetry){var n=i+a*t.nudgeOffset;g.b.log("adjust currentTime from "+i+" to "+n),r.currentTime=n,e.trigger(u.a.ERROR,{type:v.b.MEDIA_ERROR,details:v.a.BUFFER_NUDGE_ON_STALL,fatal:!1})}else g.b.error("still stuck in high buffer @"+i+" after "+t.nudgeMaxRetry+", raise fatal error"),e.trigger(u.a.ERROR,{type:v.b.MEDIA_ERROR,details:v.a.BUFFER_STALLED_ERROR,fatal:!0})},e.prototype._seekToStartPos=function(){var t=this.media,e=t.currentTime,r=t.seeking?e:this.startPosition;e!==r&&(g.b.log("target start position not buffered, seek to buffered.start(0) "+r+" from current time "+e+" "),t.currentTime=r)},E(e,[{key:"state",set:function(t){if(this.state!==t){var e=this.state;this._state=t,g.b.log("main stream:"+e+"->"+t),this.hls.trigger(u.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}(m.a);e.a=S},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,e,i){var n={};n[i]=[];var o=e.toString(),s=o.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!s)return n;for(var d,c=s[1],h=new RegExp("(\\\\n|\\W)"+a(c)+u,"g");d=h.exec(o);)"dll-reference"!==d[3]&&n[i].push(d[3]);for(h=new RegExp("\\("+a(c)+'\\("(dll-reference\\s('+l+'))"\\)\\)'+u,"g");d=h.exec(o);)t[d[2]]||(n[i].push(d[1]),t[d[2]]=r(d[1]).m),n[d[2]]=n[d[2]]||[],n[d[2]].push(d[4]);return n}function o(t){return Object.keys(t).reduce(function(e,r){return e||t[r].length>0},!1)}function s(t,e){for(var r={main:[e]},i={main:[]},a={main:{}};o(r);)for(var s=Object.keys(r),l=0;l<s.length;l++){var u=s[l],d=r[u],c=d.pop();if(a[u]=a[u]||{},!a[u][c]&&t[u][c]){a[u][c]=!0,i[u]=i[u]||[],i[u].push(c);for(var h=n(t,t[u][c],u),f=Object.keys(h),p=0;p<f.length;p++)r[f[p]]=r[f[p]]||[],r[f[p]]=r[f[p]].concat(h[f[p]])}}return i}var l="[\\.|\\-|\\+|\\w|/|@]+",u="\\((/\\*.*?\\*/)?s?.*?("+l+").*?\\)";t.exports=function(t,e){e=e||{};var a={main:r.m},n=e.all?{main:Object.keys(a)}:s(a,t),o="";Object.keys(n).filter(function(t){return"main"!==t}).forEach(function(t){for(var e=0;n[t][e];)e++;n[t].push(e),a[t][e]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",o=o+"var "+t+" = ("+i.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+n[t].map(function(e){return JSON.stringify(e)+": "+a[t][e].toString()}).join(",")+"});\n"}),o=o+"("+i.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+n.main.map(function(t){return JSON.stringify(t)+": "+a.main[t].toString()}).join(",")+"})(self);";var l=new window.Blob([o],{type:"text/javascript"});if(e.bare)return l;var u=window.URL||window.webkitURL||window.mozURL||window.msURL,d=u.createObjectURL(l),c=new window.Worker(d);return c.objectURL=d,c}},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=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}();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")}var a=function(){function t(e,r){i(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}();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){var e=t.byteLength,r=e&&new DataView(t).getUint8(e-1);return r?t.slice(0,e-r):t}var n=function(){function t(){i(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],c=s[3],h=new Uint32Array(256),f=0,p=0,v=0;for(v=0;v<256;v++)h[v]=v<128?v<<1:v<<1^283;for(v=0;v<256;v++){var g=p^p<<1^p<<2^p<<3^p<<4;g=g>>>8^255&g^99,t[f]=g,e[g]=f;var y=h[f],m=h[y],b=h[m],E=257*h[g]^16843008*g;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[g]=E<<24|E>>>8,u[g]=E<<16|E>>>16,d[g]=E<<8|E>>>24,c[g]=E,f?(f=y^h[h[h[b^y]]],p^=h[h[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,c=this.rcon,h=this.invSubMix,f=h[0],p=h[1],v=h[2],g=h[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^=c[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]]^v[d[m>>>8&255]]^g[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,i){for(var n=this.keySize+6,o=this.invKeySchedule,s=this.invSBox,l=this.invSubMix,u=l[0],d=l[1],c=l[2],h=l[3],f=this.uint8ArrayToUint32Array_(r),p=f[0],v=f[1],g=f[2],y=f[3],m=new Int32Array(t),b=new Int32Array(m.length),E=void 0,T=void 0,S=void 0,R=void 0,A=void 0,_=void 0,w=void 0,L=void 0,D=void 0,I=void 0,k=void 0,O=void 0,C=void 0,P=void 0,x=this.networkToHostOrderSwap;e<m.length;){for(D=x(m[e]),I=x(m[e+1]),k=x(m[e+2]),O=x(m[e+3]),A=D^o[0],_=O^o[1],w=k^o[2],L=I^o[3],C=4,P=1;P<n;P++)E=u[A>>>24]^d[_>>16&255]^c[w>>8&255]^h[255&L]^o[C],T=u[_>>>24]^d[w>>16&255]^c[L>>8&255]^h[255&A]^o[C+1],S=u[w>>>24]^d[L>>16&255]^c[A>>8&255]^h[255&_]^o[C+2],R=u[L>>>24]^d[A>>16&255]^c[_>>8&255]^h[255&w]^o[C+3],A=E,_=T,w=S,L=R,C+=4;E=s[A>>>24]<<24^s[_>>16&255]<<16^s[w>>8&255]<<8^s[255&L]^o[C],T=s[_>>>24]<<24^s[w>>16&255]<<16^s[L>>8&255]<<8^s[255&A]^o[C+1],S=s[w>>>24]<<24^s[L>>16&255]<<16^s[A>>8&255]<<8^s[255&_]^o[C+2],R=s[L>>>24]<<24^s[A>>16&255]<<16^s[_>>8&255]<<8^s[255&w]^o[C+3],C+=3,b[e]=x(E^p),b[e+1]=x(R^v),b[e+2]=x(S^g),b[e+3]=x(T^y),p=D,v=I,g=k,y=O,e+=4}return i?a(b.buffer):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}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(22),n=r(0),o=r(7),s=function(){function t(e,r,a){i(this,t),this.observer=e,this.config=a,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=o.a.getID3Data(t,0)||[],r=e.length,i=t.length;r<i;r++)if(a.e(t,r))return n.b.log("ADTS sync word found !"),!0;return!1},t.prototype.append=function(t,e,r,i){for(var s=this._audioTrack,l=o.a.getID3Data(t,0)||[],u=o.a.getTimeStamp(l),d=u?90*u:9e4*e,c=0,h=d,f=t.length,p=l.length,v=[{pts:h,dts:h,data:l}];p<f-1;)if(a.d(t,p)&&p+5<f){a.c(s,this.observer,t,p,s.manifestCodec);var g=a.a(s,t,p,d,c);if(!g){n.b.log("Unable to parse AAC frame");break}p+=g.length,h=g.sample.pts,c++}else o.a.isHeader(t,p)?(l=o.a.getID3Data(t,p),v.push({pts:h,dts:h,data:l}),p+=l.length):p++;this.remuxer.remux(s,{samples:[]},{samples:v,inputTimeScale:9e4},{samples:[]},e,r,i)},t.prototype.destroy=function(){},t}();e.a=s},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(22),n=r(23),o=r(1),s=r(40),l=r(41),u=r(0),d=r(2),c={video:1,audio:2,id3:3,text:4},h=function(){function t(e,r,a,n){i(this,t),this.observer=e,this.config=a,this.typeSupported=n,this.remuxer=r,this.sampleAes=null}return t.prototype.setDecryptData=function(t){null!=t&&null!=t.key&&"SAMPLE-AES"===t.method?this.sampleAes=new l.a(this.observer,this.config,t,this.discardEPB):this.sampleAes=null},t.probe=function(e){var r=t._syncOffset(e);return!(r<0)&&(r&&u.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:c[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=void 0,s=e.length,l=void 0,c=void 0,h=void 0,f=void 0,p=!1;this.contiguous=i;var v=this.pmtParsed,g=this._avcTrack,y=this._audioTrack,m=this._id3Track,b=g.pid,E=y.pid,T=m.pid,S=this._pmtId,R=g.pesData,A=y.pesData,_=m.pesData,w=this._parsePAT,L=this._parsePMT,D=this._parsePES,I=this._parseAVCPES.bind(this),k=this._parseAACPES.bind(this),O=this._parseMPEGPES.bind(this),C=this._parseID3PES.bind(this),P=t._syncOffset(e);for(s-=(s+P)%188,n=P;n<s;n+=188)if(71===e[n]){if(l=!!(64&e[n+1]),c=((31&e[n+1])<<8)+e[n+2],(48&e[n+3])>>4>1){if((h=n+5+e[n+4])===n+188)continue}else h=n+4;switch(c){case b:l&&(R&&(f=D(R))&&void 0!==f.pts&&I(f,!1),R={data:[],size:0}),R&&(R.data.push(e.subarray(h,n+188)),R.size+=n+188-h);break;case E:l&&(A&&(f=D(A))&&void 0!==f.pts&&(y.isAAC?k(f):O(f)),A={data:[],size:0}),A&&(A.data.push(e.subarray(h,n+188)),A.size+=n+188-h);break;case T:l&&(_&&(f=D(_))&&void 0!==f.pts&&C(f),_={data:[],size:0}),_&&(_.data.push(e.subarray(h,n+188)),_.size+=n+188-h);break;case 0:l&&(h+=e[h]+1),S=this._pmtId=w(e,h);break;case S:l&&(h+=e[h]+1);var x=L(e,h,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);b=x.avc,b>0&&(g.pid=b),E=x.audio,E>0&&(y.pid=E,y.isAAC=x.isAAC),T=x.id3,T>0&&(m.pid=T),p&&!v&&(u.b.log("reparse from beginning"),p=!1,n=P-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=!0}}else this.observer.trigger(o.a.ERROR,{type:d.b.MEDIA_ERROR,details:d.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});R&&(f=D(R))&&void 0!==f.pts?(I(f,!0),g.pesData=null):g.pesData=R,A&&(f=D(A))&&void 0!==f.pts?(y.isAAC?k(f):O(f),y.pesData=null):(A&&A.size&&u.b.log("last AAC PES packet truncated,might overlap between fragments"),y.pesData=A),_&&(f=D(_))&&void 0!==f.pts?(C(f),m.pesData=null):m.pesData=_,null==this.sampleAes?this.remuxer.remux(y,g,m,this._txtTrack,r,i,a):this.decryptAndRemux(y,g,m,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=void 0,n=void 0,o=void 0,s=void 0,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){u.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){u.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):u.b.log("MPEG audio found, not supported in this browser for now");break;case 36:u.b.warn("HEVC stream type found, not supported for now");break;default:u.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=0,r=void 0,i=void 0,a=void 0,n=void 0,o=void 0,s=void 0,l=void 0,d=void 0,c=t.data;if(!t||0===t.size)return null;for(;c[0].length<19&&c.length>1;){var h=new Uint8Array(c[0].length+c[1].length);h.set(c[0]),h.set(c[1],c[0].length),c[0]=h,c.splice(1,1)}if(r=c[0],1===(r[0]<<16)+(r[1]<<8)+r[2]){if((a=(r[4]<<8)+r[5])&&a>t.size-6)return null;i=r[7],192&i&&(s=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,s>4294967295&&(s-=8589934592),64&i?(l=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2,l>4294967295&&(l-=8589934592),s-l>54e5&&(u.b.warn(Math.round((s-l)/9e4)+"s delta between PTS and DTS, align them"),s=l)):l=s),n=r[8],d=n+9,t.size-=d,o=new Uint8Array(t.size);for(var f=0,p=c.length;f<p;f++){r=c[f];var v=r.byteLength;if(d){if(d>v){d-=v;continue}r=r.subarray(d),v-=d,d=0}o.set(r,e),e+=v}return a&&(a-=n+3),{data:o,pts:s,dts:l,len:a}}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&&u.b.log(t.pts+"/"+t.dts+":"+t.debug)},t.prototype._parseAVCPES=function(t,e){var r=this,i=this._avcTrack,a=this._parseAVCNALu(t.data),n=void 0,o=this.avcSample,l=void 0,u=!1,d=void 0,c=this.pushAccesUnit.bind(this),h=function(t,e,r,i){return{key:t,pts:e,dts:r,units:[],debug:i}};t.data=null,o&&a.length&&!i.audFound&&(c(o,i),o=this.avcSample=h(!1,t.pts,t.dts,"")),a.forEach(function(e){switch(e.type){case 1:l=!0,o||(o=r.avcSample=h(!0,t.pts,t.dts,"")),o.frame=!0;var a=e.data;if(u&&a.length>4){var f=new s.a(a).readSliceType();2!==f&&4!==f&&7!==f&&9!==f||(o.key=!0)}break;case 5:l=!0,o||(o=r.avcSample=h(!0,t.pts,t.dts,"")),o.key=!0,o.frame=!0;break;case 6:l=!0,n=new s.a(r.discardEPB(e.data)),n.readUByte();for(var p=0,v=0,g=!1,y=0;!g&&n.bytesAvailable>1;){p=0;do{y=n.readUByte(),p+=y}while(255===y);v=0;do{y=n.readUByte(),v+=y}while(255===y);if(4===p&&0!==n.bytesAvailable){g=!0;if(181===n.readUByte()){if(49===n.readUShort()){if(1195456820===n.readUInt()){if(3===n.readUByte()){var m=n.readUByte(),b=n.readUByte(),E=31&m,T=[m,b];for(d=0;d<E;d++)T.push(n.readUByte()),T.push(n.readUByte()),T.push(n.readUByte());r._insertSampleInOrder(r._txtTrack.samples,{type:3,pts:t.pts,bytes:T})}}}}}else if(v<n.bytesAvailable)for(d=0;d<v;d++)n.readUByte()}break;case 7:if(l=!0,u=!0,!i.sps){n=new s.a(e.data);var S=n.readSPS();i.width=S.width,i.height=S.height,i.pixelRatio=S.pixelRatio,i.sps=[e.data],i.duration=r._duration;var R=e.data.subarray(1,4),A="avc1.";for(d=0;d<3;d++){var _=R[d].toString(16);_.length<2&&(_="0"+_),A+=_}i.codec=A}break;case 8:l=!0,i.pps||(i.pps=[e.data]);break;case 9:l=!1,i.audFound=!0,o&&c(o,i),o=r.avcSample=h(!1,t.pts,t.dts,"");break;case 12:l=!1;break;default:l=!1,o&&(o.debug+="unknown NAL "+e.type+" ")}if(o&&l){o.units.push(e)}}),e&&o&&(c(o,i),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=0,r=t.byteLength,i=void 0,a=void 0,n=this._avcTrack,o=n.naluState||0,s=o,l=[],u=void 0,d=void 0,c=-1,h=void 0;for(-1===o&&(c=0,h=31&t[0],o=0,e=1);e<r;)if(i=t[e++],o)if(1!==o)if(i)if(1===i){if(c>=0)u={data:t.subarray(c,e-o-1),type:h},l.push(u);else{var f=this._getLastNalUnit();if(f&&(s&&e<=4-s&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-s)),(a=e-o-1)>0)){var p=new Uint8Array(f.data.byteLength+a);p.set(f.data,0),p.set(t.subarray(0,a),f.data.byteLength),f.data=p}}e<r?(d=31&t[e],c=e,h=d,o=0):o=-1}else o=0;else o=3;else o=i?0:2;else o=i?0:1;if(c>=0&&o>=0&&(u={data:t.subarray(c,r),type:h,state:o},l.push(u)),0===l.length){var v=this._getLastNalUnit();if(v){var g=new Uint8Array(v.data.byteLength+t.byteLength);g.set(v.data,0),g.set(t,v.data.byteLength),v.data=g}}return n.naluState=o,l},t.prototype.discardEPB=function(t){for(var e=t.byteLength,r=[],i=1,a=void 0,n=void 0;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return t;a=e-r.length,n=new Uint8Array(a);var o=0;for(i=0;i<a;o++,i++)o===r[0]&&(o++,r.shift()),n[i]=t[o];return n},t.prototype._parseAACPES=function(t){var e=this._audioTrack,r=t.data,i=t.pts,n=this.aacOverFlow,s=this.aacLastPTS,l=void 0,c=void 0,h=void 0,f=void 0,p=void 0;if(n){var v=new Uint8Array(n.byteLength+r.byteLength);v.set(n,0),v.set(r,n.byteLength),r=v}for(h=0,p=r.length;h<p-1&&!a.d(r,h);h++);if(h){var g=void 0,y=void 0;if(h<p-1?(g="AAC PES did not start with ADTS header,offset:"+h,y=!1):(g="no ADTS header found in AAC PES",y=!0),u.b.warn("parsing error:"+g),this.observer.trigger(o.a.ERROR,{type:d.b.MEDIA_ERROR,details:d.a.FRAG_PARSING_ERROR,fatal:y,reason:g}),y)return}if(a.c(e,this.observer,r,h,this.audioCodec),c=0,l=a.b(e.samplerate),n&&s){var m=s+l;Math.abs(m-i)>1&&(u.b.log("AAC: align PTS for overlapping frames by "+Math.round((m-i)/90)),i=m)}for(;h<p;)if(a.d(r,h)&&h+5<p){var b=a.a(e,r,h,i,c);if(!b)break;h+=b.length,f=b.sample.pts,c++}else h++;n=h<p?r.subarray(h,p):null,this.aacOverFlow=n,this.aacLastPTS=f},t.prototype._parseMPEGPES=function(t){for(var e=t.data,r=e.length,i=0,a=0,o=t.pts;a<r;)if(n.a.isHeader(e,a)){var s=n.a.appendFrame(this._audioTrack,e,a,o,i);if(!s)break;a+=s.length,i++}else a++},t.prototype._parseID3PES=function(t){this._id3Track.samples.push(t)},t}();e.a=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(0),n=function(){function t(e){i(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=void 0;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&&a.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=void 0;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=8,r=8,i=void 0,a=void 0;for(i=0;i<t;i++)0!==r&&(a=this.readEG(),r=(e+a+256)%256),e=0===r?e:r},t.prototype.readSPS=function(){var t=0,e=0,r=0,i=0,a=void 0,n=void 0,o=void 0,s=void 0,l=void 0,u=void 0,d=void 0,c=this.readUByte.bind(this),h=this.readBits.bind(this),f=this.readUEG.bind(this),p=this.readBoolean.bind(this),v=this.skipBits.bind(this),g=this.skipEG.bind(this),y=this.skipUEG.bind(this),m=this.skipScalingList.bind(this);if(c(),a=c(),h(5),v(3),c(),y(),100===a||110===a||122===a||244===a||44===a||83===a||86===a||118===a||128===a){var b=f();if(3===b&&v(1),y(),y(),v(1),p())for(u=3!==b?8:12,d=0;d<u;d++)p()&&m(d<6?16:64)}y();var E=f();if(0===E)f();else if(1===E)for(v(1),g(),g(),n=f(),d=0;d<n;d++)g();y(),v(1),o=f(),s=f(),l=h(1),0===l&&v(1),v(1),p()&&(t=f(),e=f(),r=f(),i=f());var T=[1,1];if(p()&&p()){switch(c()){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=[c()<<8|c(),c()<<8|c()]}}return{width:Math.ceil(16*(o+1)-2*t-2*e),height:(2-l)*(s+1)*16-(l?2:4)*(r+i),pixelRatio:T}},t.prototype.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},t}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(13),n=function(){function t(e,r,n,o){i(this,t),this.decryptdata=n,this.discardEPB=o,this.decrypter=new a.a(e,r,{removePKCS7Padding:!1})}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}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(7),n=r(0),o=r(23),s=function(){function t(e,r,a){i(this,t),this.observer=e,this.config=a,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=void 0,r=void 0,i=a.a.getID3Data(t,0);if(i&&void 0!==a.a.getTimeStamp(i))for(e=i.length,r=Math.min(t.length-1,e+100);e<r;e++)if(o.a.probe(t,e))return n.b.log("MPEG Audio sync word found !"),!0;return!1},t.prototype.append=function(t,e,r,i){for(var n=a.a.getID3Data(t,0),s=a.a.getTimeStamp(n),l=s?90*s:9e4*e,u=n.length,d=t.length,c=0,h=0,f=this._audioTrack,p=[{pts:l,dts:l,data:n}];u<d;)if(o.a.isHeader(t,u)){var v=o.a.appendFrame(f,t,u,l,c);if(!v)break;u+=v.length,h=v.sample.pts,c++}else a.a.isHeader(t,u)?(n=a.a.getID3Data(t,u),p.push({pts:h,dts:h,data:n}),u+=n.length):u++;this.remuxer.remux(f,{samples:[]},{samples:p,inputTimeScale:9e4},{samples:[]},e,r,i)},t.prototype.destroy=function(){},t}();e.a=s},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(44),n=r(45),o=r(1),s=r(2),l=r(0),u=function(){function t(e,r,a,n){i(this,t),this.observer=e,this.config=r,this.typeSupported=a;var o=navigator.userAgent;this.isSafari=n&&n.indexOf("Apple")>-1&&o&&!o.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,s){if(this.ISGenerated||this.generateIS(t,e,a),this.ISGenerated){var u=t.samples.length,d=e.samples.length,c=a,h=a;if(u&&d){var f=(t.samples[0].dts-e.samples[0].dts)/e.inputTimeScale;c+=Math.max(0,f),h+=Math.max(0,-f)}if(u){t.timescale||(l.b.warn("regenerate InitSegment as audio detected"),this.generateIS(t,e,a));var p=this.remuxAudio(t,c,n,s);if(d){var v=void 0;p&&(v=p.endPTS-p.startPTS),e.timescale||(l.b.warn("regenerate InitSegment as video detected"),this.generateIS(t,e,a)),this.remuxVideo(e,h,n,v,s)}}else if(d){var g=this.remuxVideo(e,h,n,0,s);g&&t.codec&&this.remuxEmptyAudio(t,c,n,g)}}r.samples.length&&this.remuxID3(r,a),i.samples.length&&this.remuxText(i,a),this.observer.trigger(o.a.FRAG_PARSED)},t.prototype.generateIS=function(t,e,r){var i=this.observer,a=t.samples,u=e.samples,d=this.typeSupported,c="audio/mp4",h={},f={tracks:h},p=void 0===this._initPTS,v=void 0,g=void 0;if(p&&(v=g=1/0),t.config&&a.length&&(t.timescale=t.samplerate,l.b.log("audio sampling rate : "+t.samplerate),t.isAAC||(d.mpeg?(c="audio/mpeg",t.codec=""):d.mp3&&(t.codec="mp3")),h.audio={container:c,codec:t.codec,initSegment:!t.isAAC&&d.mpeg?new Uint8Array:n.a.initSegment([t]),metadata:{channelCount:t.channelCount}},p&&(v=g=a[0].pts-t.inputTimeScale*r)),e.sps&&e.pps&&u.length){var y=e.inputTimeScale;e.timescale=y,h.video={container:"video/mp4",codec:e.codec,initSegment:n.a.initSegment([e]),metadata:{width:e.width,height:e.height}},p&&(v=Math.min(v,u[0].pts-y*r),g=Math.min(g,u[0].dts-y*r),this.observer.trigger(o.a.INIT_PTS_FOUND,{initPTS:v}))}Object.keys(h).length?(i.trigger(o.a.FRAG_PARSING_INIT_SEGMENT,f),this.ISGenerated=!0,p&&(this._initPTS=v,this._initDTS=g)):i.trigger(o.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},t.prototype.remuxVideo=function(t,e,r,i,a){var u=8,d=t.timescale,c=void 0,h=void 0,f=void 0,p=void 0,v=void 0,g=void 0,y=void 0,m=t.samples,b=[],E=m.length,T=this._PTSNormalize,S=this._initDTS,R=this.nextAvcDts,A=this.isSafari;if(0!==E){A&&(r|=m.length&&R&&(a&&Math.abs(e-R/d)<.1||Math.abs(m[0].pts-R-S)<d/5)),r||(R=e*d),m.forEach(function(t){t.pts=T(t.pts-S,R),t.dts=T(t.dts-S,R)}),m.sort(function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i||t.id-e.id});var _=m.reduce(function(t,e){return Math.max(Math.min(t,e.pts-e.dts),-18e3)},0);if(_<0){l.b.warn("PTS < DTS detected in video samples, shifting DTS by "+Math.round(_/90)+" ms to overcome this issue");for(var w=0;w<m.length;w++)m[w].dts+=_}var L=m[0];v=Math.max(L.dts,0),p=Math.max(L.pts,0);var D=Math.round((v-R)/90);r&&D&&(D>1?l.b.log("AVC:"+D+" ms hole between fragments detected,filling it"):D<-1&&l.b.log("AVC:"+-D+" ms overlapping between fragments detected"),v=R,m[0].dts=v,p=Math.max(p-D,R),m[0].pts=p,l.b.log("Video/PTS/DTS adjusted: "+Math.round(p/90)+"/"+Math.round(v/90)+",delta:"+D+" ms")),v,L=m[m.length-1],y=Math.max(L.dts,0),g=Math.max(L.pts,0,y),A&&(c=Math.round((y-v)/(m.length-1)));for(var I=0,k=0,O=0;O<E;O++){for(var C=m[O],P=C.units,x=P.length,F=0,N=0;N<x;N++)F+=P[N].data.length;k+=F,I+=x,C.length=F,C.dts=A?v+O*c:Math.max(C.dts,v),C.pts=Math.max(C.pts,C.dts)}var M=k+4*I+8;try{h=new Uint8Array(M)}catch(t){return void this.observer.trigger(o.a.ERROR,{type:s.b.MUX_ERROR,details:s.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:M,reason:"fail allocating video mdat "+M})}var U=new DataView(h.buffer);U.setUint32(0,M),h.set(n.a.types.mdat,4);for(var B=0;B<E;B++){for(var G=m[B],K=G.units,j=0,H=void 0,V=0,Y=K.length;V<Y;V++){var W=K[V],q=W.data,X=W.data.byteLength;U.setUint32(u,X),u+=4,h.set(q,u),u+=X,j+=4+X}if(A)H=Math.max(0,c*Math.round((G.pts-G.dts)/c));else{if(B<E-1)c=m[B+1].dts-G.dts;else{var z=this.config,Q=G.dts-m[B>0?B-1:B].dts;if(z.stretchShortVideoTrack){var $=z.maxBufferHole,J=Math.floor($*d),Z=(i?p+i*d:this.nextAudioPts)-G.pts;Z>J?(c=Z-Q,c<0&&(c=Q),l.b.log("It is approximately "+Z/90+" ms to the next segment; using duration "+c/90+" ms for the last video frame.")):c=Q}else c=Q}H=Math.round(G.pts-G.dts)}b.push({size:j,duration:c,cts:H,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:G.key?2:1,isNonSync:G.key?0:1}})}this.nextAvcDts=y+c;var tt=t.dropped;if(t.len=0,t.nbNalu=0,t.dropped=0,b.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var et=b[0].flags;et.dependsOn=2,et.isNonSync=0}t.samples=b,f=n.a.moof(t.sequenceNumber++,v,t),t.samples=[];var rt={data1:f,data2:h,startPTS:p/d,endPTS:(g+c)/d,startDTS:v/d,endDTS:this.nextAvcDts/d,type:"video",hasAudio:!1,hasVideo:!0,nb:b.length,dropped:tt};return this.observer.trigger(o.a.FRAG_PARSING_DATA,rt),rt}},t.prototype.remuxAudio=function(t,e,r,i){var u=t.inputTimeScale,d=t.timescale,c=u/d,h=t.isAAC?1024:1152,f=h*c,p=this._PTSNormalize,v=this._initDTS,g=!t.isAAC&&this.typeSupported.mpeg,y=void 0,m=void 0,b=void 0,E=void 0,T=void 0,S=void 0,R=void 0,A=t.samples,_=[],w=this.nextAudioPts;if(r|=A.length&&w&&(i&&Math.abs(e-w/u)<.1||Math.abs(A[0].pts-w-v)<20*f),A.forEach(function(t){t.pts=t.dts=p(t.pts-v,e*u)}),A=A.filter(function(t){return t.pts>=0}),0!==A.length){if(r||(w=i?e*u:A[0].pts),t.isAAC)for(var L=this.config.maxAudioFramesDrift,D=0,I=w;D<A.length;){var k,O=A[D],C=O.pts;k=C-I;var P=Math.abs(1e3*k/u);if(k<=-L*f)l.b.warn("Dropping 1 audio frame @ "+(I/u).toFixed(3)+"s due to "+Math.round(P)+" ms overlap."),A.splice(D,1),t.len-=O.unit.length;else if(k>=L*f&&P<1e4&&I){var x=Math.round(k/f);l.b.warn("Injecting "+x+" audio frame @ "+(I/u).toFixed(3)+"s due to "+Math.round(1e3*k/u)+" ms gap.");for(var F=0;F<x;F++){var N=Math.max(I,0);b=a.a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),b||(l.b.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),b=O.unit.subarray()),A.splice(D,0,{unit:b,pts:N,dts:N}),t.len+=b.length,I+=f,D++}O.pts=O.dts=I,I+=f,D++}else Math.abs(k),O.pts=O.dts=I,I+=f,D++}for(var M=0,U=A.length;M<U;M++){var B=A[M],G=B.unit,K=B.pts;if(void 0!==R)m.duration=Math.round((K-R)/c);else{var j=Math.round(1e3*(K-w)/u),H=0;if(r&&t.isAAC&&j){if(j>0&&j<1e4)H=Math.round((K-w)/f),l.b.log(j+" ms hole between AAC samples detected,filling it"),H>0&&(b=a.a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),b||(b=G.subarray()),t.len+=H*b.length);else if(j<-12){l.b.log("drop overlapping AAC sample, expected/parsed/delta:"+(w/u).toFixed(3)+"s/"+(K/u).toFixed(3)+"s/"+-j+"ms"),t.len-=G.byteLength;continue}K=w}if(S=K,!(t.len>0))return;var V=g?t.len:t.len+8;y=g?0:8;try{E=new Uint8Array(V)}catch(t){return void this.observer.trigger(o.a.ERROR,{type:s.b.MUX_ERROR,details:s.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:V,reason:"fail allocating audio mdat "+V})}if(!g){new DataView(E.buffer).setUint32(0,V),E.set(n.a.types.mdat,4)}for(var Y=0;Y<H;Y++)b=a.a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount),b||(l.b.log("Unable to get silent frame for given audio codec; duplicating this frame instead."),b=G.subarray()),E.set(b,y),y+=b.byteLength,m={size:b.byteLength,cts:0,duration:1024,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},_.push(m)}E.set(G,y);var W=G.byteLength;y+=W,m={size:W,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},_.push(m),R=K}var q=0,X=_.length;if(X>=2&&(q=_[X-2].duration,m.duration=q),X){this.nextAudioPts=w=R+c*q,t.len=0,t.samples=_,T=g?new Uint8Array:n.a.moof(t.sequenceNumber++,S/c,t),t.samples=[];var z=S/u,Q=w/u,$={data1:T,data2:E,startPTS:z,endPTS:Q,startDTS:z,endDTS:Q,type:"audio",hasAudio:!0,hasVideo:!1,nb:X};return this.observer.trigger(o.a.FRAG_PARSING_DATA,$),$}return null}},t.prototype.remuxEmptyAudio=function(t,e,r,i){var n=t.inputTimeScale,o=t.samplerate?t.samplerate:n,s=n/o,u=this.nextAudioPts,d=(void 0!==u?u:i.startDTS*n)+this._initDTS,c=i.endDTS*n+this._initDTS,h=1024*s,f=Math.ceil((c-d)/h),p=a.a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(l.b.warn("remux empty Audio"),!p)return void l.b.trace("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!");for(var v=[],g=0;g<f;g++){var y=d+g*h;v.push({unit:p,pts:y,dts:y}),t.len+=p.length}t.samples=v,this.remuxAudio(t,e,r)},t.prototype.remuxID3=function(t,e){var r=t.samples.length,i=void 0,a=t.inputTimeScale,n=this._initPTS,s=this._initDTS;if(r){for(var l=0;l<r;l++)i=t.samples[l],i.pts=(i.pts-n)/a,i.dts=(i.dts-s)/a;this.observer.trigger(o.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=t.samples.length,i=void 0,a=t.inputTimeScale,n=this._initPTS;if(r){for(var s=0;s<r;s++)i=t.samples[s],i.pts=(i.pts-n)/a;this.observer.trigger(o.a.FRAG_PARSING_USERDATA,{samples:t.samples})}t.samples=[],e=e},t.prototype._PTSNormalize=function(t,e){var r=void 0;if(void 0===e)return t;for(r=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=r;return t},t}();e.a=u},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=function(){function t(){i(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}();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")}var a=Math.pow(2,32)-1,n=function(){function t(){i(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=void 0;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=Array.prototype.slice.call(arguments,1),r=8,i=e.length,a=i,n=void 0;i--;)r+=e[i].byteLength;for(n=new Uint8Array(r),n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),i=0,r=8;i<a;i++)n.set(e[i],r),r+=e[i].byteLength;return n},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/(a+1)),n=Math.floor(r%(a+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,n>>24,n>>16&255,n>>8&255,255&n,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/(a+1)),n=Math.floor(r%(a+1)),o=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,n>>24,n>>16&255,n>>8&255,255&n,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,o)},t.sdtp=function(e){var r=e.samples||[],i=new Uint8Array(4+r.length),a=void 0,n=void 0;for(n=0;n<r.length;n++)a=r[n].flags,i[n+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return t.box(t.types.sdtp,i)},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=void 0,n=void 0,o=void 0;for(a=0;a<e.sps.length;a++)n=e.sps[a],o=n.byteLength,r.push(o>>>8&255),r.push(255&o),r=r.concat(Array.prototype.slice.call(n));for(a=0;a<e.pps.length;a++)n=e.pps[a],o=n.byteLength,i.push(o>>>8&255),i.push(255&o),i=i.concat(Array.prototype.slice.call(n));var s=t.box(t.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(i))),l=e.width,u=e.height,d=e.pixelRatio[0],c=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,c>>24,c>>16&255,c>>8&255,255&c])))},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,n=e.width,o=e.height,s=Math.floor(i/(a+1)),l=Math.floor(i%(a+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,s>>24,s>>16&255,s>>8&255,255&s,l>>24,l>>16&255,l>>8&255,255&l,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,n>>8&255,255&n,0,0,o>>8&255,255&o,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),n=e.id,o=Math.floor(r/(a+1)),s=Math.floor(r%(a+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,s>>24,s>>16&255,s>>8&255,255&s])),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=e.samples||[],a=i.length,n=12+16*a,o=new Uint8Array(n),s=void 0,l=void 0,u=void 0,d=void 0,c=void 0,h=void 0;for(r+=8+n,o.set([0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,255&a,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),s=0;s<a;s++)l=i[s],u=l.duration,d=l.size,c=l.flags,h=l.cts,o.set([u>>>24&255,u>>>16&255,u>>>8&255,255&u,d>>>24&255,d>>>16&255,d>>>8&255,255&d,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,h>>>24&255,h>>>16&255,h>>>8&255,255&h],12+16*s);return t.box(t.types.trun,o)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=void 0;return i=new Uint8Array(t.FTYP.byteLength+r.byteLength),i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(1),n=function(){function t(e){i(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,n,o,s,l){var u=this.observer,d="";t&&(d+="audio"),e&&(d+="video"),u.trigger(a.a.FRAG_PARSING_DATA,{data1:l,startPTS:n,startDTS:n,type:d,hasAudio:!!t,hasVideo:!!e,nb:1,dropped:0}),u.trigger(a.a.FRAG_PARSED)},t}();e.a=n},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=r(21),a=r(1),n=r(0),o=r(12),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},function(t,e,r){"use strict";function i(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments[2],i=0;if(r.programDateTime){var a=Date.parse(r.programDateTime);isNaN(a)||(i=1e3*e+a-1e3*t)}return i}function a(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(!Array.isArray(t)||!t.length||null===e)return null;if(e<t[0].pdt)return null;if(e>=t[t.length-1].endPdt)return null;for(var r=0;r<t.length;++r){var i=t[r];if(e<i.endPdt)return i}return null}function n(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,n=void 0,l=t?e[t.sn-e[0].sn+1]:null;return r<i&&(r>i-a&&(a=0),n=l&&!o(r,a,l)?l:s.a.search(e,o.bind(null,r,a))),n}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments[2],i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}e.a=i,e.b=a,e.c=n,e.d=o;var s=r(6)},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)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)}var o=r(1),s=r(3),l=r(0),u=r(2),d=r(19),c=r(15),h="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},f=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}}(),p=window,v=p.performance,g=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MANIFEST_LOADED,o.a.LEVEL_LOADED,o.a.AUDIO_TRACK_SWITCHED,o.a.FRAG_LOADED,o.a.ERROR));return n.canload=!1,n.currentLevelIndex=null,n.manualLevelIndex=-1,n.timer=null,n}return n(e,t),e.prototype.onHandlerDestroying=function(){this.clearTimer(),this.manualLevelIndex=-1},e.prototype.clearTimer=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)}),null!==this.timer&&this.loadLevel()},e.prototype.stopLoad=function(){this.canload=!1},e.prototype.onManifestLoaded=function(t){var e=[],r=void 0,i={},a=null,n=!1,s=!1,h=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),f=[];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),h&&t.audioCodec&&-1!==t.audioCodec.indexOf("mp4a.40.34")&&(t.audioCodec=void 0),a=i[t.bitrate],a?a.url.push(t.url):(t.url=[t.url],t.urlId=0,i[t.bitrate]=t,e.push(t)),t.attrs&&t.attrs.AUDIO&&Object(c.a)(a||t,"audio",t.attrs.AUDIO),t.attrs&&t.attrs.SUBTITLES&&Object(c.a)(a||t,"text",t.attrs.SUBTITLES)}),n&&s&&(e=e.filter(function(t){return!!t.videoCodec})),e=e.filter(function(t){var e=t.audioCodec,r=t.videoCodec;return(!e||Object(d.a)(e))&&(!r||Object(d.a)(r))}),t.audioTracks&&(f=t.audioTracks.filter(function(t){return!t.audioCodec||Object(d.a)(t.audioCodec,"audio")})),e.length>0){r=e[0].bitrate,e.sort(function(t,e){return t.bitrate-e.bitrate}),this._levels=e;for(var p=0;p<e.length;p++)if(e[p].bitrate===r){this._firstLevel=p,l.b.log("manifest loaded,"+e.length+" level(s) found, first bitrate:"+r);break}this.hls.trigger(o.a.MANIFEST_PARSED,{levels:e,audioTracks:f,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:n,altAudio:f.length>0&&n})}else this.hls.trigger(o.a.ERROR,{type:u.b.MEDIA_ERROR,details:u.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.clearTimer(),this.currentLevelIndex!==t){l.b.log("switching to level "+t),this.currentLevelIndex=t;var i=e[t];i.level=t,r.trigger(o.a.LEVEL_SWITCHING,i)}var a=e[t],n=a.details;if(!n||n.live){var s=a.urlId;r.trigger(o.a.LEVEL_LOADING,{url:a.url[s],level:t,id:s})}}else r.trigger(o.a.ERROR,{type:u.b.OTHER_ERROR,details:u.a.LEVEL_SWITCH_ERROR,level:t,fatal:!1,reason:"invalid level idx"})},e.prototype.onError=function(t){if(t.fatal)return void(t.type===u.b.NETWORK_ERROR&&this.clearTimer());var e=!1,r=!1,i=void 0;switch(t.details){case u.a.FRAG_LOAD_ERROR:case u.a.FRAG_LOAD_TIMEOUT:case u.a.KEY_LOAD_ERROR:case u.a.KEY_LOAD_TIMEOUT:i=t.frag.level,r=!0;break;case u.a.LEVEL_LOAD_ERROR:case u.a.LEVEL_LOAD_TIMEOUT:i=t.context.level,e=!0;break;case u.a.REMUX_ALLOC_ERROR:i=t.level,e=!0}void 0!==i&&this.recoverLevel(t,i,e,r)},e.prototype.recoverLevel=function(t,e,r,i){var a=this,n=this.hls.config,o=t.details,s=this._levels[e],u=void 0,d=void 0,c=void 0;if(s.loadError++,s.fragmentError=i,r){if(!(this.levelRetryCount+1<=n.levelLoadingMaxRetry))return l.b.error("level controller, cannot recover from "+o+" error"),this.currentLevelIndex=null,this.clearTimer(),void(t.fatal=!0);d=Math.min(Math.pow(2,this.levelRetryCount)*n.levelLoadingRetryDelay,n.levelLoadingMaxRetryTimeout),this.timer=setTimeout(function(){return a.loadLevel()},d),t.levelRetry=!0,this.levelRetryCount++,l.b.warn("level controller, "+o+", retry in "+d+" ms, current retry count is "+this.levelRetryCount)}(r||i)&&(u=s.url.length,u>1&&s.loadError<u?(s.urlId=(s.urlId+1)%u,s.details=void 0,l.b.warn("level controller, "+o+" for level "+e+": switching to redundant URL-id "+s.urlId)):-1===this.manualLevelIndex?(c=0===e?this._levels.length-1:e-1,l.b.warn("level controller, "+o+": switch to "+c),this.hls.nextAutoLevel=this.currentLevelIndex=c):i&&(l.b.warn("level controller, "+o+": reload a fragment"),this.currentLevelIndex=null))},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.currentLevelIndex){var i=this._levels[r];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=n,s=i.details;s&&a.endSN===s.endSN&&(o/=2,l.b.log("same live playlist, reload twice faster")),o-=v.now()-t.stats.trequest,o=Math.max(n/2,Math.round(o)),l.b.log("live playlist, reload in "+Math.round(o)+" ms"),this.timer=setTimeout(function(){return e.loadLevel()},o)}else this.clearTimer()}},e.prototype.onAudioTrackSwitched=function(t){var e=this.hls.audioTracks[t.id].groupId,r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){var i=r.audioGroupIds.findIndex(function(t){return t===e});i!==r.urlId&&(r.urlId=i,this.startLoad())}},e.prototype.loadLevel=function(){if(l.b.debug("call to loadLevel"),null!==this.currentLevelIndex&&this.canload){var t=this._levels[this.currentLevelIndex];if("object"===(void 0===t?"undefined":h(t))&&t.url.length>0){var e=this.currentLevelIndex,r=t.urlId,i=t.url[r];l.b.log("Attempt loading level index "+e+" with URL-id "+r),this.hls.trigger(o.a.LEVEL_LOADING,{url:i,level:e,id:r})}}},f(e,[{key:"levels",get:function(){return this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e=this._levels;e&&(t=Math.min(t,e.length-1),this.currentLevelIndex===t&&e[t].details||this.setLevelInternal(t))}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=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.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}]),e}(s.a);e.a=g},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)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)}var o=r(1),s=r(3),l=r(7),u=r(26),d=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MEDIA_ATTACHED,o.a.MEDIA_DETACHING,o.a.FRAG_PARSING_METADATA));return n.id3Track=void 0,n.media=void 0,n}return n(e,t),e.prototype.destroy=function(){s.a.prototype.destroy.call(this)},e.prototype.onMediaAttached=function(t){this.media=t.media,this.media},e.prototype.onMediaDetaching=function(){Object(u.a)(this.id3Track),this.id3Track=void 0,this.media=void 0},e.prototype.getID3Track=function(t){for(var e=0;e<t.length;e++){var r=t[e];if("metadata"===r.kind&&"id3"===r.label)return Object(u.b)(r,this.media),r}return this.media.addTextTrack("metadata","id3")},e.prototype.onFragParsingMetadata=function(t){var e=t.frag,r=t.samples;this.id3Track||(this.id3Track=this.getID3Track(this.media.textTracks),this.id3Track.mode="hidden");for(var i=window.WebKitDataCue||window.VTTCue||window.TextTrackCue,a=0;a<r.length;a++){var n=l.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 u=0;u<n.length;u++){var d=n[u];if(!l.a.isTimeStampFrame(d)){var c=new i(o,s,"");c.value=d,this.id3Track.addCue(c)}}}}},e}(s.a);e.a=d},function(t,e,r){"use strict";function i(){var t=Object(a.a)(),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}e.a=i;var a=r(14)},function(t,e,r){"use strict";r.d(e,"a",function(){return g});var i=r(53),a=r(56),n=r(57),o=r(58),s=r(59),l=r(60),u=r(61),d=r(62),c=r(64),h=r(68),f=r(69),p=r(70),v=r(71),g={autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,initialLiveManifestSize:1,maxBufferLength:30,maxBufferSize:6e7,maxBufferHole:.5,lowBufferWatchdogPeriod:.5,highBufferWatchdogPeriod:3,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,liveDurationInfinity:!1,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,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:s.a,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,abrController:i.a,bufferController:a.a,capLevelController:n.a,fpsController:o.a,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,emeEnabled:!1,widevineLicenseUrl:void 0,requestMediaKeySystemAccessFunc:v.a};g.subtitleStreamController=f.a,g.subtitleTrackController=h.a,g.timelineController=c.a,g.cueHandler=d,g.enableCEA708Captions=!0,g.enableWebVTT=!0,g.captionsTextTrack1Label="English",g.captionsTextTrack1LanguageCode="en",g.captionsTextTrack2Label="Spanish",g.captionsTextTrack2LanguageCode="es",g.audioStreamController=u.a,g.audioTrackController=l.a,g.emeController=p.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)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)}var o=r(1),s=r(3),l=r(11),u=r(2),d=r(0),c=r(54),h=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}}(),f=window,p=f.performance,v=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.FRAG_LOADING,o.a.FRAG_LOADED,o.a.FRAG_BUFFERED,o.a.ERROR));return n.lastLoadedFragLevel=0,n._nextAutoLevel=-1,n.hls=r,n.timer=null,n._bwEstimator=null,n.onCheck=n._abandonRulesCheck.bind(n),n}return n(e,t),e.prototype.destroy=function(){this.clearTimer(),s.a.prototype.destroy.call(this)},e.prototype.onFragLoading=function(t){var e=t.frag;if("main"===e.type&&(this.timer||(this.fragCurrent=e,this.timer=setInterval(this.onCheck,100)),!this._bwEstimator)){var r=this.hls,i=r.config,a=e.level,n=r.levels[a].details.live,o=void 0,s=void 0;n?(o=i.abrEwmaFastLive,s=i.abrEwmaSlowLive):(o=i.abrEwmaFastVoD,s=i.abrEwmaSlowVoD),this._bwEstimator=new c.a(r,s,o,i.abrEwmaDefaultEstimate)}},e.prototype._abandonRulesCheck=function(){var t=this.hls,e=t.media,r=this.fragCurrent;if(r){var i=r.loader,a=t.minAutoLevel;if(!i||i.stats&&i.stats.aborted)return d.b.warn("frag loader destroy or aborted, disarm abandonRules"),this.clearTimer(),void(this._nextAutoLevel=-1);var n=i.stats;if(e&&n&&(!e.paused&&0!==e.playbackRate||!e.readyState)&&r.autoLevel&&r.level){var s=p.now()-n.trequest,u=Math.abs(e.playbackRate);if(s>500*r.duration/u){var c=t.levels,h=Math.max(1,n.bw?n.bw/8:1e3*n.loaded/s),f=c[r.level],v=f.realBitrate?Math.max(f.realBitrate,f.bitrate):f.bitrate,g=n.total?n.total:Math.max(n.loaded,Math.round(r.duration*v/8)),y=e.currentTime,m=(g-n.loaded)/h,b=(l.a.bufferInfo(e,y,t.config.maxBufferHole).end-y)/u;if(b<2*r.duration/u&&m>b){var E=void 0,T=void 0;for(T=r.level-1;T>a;T--){var S=c[T].realBitrate?Math.max(c[T].realBitrate,c[T].bitrate):c[T].bitrate;if((E=r.duration*S/(6.4*h))<b)break}E<m&&(d.b.warn("loading too slow, abort fragment loading and switch to level "+T+":fragLoadedDelay["+T+"]<fragLoadedDelay["+(r.level-1)+"];bufferStarvationDelay:"+E.toFixed(1)+"<"+m.toFixed(1)+":"+b.toFixed(1)),t.nextLoadLevel=T,this._bwEstimator.sample(s,n.loaded),i.abort(),this.clearTimer(),t.trigger(o.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||"main"!==r.type||isNaN(r.sn)||r.bitrateTest&&e.tload!==e.tbuffered)){var i=e.tparsed-e.trequest;d.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 u.a.FRAG_LOAD_ERROR:case u.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 c=l[u],h=c.details,f=h?h.totalduration/h.fragments.length:e,p=!!h&&h.live,v=void 0;v=u<=t?o*r:s*r;var g=l[u].realBitrate?Math.max(l[u].realBitrate,l[u].bitrate):l[u].bitrate,y=g*f/v;if(d.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+u+"/"+Math.round(v)+"/"+g+"/"+f+"/"+n+"/"+y),v>g&&(!y||p&&!this.bitrateTestDelay||y<n))return u}return-1},h(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,u=n?n.currentTime:0,c=n&&0!==n.playbackRate?Math.abs(n.playbackRate):1,h=this._bwEstimator?this._bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,f=(l.a.bufferInfo(n,u,i.maxBufferHole).end-u)/c,p=this._findBestLevel(o,s,h,a,e,f,i.abrBandWidthFactor,i.abrBandWidthUpFactor,r);if(p>=0)return p;d.b.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var v=s?Math.min(s,i.maxStarvationDelay):i.maxStarvationDelay,g=i.abrBandWidthFactor,y=i.abrBandWidthUpFactor;if(0===f){var m=this.bitrateTestDelay;if(m){v=(s?Math.min(s,i.maxLoadingDelay):i.maxLoadingDelay)-m,d.b.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*v)+" ms"),g=y=1}}return p=this._findBestLevel(o,s,h,a,e,f+v,g,y,r),Math.max(p,0)}}]),e}(s.a);e.a=v},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(55),n=function(){function t(e,r,n,o){i(this,t),this.hls=e,this.defaultEstimate_=o,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new a.a(r),this.fast_=new a.a(n)}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}();e.a=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=function(){function t(e){i(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.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)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)}var o=r(1),s=r(3),l=r(0),u=r(2),d=r(14),c=Object(d.a)(),h=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MEDIA_ATTACHING,o.a.MEDIA_DETACHING,o.a.MANIFEST_PARSED,o.a.BUFFER_RESET,o.a.BUFFER_APPENDING,o.a.BUFFER_CODECS,o.a.BUFFER_EOS,o.a.BUFFER_FLUSHING,o.a.LEVEL_PTS_UPDATED,o.a.LEVEL_UPDATED));return n._msDuration=null,n._levelDuration=null,n._live=null,n._objectUrl=null,n.onsbue=n.onSBUpdateEnd.bind(n),n.onsbe=n.onSBUpdateError.bind(n),n.pendingTracks={},n.tracks={},n}return n(e,t),e.prototype.destroy=function(){s.a.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,l.b.warn("can not abort audio buffer: "+t)}a?this.audioTimestampOffset=t.start:(l.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.altAudio,i=0;t.altAudio&&(e||r)&&(i=(e?1:0)+(r?1:0),l.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 c;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=window.URL.createObjectURL(r),this._objectUrl=e.src}},e.prototype.onMediaDetaching=function(){l.b.log("media source detaching");var t=this.mediaSource;if(t){if("open"===t.readyState)try{t.endOfStream()}catch(t){l.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&&(window.URL.revokeObjectURL(this._objectUrl),this.media.src===this._objectUrl?(this.media.removeAttribute("src"),this.media.load()):l.b.warn("media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.onmso=this.onmse=this.onmsc=null,this.hls.trigger(o.a.MEDIA_DETACHED)},e.prototype.onMediaSourceOpen=function(){l.b.log("media source opened"),this.hls.trigger(o.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(){l.b.log("media source closed")},e.prototype.onMediaSourceEnded=function(){l.b.log("media source ended")},e.prototype.onSBUpdateEnd=function(){if(this.audioTimestampOffset){var t=this.sourceBuffer.audio;l.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),i={},a=this.sourceBuffer;for(var n in a)i[n]=a[n].buffered;this.hls.trigger(o.a.BUFFER_APPENDED,{parent:e,pending:r,timeRanges:i}),this._needsFlush||this.doAppending(),this.updateMediaElementDuration()},e.prototype.onSBUpdateError=function(t){l.b.error("sourceBuffer error:",t),this.hls.trigger(o.a.ERROR,{type:u.b.MEDIA_ERROR,details:u.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,s=a.container+";codecs="+n;l.b.log("creating sourceBuffer("+s+")");try{var d=e[i]=r.addSourceBuffer(s);d.addEventListener("updateend",this.onsbue),d.addEventListener("error",this.onsbe),this.tracks[i]={codec:n,container:a.container},a.buffer=d}catch(t){l.b.error("error while trying to add sourceBuffer:"+t.message),this.hls.trigger(o.a.ERROR,{type:u.b.MEDIA_ERROR,details:u.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:t,mimeType:s})}}this.hls.trigger(o.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){l.b.error("sourceBuffer error:",t.event),this.hls.trigger(o.a.ERROR,{type:u.b.MEDIA_ERROR,details:u.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,l.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)}l.b.log("all media data available, signal endOfStream() to MediaSource and stop loading fragment");try{e.endOfStream()}catch(t){l.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;e.fragments.length>0&&(this._levelDuration=e.totalduration+e.fragments[0].start,this._live=e.live,this.updateMediaElementDuration())},e.prototype.updateMediaElementDuration=function(){var t=this.hls.config,e=void 0;if(null!==this._levelDuration&&this.media&&this.mediaSource&&this.sourceBuffer&&0!==this.media.readyState&&"open"===this.mediaSource.readyState){for(var r in this.sourceBuffer)if(!0===this.sourceBuffer[r].updating)return;e=this.media.duration,null===this._msDuration&&(this._msDuration=this.mediaSource.duration),!0===this._live&&!0===t.liveDurationInfinity?(l.b.log("Media Source duration is set to Infinity"),this._msDuration=this.mediaSource.duration=1/0):(this._levelDuration>this._msDuration&&this._levelDuration>e||e===1/0||isNaN(e))&&(l.b.log("Updating Media Source duration to "+this._levelDuration.toFixed(3)),this._msDuration=this.mediaSource.duration=this._levelDuration)}},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){l.b.error("error while accessing sourceBuffer.buffered")}this.appended=e,this.hls.trigger(o.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 l.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){l.b.error("error while trying to append buffer:"+e.message),r.unshift(i);var s={type:u.b.MEDIA_ERROR,parent:i.parent};22!==e.code?(this.appendError?this.appendError++:this.appendError=1,s.details=u.a.BUFFER_APPEND_ERROR,this.appendError>t.config.appendErrorMaxRetry?(l.b.log("fail "+t.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),r=[],s.fatal=!0,t.trigger(o.a.ERROR,s)):(s.fatal=!1,t.trigger(o.a.ERROR,s))):(this.segments=[],s.details=u.a.BUFFER_FULL_ERROR,s.fatal=!1,t.trigger(o.a.ERROR,s))}}}},e.prototype.flushBuffer=function(t,e,r){var i=void 0,a=void 0,n=void 0,o=void 0,s=void 0,u=void 0,d=this.sourceBuffer;if(Object.keys(d).length){if(l.b.log("flushBuffer,pos/start/end: "+this.media.currentTime.toFixed(3)+"/"+t+"/"+e),this.flushBufferCounter<this.appended){for(var c in d)if(!r||c===r){if(i=d[c],i.ended=!1,i.updating)return l.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,u=e):(s=Math.max(n,t),u=Math.min(o,e)),Math.min(u,o)-s>.5)return this.flushBufferCounter++,l.b.log("flush "+c+" ["+s+","+u+"], of ["+n+","+o+"], pos:"+this.media.currentTime),i.remove(s,u),!1}catch(t){l.b.warn("exception while accessing sourcebuffer, it might have been removed from MediaSource")}}}else l.b.warn("abort flushing too many retries");l.b.log("buffer flushed")}return!0},e}(s.a);e.a=h},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)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)}var o=r(1),s=r(3),l=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}}(),u=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.FPS_DROP_LEVEL_CAPPING,o.a.MEDIA_ATTACHING,o.a.MANIFEST_PARSED,o.a.BUFFER_CODECS));return n.autoLevelCapping=Number.POSITIVE_INFINITY,n.firstLevel=null,n.levels=[],n.media=null,n.restrictedLevels=[],n.timer=null,n}return n(e,t),e.prototype.destroy=function(){this.hls.config.capLevelToPlayerSize&&(this.media=null,this._stopCapping())},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 window.HTMLVideoElement?t.media:null},e.prototype.onManifestParsed=function(t){var e=this.hls;this.restrictedLevels=[],this.levels=t.levels,this.firstLevel=t.firstLevel,e.config.capLevelToPlayerSize&&(t.video||t.levels.length&&t.altAudio)&&this._startCapping()},e.prototype.onBufferCodecs=function(t){this.hls.config.capLevelToPlayerSize&&t.video&&this._startCapping()},e.prototype.onLevelsUpdated=function(t){this.levels=t.levels},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.prototype._startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),clearInterval(this.timer),this.timer=setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},e.prototype._stopCapping=function(){this.restrictedLevels=[],this.firstLevel=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer),this.timer=null)},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},l(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}(s.a);e.a=u},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)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)}var o=r(1),s=r(3),l=r(0),u=window,d=u.performance,c=function(t){function e(r){return i(this,e),a(this,t.call(this,r,o.a.MEDIA_ATTACHING))}return n(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 window.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=d.now();if(e){if(this.lastTime){var a=i-this.lastTime,n=r-this.lastDroppedFrames,s=e-this.lastDecodedFrames,u=1e3*n/a,c=this.hls;if(c.trigger(o.a.FPS_DROP,{currentDropped:n,currentDecoded:s,totalDroppedFrames:r}),u>0&&n>c.config.fpsDroppedMonitoringThreshold*s){var h=c.currentLevel;l.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===c.autoLevelCapping||c.autoLevelCapping>=h)&&(h-=1,c.trigger(o.a.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,c.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}(s.a);e.a=c},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=r(0),n=window,o=n.performance,s=n.XMLHttpRequest,l=function(){function t(e){i(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:o.now(),retry:0},this.retryDelay=e.retryDelay,this.loadInternal()},t.prototype.loadInternal=function(){var t=void 0,e=this.context;t=this.loader=new s;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,n=this.context,s=this.config;if(!i.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(o.now(),i.trequest)),4===r){var l=e.status;if(l>=200&&l<300){i.tload=Math.max(i.tfirst,o.now());var u=void 0,d=void 0;"arraybuffer"===n.responseType?(u=e.response,d=u.byteLength):(u=e.responseText,d=u.length),i.loaded=i.total=d;var c={url:e.responseURL,data:u};this.callbacks.onSuccess(c,i,n,e)}else i.retry>=s.maxRetry||l>=400&&l<499?(a.b.error(l+" while loading "+n.url),this.callbacks.onError({code:l,text:e.statusText},n,e)):(a.b.warn(l+" while loading "+n.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,s.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),s.timeout)},t.prototype.loadtimeout=function(){a.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}();e.a=l},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)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)}var o=r(1),s=r(8),l=r(0),u=r(2),d=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}}(),c=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MANIFEST_LOADING,o.a.MANIFEST_PARSED,o.a.AUDIO_TRACK_LOADED,o.a.AUDIO_TRACK_SWITCHED,o.a.LEVEL_LOADED,o.a.ERROR));return n.trackId=-1,n.tracks=[],n.trackIdBlacklist=Object.create(null),n.audioGroupId=null,n}return n(e,t),e.prototype.onManifestLoading=function(){this.tracks=[],this.trackId=-1},e.prototype.onManifestParsed=function(t){var e=this.tracks=t.audioTracks||[];this.hls.trigger(o.a.AUDIO_TRACKS_UPDATED,{audioTracks:e})},e.prototype.onAudioTrackLoaded=function(t){if(t.id>=this.tracks.length)return void l.b.warn("Invalid audio track id:",t.id);if(l.b.log("audioTrack "+t.id+" loaded"),this.tracks[t.id].details=t.details,t.details.live&&!this.hasInterval()){var e=1e3*t.details.targetduration;this.setInterval(e)}!t.details.live&&this.hasInterval()&&this.clearInterval()},e.prototype.onAudioTrackSwitched=function(t){var e=this.tracks[t.id].groupId;e&&this.audioGroupId!==e&&(this.audioGroupId=e)},e.prototype.onLevelLoaded=function(t){var e=this.hls.levels[t.level];if(e.audioGroupIds){var r=e.audioGroupIds[e.urlId];this.audioGroupId!==r&&(this.audioGroupId=r,this._selectInitialAudioTrack())}},e.prototype.onError=function(t){t.type===u.b.NETWORK_ERROR&&(t.fatal&&this.clearInterval(),t.details===u.a.AUDIO_TRACK_LOAD_ERROR&&(l.b.warn("Network failure on audio-track id:",t.context.id),this._handleLoadError()))},e.prototype.doTick=function(){this._updateTrack(this.trackId)},e.prototype._selectInitialAudioTrack=function(){var t=this,e=this.tracks;if(e.length){var r=this.tracks[this.trackId],i=null;r&&(i=r.name);var a=e.filter(function(t){return t.default});a.length?e=a:l.b.warn("No default audio tracks defined");var n=!1,s=function(){e.forEach(function(e){n||t.audioGroupId&&e.groupId!==t.audioGroupId||i&&i!==e.name||(t.audioTrack=e.id,n=!0)})};s(),n||(i=null,s()),n||(l.b.error("No track found for running audio group-ID: "+this.audioGroupId),this.hls.trigger(o.a.ERROR,{type:u.b.MEDIA_ERROR,details:u.a.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))}},e.prototype._needsTrackLoading=function(t){var e=t.details;return!e||(!!e.live||void 0)},e.prototype._loadTrackDetailsIfNeeded=function(t){if(this._needsTrackLoading(t)){var e=t.url,r=t.id;l.b.log("loading audio-track playlist for id: "+r),this.hls.trigger(o.a.AUDIO_TRACK_LOADING,{url:e,id:r})}},e.prototype._updateTrack=function(t){if(!(t<0||t>=this.tracks.length)){this.clearInterval(),this.trackId=t,l.b.log("trying to update audio-track "+t);var e=this.tracks[t];this._loadTrackDetailsIfNeeded(e)}},e.prototype._handleLoadError=function(){this.trackIdBlacklist[this.trackId]=!0;var t=this.trackId,e=this.tracks[t],r=e.name,i=e.language,a=e.groupId;l.b.warn("Loading failed on audio track id: "+t+", group-id: "+a+', name/language: "'+r+'" / "'+i+'"');for(var n=t,o=0;o<this.tracks.length;o++)if(!this.trackIdBlacklist[o]){var s=this.tracks[o];if(s.name===r){n=o;break}}if(n===t)return void l.b.warn('No fallback audio-track found for name/language: "'+r+'" / "'+i+'"');l.b.log("Attempting audio-track fallback id:",n,"group-id:",this.tracks[n].groupId),this.audioTrack=n},d(e,[{key:"audioTracks",get:function(){return this.tracks}},{key:"audioTrack",get:function(){return this.trackId},set:function(t){if(this.trackId===t&&this.tracks[this.trackId].details)return void l.b.debug("Same id as current audio-track passed, and track details available -> no-op");if(t<0||t>=this.tracks.length)return void l.b.warn("Invalid id passed to audio-track controller");var e=this.tracks[t];l.b.log("Now switching to audio-track index "+t),this.clearInterval(),this.trackId=t;var r=e.url,i=e.type,a=e.id;this.hls.trigger(o.a.AUDIO_TRACK_SWITCHING,{id:a,type:i,url:r}),this._loadTrackDetailsIfNeeded(e)}}]),e}(s.a);e.a=c},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)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)}var o=r(6),s=r(11),l=r(20),u=r(1),d=r(15),c=r(24),h=r(2),f=r(0),p=r(25),v=r(8),g=r(10),y=r(9),m=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}}(),b=window,E=b.performance,T={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"},S=function(t){function e(r,n){i(this,e);var o=a(this,t.call(this,r,u.a.MEDIA_ATTACHED,u.a.MEDIA_DETACHING,u.a.AUDIO_TRACKS_UPDATED,u.a.AUDIO_TRACK_SWITCHING,u.a.AUDIO_TRACK_LOADED,u.a.KEY_LOADED,u.a.FRAG_LOADED,u.a.FRAG_PARSING_INIT_SEGMENT,u.a.FRAG_PARSING_DATA,u.a.FRAG_PARSED,u.a.ERROR,u.a.BUFFER_RESET,u.a.BUFFER_CREATED,u.a.BUFFER_APPENDED,u.a.BUFFER_FLUSHED,u.a.INIT_PTS_FOUND));return o.fragmentTracker=n,o.config=r.config,o.audioCodecSwap=!1,o._state=T.STOPPED,o.initPTS=[],o.waitingFragment=null,o.videoTrackCC=null,o}return n(e,t),e.prototype.onHandlerDestroying=function(){this.stopLoad(),t.prototype.onHandlerDestroying.call(this)},e.prototype.onHandlerDestroyed=function(){this.state=T.STOPPED,this.fragmentTracker=null,t.prototype.onHandlerDestroyed.call(this)},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,f.b.log("InitPTS for cc: "+r+" found from video track: "+i),this.state===T.WAITING_INIT_PTS&&this.tick())},e.prototype.startLoad=function(t){if(this.tracks){var e=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),this.fragLoadError=0,e>0&&-1===t?(f.b.log("audio:override startPosition with lastCurrentTime @"+e.toFixed(3)),this.state=T.IDLE):(this.lastCurrentTime=this.startPosition?this.startPosition:t,this.state=T.STARTING),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=t,this.state=T.STOPPED},e.prototype.stopLoad=function(){var t=this.fragCurrent;t&&(t.loader&&t.loader.abort(),this.fragmentTracker.removeFragment(t),this.fragCurrent=null),this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=T.STOPPED},e.prototype.doTick=function(){var t=void 0,e=void 0,r=void 0,i=this.hls,a=i.config;switch(this.state){case T.ERROR:case T.PAUSED:case T.BUFFER_FLUSHING:break;case T.STARTING:this.state=T.WAITING_TRACK,this.loadedmetadata=!1;break;case T.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 l=this.mediaBuffer?this.mediaBuffer:this.media,d=this.videoBuffer?this.videoBuffer:this.media,c=s.a.bufferInfo(l,t,a.maxBufferHole),h=s.a.bufferInfo(d,t,a.maxBufferHole),v=c.len,y=c.end,m=this.fragPrevious,b=Math.min(a.maxBufferLength,a.maxMaxBufferLength),S=Math.max(b,h.len),R=this.audioSwitch,A=this.trackId;if((v<S||R)&&A<n.length){if(void 0===(r=n[A].details)){this.state=T.WAITING_TRACK;break}if(!R&&!r.live&&m&&m.sn===r.endSN&&!c.nextStart&&(!this.media.seeking||this.media.duration-y<m.duration/2)){this.hls.trigger(u.a.BUFFER_EOS,{type:"audio"}),this.state=T.ENDED;break}var _=r.fragments,w=_.length,L=_[0].start,D=_[w-1].start+_[w-1].duration,I=void 0;if(R)if(r.live&&!r.PTSKnown)f.b.log("switching audiotrack, live stream, unknown PTS,load first fragment"),y=0;else if(y=t,r.PTSKnown&&t<L){if(!(c.end>L||c.nextStart))return;f.b.log("alt audio track ahead of main track, seek to start of alt audio track"),this.media.currentTime=L+.05}if(r.initSegment&&!r.initSegment.data)I=r.initSegment;else if(y<=L){if(I=_[0],null!==this.videoTrackCC&&I.cc!==this.videoTrackCC&&(I=Object(p.b)(_,this.videoTrackCC)),r.live&&I.loadIdx&&I.loadIdx===this.fragLoadIdx){var k=c.nextStart?c.nextStart:L;return f.b.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(k+.05)),void(this.media.currentTime=k+.05)}}else{var O=void 0,C=a.maxFragLookUpTolerance,P=m?_[m.sn-_[0].sn+1]:void 0,x=function(t){var e=Math.min(C,t.duration);return t.start+t.duration-e<=y?1:t.start-e>y&&t.start?-1:0};y<D?(y>D-C&&(C=0),O=P&&!x(P)?P:o.a.search(_,x)):O=_[w-1],O&&(I=O,L=O.start,m&&I.level===m.level&&I.sn===m.sn&&(I.sn<r.endSN?(I=_[I.sn+1-r.startSN],f.b.log("SN just loaded, load next one: "+I.sn)):I=null))}I&&(I.encrypted?(f.b.log("Loading key for "+I.sn+" of ["+r.startSN+" ,"+r.endSN+"],track "+A),this.state=T.KEY_LOADING,i.trigger(u.a.KEY_LOADING,{frag:I})):(f.b.log("Loading "+I.sn+", cc: "+I.cc+" of ["+r.startSN+" ,"+r.endSN+"],track "+A+", currentTime:"+t+",bufferEnd:"+y.toFixed(3)),(R||this.fragmentTracker.getState(I)===g.a.NOT_LOADED)&&(this.fragCurrent=I,this.startFragRequested=!0,isNaN(I.sn)||(this.nextLoadPosition=I.start+I.duration),i.trigger(u.a.FRAG_LOADING,{frag:I}),this.state=T.FRAG_LOADING)))}break;case T.WAITING_TRACK:e=this.tracks[this.trackId],e&&e.details&&(this.state=T.IDLE);break;case T.FRAG_LOADING_WAITING_RETRY:var F=E.now(),N=this.retryDate;l=this.media;var M=l&&l.seeking;(!N||F>=N||M)&&(f.b.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=T.IDLE);break;case T.WAITING_INIT_PTS:var U=this.videoTrackCC;if(void 0===this.initPTS[U])break;var B=this.waitingFragment;if(B){var G=B.frag.cc;U!==G?(e=this.tracks[this.trackId],e.details&&e.details.live&&(f.b.warn("Waiting fragment CC ("+G+") does not match video track CC ("+U+")"),this.waitingFragment=null,this.state=T.IDLE)):(this.state=T.FRAG_LOADING,this.onFragLoaded(this.waitingFragment),this.waitingFragment=null)}else this.state=T.IDLE;break;case T.STOPPED:case T.FRAG_LOADING:case T.PARSING:case T.PARSED:case T.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&&(f.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=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===T.ENDED&&(this.state=T.IDLE),this.media&&(this.lastCurrentTime=this.media.currentTime),this.tick()},e.prototype.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},e.prototype.onAudioTracksUpdated=function(t){f.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=T.PAUSED,this.waitingFragment=null,e?this.setInterval(100):this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),e&&(this.audioSwitch=!0,this.state=T.IDLE),this.tick()},e.prototype.onAudioTrackLoaded=function(t){var e=t.details,r=t.id,i=this.tracks[r],a=e.totalduration,n=0;if(f.b.log("track "+r+" loaded ["+e.startSN+","+e.endSN+"],duration:"+a),e.live){var o=i.details;o&&e.fragments.length>0?(d.b(o,e),n=e.fragments[0].start,e.PTSKnown?f.b.log("live audio playlist sliding:"+n.toFixed(3)):f.b.log("live audio playlist - outdated PTS, unknown sliding")):(e.PTSKnown=!1,f.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:(f.b.log("start time offset found in playlist, adjust startPosition to "+s),this.startPosition=s)}this.nextLoadPosition=this.startPosition}this.state===T.WAITING_TRACK&&(this.state=T.IDLE),this.tick()},e.prototype.onKeyLoaded=function(){this.state===T.KEY_LOADING&&(this.state=T.IDLE,this.tick())},e.prototype.onFragLoaded=function(t){var e=this.fragCurrent,r=t.frag;if(this.state===T.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,d=e.cc,c=this.config.defaultAudioCodec||i.audioCodec||"mp4a.40.2",h=this.stats=t.stats;if("initSegment"===s)this.state=T.IDLE,h.tparsed=h.tbuffered=E.now(),a.initSegment.data=t.payload,this.hls.trigger(u.a.FRAG_BUFFERED,{stats:h,frag:e,id:"audio"}),this.tick();else{this.state=T.PARSING,this.appended=!1,this.demuxer||(this.demuxer=new l.a(this.hls,"audio"));var p=this.initPTS[d],v=a.initSegment?a.initSegment.data:[];if(a.initSegment||void 0!==p){this.pendingBuffering=!0,f.b.log("Demuxing "+s+" of ["+a.startSN+" ,"+a.endSN+"],track "+o);this.demuxer.push(t.payload,v,c,null,e,n,!1,p)}else f.b.log("unknown video PTS for continuity counter "+d+", waiting for video PTS before demuxing audio frag "+s+" of ["+a.startSN+" ,"+a.endSN+"],track "+o),this.waitingFragment=t,this.state=T.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===T.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(u.a.BUFFER_CODECS,i),f.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(u.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===T.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),r.addElementaryStream(y.a.ElementaryStreamTypes.AUDIO),f.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),d.c(n.details,r,t.startPTS,t.endPTS);var s=this.audioSwitch,l=this.media,c=!1;if(s&&l)if(l.readyState){var p=l.currentTime;f.b.log("switching audio track : currentTime:"+p),p>=t.startPTS&&(f.b.log("switching audio track : flushing all audio"),this.state=T.BUFFER_FLUSHING,o.trigger(u.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),c=!0,this.audioSwitch=!1,o.trigger(u.a.AUDIO_TRACK_SWITCHED,{id:a}))}else this.audioSwitch=!1,o.trigger(u.a.AUDIO_TRACK_SWITCHED,{id:a});var v=this.pendingData;if(!v)return f.b.warn("Apparently attempt to enqueue media payload without codec initialization data upfront"),void o.trigger(u.a.ERROR,{type:h.b.MEDIA_ERROR,details:null,fatal:!0});this.audioSwitch||([t.data1,t.data2].forEach(function(e){e&&e.length&&v.push({type:t.type,data:e,parent:"audio",content:"data"})}),!c&&v.length&&(v.forEach(function(t){e.state===T.PARSING&&(e.pendingBuffering=!0,e.hls.trigger(u.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===T.PARSING&&(this.stats.tparsed=E.now(),this.state=T.PARSED,this._checkAppendedParsed())},e.prototype.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},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!==T.PARSING&&e!==T.PARSED||(this.pendingBuffering=t.pending>0,this._checkAppendedParsed())}},e.prototype._checkAppendedParsed=function(){if(!(this.state!==T.PARSED||this.appended&&this.pendingBuffering)){var t=this.fragCurrent,e=this.stats,r=this.hls;if(t){this.fragPrevious=t,e.tbuffered=E.now(),r.trigger(u.a.FRAG_BUFFERED,{stats:e,frag:t,id:"audio"});var i=this.mediaBuffer?this.mediaBuffer:this.media;f.b.log("audio buffered : "+c.a.toString(i.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(u.a.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=T.IDLE}this.tick()}},e.prototype.onError=function(t){var e=t.frag;if(!e||"audio"===e.type)switch(t.details){case h.a.FRAG_LOAD_ERROR:case h.a.FRAG_LOAD_TIMEOUT:var r=t.frag;if(r&&"audio"!==r.type)break;if(!t.fatal){var i=this.fragLoadError;i?i++:i=1;var a=this.config;if(i<=a.fragLoadingMaxRetry){this.fragLoadError=i;var n=Math.min(Math.pow(2,i-1)*a.fragLoadingRetryDelay,a.fragLoadingMaxRetryTimeout);f.b.warn("AudioStreamController: frag loading failed, retry in "+n+" ms"),this.retryDate=E.now()+n,this.state=T.FRAG_LOADING_WAITING_RETRY}else f.b.error("AudioStreamController: "+t.details+" reaches max retry, redispatch as fatal ..."),t.fatal=!0,this.state=T.ERROR}break;case h.a.AUDIO_TRACK_LOAD_ERROR:case h.a.AUDIO_TRACK_LOAD_TIMEOUT:case h.a.KEY_LOAD_ERROR:case h.a.KEY_LOAD_TIMEOUT:this.state!==T.ERROR&&(this.state=t.fatal?T.ERROR:T.IDLE,f.b.warn("AudioStreamController: "+t.details+" while loading frag, now switching to "+this.state+" state ..."));break;case h.a.BUFFER_FULL_ERROR:if("audio"===t.parent&&(this.state===T.PARSING||this.state===T.PARSED)){var o=this.mediaBuffer,l=this.media.currentTime;if(o&&s.a.isBuffered(o,l)&&s.a.isBuffered(o,l+.5)){var d=this.config;d.maxMaxBufferLength>=d.maxBufferLength&&(d.maxMaxBufferLength/=2,f.b.warn("AudioStreamController: reduce max buffer length to "+d.maxMaxBufferLength+"s")),this.state=T.IDLE}else f.b.warn("AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=T.BUFFER_FLUSHING,this.hls.trigger(u.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}},e.prototype.onBufferFlushed=function(){var t=this,e=this.pendingData;e&&e.length?(f.b.log("AudioStreamController: appending pending audio data after buffer flushed"),e.forEach(function(e){t.hls.trigger(u.a.BUFFER_APPENDING,e)}),this.appended=!0,this.pendingData=[],this.state=T.PARSED):(this.state=T.IDLE,this.fragPrevious=null,this.tick())},m(e,[{key:"state",set:function(t){if(this.state!==t){var e=this.state;this._state=t,f.b.log("audio stream:"+e+"->"+t)}},get:function(){return this._state}}]),e}(v.a);e.a=S},function(t,e,r){"use strict";function i(t,e,r,i){for(var n=void 0,o=void 0,s=void 0,l=void 0,u=void 0,d=window.VTTCue||window.TextTrackCue,c=0;c<i.rows.length;c++)if(n=i.rows[c],s=!0,l=0,u="",!n.isEmpty()){for(var h=0;h<n.chars.length;h++)n.chars[h].uchar.match(/\s/)&&s?l++:(u+=n.chars[h].uchar,s=!1);n.cueStartTime=e,e===r&&(r+=1e-4),o=new d(e,r,Object(a.b)(u.trim())),l>=16?l--:l++,navigator.userAgent.match(/Firefox\//)?o.line=c+1:o.line=c>7?c-2:c+1,o.align="left",o.position=Math.max(0,Math.min(100,l/32*100+(navigator.userAgent.match(/Firefox\//)?50:0))),t.addCue(o)}}Object.defineProperty(e,"__esModule",{value:!0}),e.newCue=i;var a=r(27)},function(t,e,r){"use strict";e.a=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="",c=!1,h=i,f=n,p=o,v=null,g="",y=!0,m="auto",b="start",E=50,T="middle",S=50,R="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 c},set:function(t){c=!!t}})),Object.defineProperty(s,"startTime",r({},u,{get:function(){return h},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");h=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 v},set:function(t){v=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"vertical",r({},u,{get:function(){return g},set:function(e){var r=t(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");g=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 S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"align",r({},u,{get:function(){return R},set:function(t){var r=e(t);if(!r)throw new SyntaxError("An invalid or illegal string was specified.");R=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}()},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)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 o(t,e){return t&&t.label===e.name&&!(t.textTrack1||t.textTrack2)}function s(t,e,r,i){return Math.min(e,i)-Math.max(t,r)}var l=r(1),u=r(3),d=r(65),c=r(66),h=r(67),f=r(0),p=r(26),v=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,l.a.MEDIA_ATTACHING,l.a.MEDIA_DETACHING,l.a.FRAG_PARSING_USERDATA,l.a.FRAG_DECRYPTED,l.a.MANIFEST_LOADING,l.a.MANIFEST_LOADED,l.a.FRAG_LOADED,l.a.LEVEL_SWITCHING,l.a.INIT_PTS_FOUND));if(n.hls=r,n.config=r.config,n.enabled=!0,n.Cues=r.config.cueHandler,n.textTracks=[],n.tracks=[],n.unparsedVttFrags=[],n.initPTS=void 0,n.cueRanges=[],n.captionsTracks={},n.captionsProperties={textTrack1:{label:n.config.captionsTextTrack1Label,languageCode:n.config.captionsTextTrack1LanguageCode},textTrack2:{label:n.config.captionsTextTrack2Label,languageCode:n.config.captionsTextTrack2LanguageCode}},n.config.enableCEA708Captions){var o=new c.a(n,"textTrack1"),s=new c.a(n,"textTrack2");n.cea608Parser=new d.a(0,o,s)}return n}return n(e,t),e.prototype.addCues=function(t,e,r,i){for(var a=this.cueRanges,n=!1,o=a.length;o--;){var l=a[o],u=s(l[0],l[1],e,r);if(u>=0&&(l[0]=Math.min(l[0],e),l[1]=Math.max(l[1],r),n=!0,u/(r-e)>.5))return}n||a.push([e,r]),this.Cues.newCue(this.captionsTracks[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];if(i[t])return i}return null},e.prototype.createCaptionsTrack=function(t){var e=this.captionsProperties[t],r=e.label,i=e.languageCode,a=this.captionsTracks;if(!a[t]){var n=this.getExistingTrack(t);if(n)a[t]=n,Object(p.a)(a[t]),Object(p.b)(a[t],this.media);else{var o=this.createTextTrack("captions",r,i);o&&(o[t]=!0,a[t]=o)}}},e.prototype.createTextTrack=function(t,e,r){var i=this.media;if(i)return i.addTextTrack(t,e,r)},e.prototype.destroy=function(){u.a.prototype.destroy.call(this)},e.prototype.onMediaAttaching=function(t){this.media=t.media,this._cleanTracks()},e.prototype.onMediaDetaching=function(){var t=this.captionsTracks;Object.keys(t).forEach(function(e){Object(p.a)(t[e]),delete t[e]})},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++)Object(p.a)(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];o(n,t)&&(a=n)}a||(a=e.createTextTrack("subtitles",t.name,t.lang)),t.default?a.mode=e.hls.subtitleDisplay?"showing":"hidden":a.mode="disabled",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(l.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;h.a.parse(e,this.initPTS,r,t.cc,function(e){var r=i[t.trackId];if("disabled"===r.mode)return void a.trigger(l.a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t});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(l.a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},function(e){f.b.log("Failed to parse VTT cue: "+e),a.trigger(l.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=31&t[0],r=2,i=void 0,a=void 0,n=void 0,o=void 0,s=void 0,l=[],u=0;u<e;u++)i=t[r++],a=127&t[r++],n=127&t[r++],o=0!=(4&i),s=3&i,0===a&&0===n||o&&0===s&&(l.push(a),l.push(n));return l},e}(u.a);e.a=v},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a={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},n=function(t){var e=t;return a.hasOwnProperty(t)&&(e=a[t]),String.fromCharCode(e)},o=15,s=100,l={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},u={17:2,18:4,21:6,22:8,23:10,19:13,20:15},d={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},c={25:2,26:4,29:6,30:8,31:10,27:13,28:15},h=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],f={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){this.verboseFilter[t];this.verboseLevel}},p=function(t){for(var e=[],r=0;r<t.length;r++)e.push(t[r].toString(16));return e},v=function(){function t(e,r,a,n,o){i(this,t),this.foreground=e||"white",this.underline=r||!1,this.italics=a||!1,this.background=n||"black",this.flash=o||!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}(),g=function(){function t(e,r,a,n,o,s){i(this,t),this.uchar=e||" ",this.penState=new v(r,a,n,o,s)}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}(),y=function(){function t(){i(this,t),this.chars=[];for(var e=0;e<s;e++)this.chars.push(new g);this.pos=0,this.currPenState=new v}return t.prototype.equals=function(t){for(var e=!0,r=0;r<s;r++)if(!this.chars[r].equals(t.chars[r])){e=!1;break}return e},t.prototype.copy=function(t){for(var e=0;e<s;e++)this.chars[e].copy(t.chars[e])},t.prototype.isEmpty=function(){for(var t=!0,e=0;e<s;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?(f.log("ERROR","Negative cursor position "+this.pos),this.pos=0):this.pos>s&&(f.log("ERROR","Too large cursor position "+this.pos),this.pos=s)},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=n(t);if(this.pos>=s)return void f.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=void 0;for(e=t;e<s;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<s;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}(),m=function(){function t(){i(this,t),this.rows=[];for(var e=0;e<o;e++)this.rows.push(new y);this.currRow=o-1,this.nrRollUpRows=null,this.reset()}return t.prototype.reset=function(){for(var t=0;t<o;t++)this.rows[t].clear();this.currRow=o-1},t.prototype.equals=function(t){for(var e=!0,r=0;r<o;r++)if(!this.rows[r].equals(t.rows[r])){e=!1;break}return e},t.prototype.copy=function(t){for(var e=0;e<o;e++)this.rows[e].copy(t.rows[e])},t.prototype.isEmpty=function(){for(var t=!0,e=0;e<o;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){f.log("INFO","setCursor: "+t),this.rows[this.currRow].setCursor(t)},t.prototype.setPAC=function(t){f.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<o;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<f.time)for(var s=0;s<this.nrRollUpRows;s++)this.rows[e-this.nrRollUpRows+s+1].copy(a.rows[i+s])}}this.currRow=e;var l=this.rows[this.currRow];if(null!==t.indent){var u=t.indent,d=Math.max(u-1,0);l.setCursor(t.indent),t.color=l.chars[d].penState.foreground}var c={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(c)},t.prototype.setBkgData=function(t){f.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 f.log("DEBUG","roll_up but nrRollUpRows not set yet");f.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),f.log("INFO","Rolling up")},t.prototype.getDisplayText=function(t){t=t||!1;for(var e=[],r="",i=-1,a=0;a<o;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}(),b=function(){function t(e,r){i(this,t),this.chNr=e,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new m,this.nonDisplayedMemory=new m,this.lastOutputScreen=new m,this.currRollUpRow=this.displayedMemory.rows[o-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[o-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,f.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";f.log("INFO",r+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(f.log("TEXT","DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())},t.prototype.ccRCL=function(){f.log("INFO","RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},t.prototype.ccBS=function(){f.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(){f.log("INFO","DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},t.prototype.ccRU=function(t){f.log("INFO","RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)},t.prototype.ccFON=function(){f.log("INFO","FON - Flash On"),this.writeScreen.setPen({flash:!0})},t.prototype.ccRDC=function(){f.log("INFO","RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},t.prototype.ccTR=function(){f.log("INFO","TR"),this.setMode("MODE_TEXT")},t.prototype.ccRTD=function(){f.log("INFO","RTD"),this.setMode("MODE_TEXT")},t.prototype.ccEDM=function(){f.log("INFO","EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},t.prototype.ccCR=function(){f.log("CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},t.prototype.ccENM=function(){f.log("INFO","ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},t.prototype.ccEOC=function(){if(f.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,f.log("TEXT","DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)},t.prototype.ccTO=function(t){f.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]}f.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=f.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}(),E=function(){function t(e,r,a){i(this,t),this.field=e||1,this.outputs=[r,a],this.channels=[new b(1,r),new b(2,a)],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=void 0,i=void 0,a=void 0,n=!1;this.lastTime=t,f.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(f.log("DATA","["+p([e[o],e[o+1]])+"] -> ("+p([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 f.log("WARNING","No channel found yet. TEXT-MODE?");r?this.dataCounters.cmd+=2:n?this.dataCounters.char+=2:(this.dataCounters.other+=2,f.log("WARNING","Couldn't parse cleaned data "+p([i,a])+" orig: "+p([e[o],e[o+1]])))}else this.dataCounters.padding+=2},t.prototype.parseCmd=function(t,e){var r=null,i=(20===t||28===t)&&e>=32&&e<=47,a=(23===t||31===t)&&e>=33&&e<=35;if(!i&&!a)return!1;if(t===this.lastCmdA&&e===this.lastCmdB)return this.lastCmdA=null,this.lastCmdB=null,f.log("DEBUG","Repeated command ("+p([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)&&e>=32&&e<=47){if((r=17===t?1:2)!==this.currChNr)return f.log("ERROR","Mismatch channel in midrow parsing"),!1;return this.channels[r-1].ccMIDROW(e),f.log("DEBUG","MIDROW ("+p([t,e])+")"),!0}return!1},t.prototype.parsePAC=function(t,e){var r=null,i=null,a=(t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127,n=(16===t||24===t)&&e>=64&&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=e>=64&&e<=95?1===r?l[t]:d[t]:1===r?u[t]:c[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),a>=17&&a<=19){var o=e;o=17===a?e+80:18===a?e+112:e+144,f.log("INFO","Special char '"+n(o)+"' in channel "+r),i=[o]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);if(i){var s=p(i);f.log("DEBUG","Char codes = "+s.join(",")),this.lastCmdA=null,this.lastCmdB=null}return i},t.prototype.parseBackgroundAttributes=function(t,e){var r=void 0,i=void 0,a=void 0,n=void 0,o=(16===t||24===t)&&e>=32&&e<=47,s=(23===t||31===t)&&e>=45&&e<=47;return!(!o&&!s)&&(r={},16===t||24===t?(i=Math.floor((e-32)/2),r.background=h[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}();e.a=E},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var a=function(){function t(e,r){i(this,t),this.timelineController=e,this.trackName=r,this.startTime=null,this.endTime=null,this.screen=null}return t.prototype.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,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.trackName)},t}();e.a=a},function(t,e,r){"use strict";var i=r(27),a=r(7),n=function(t,e,r){return t.substr(r||0,e.length)===e},o=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)},s=function(t){for(var e=5381,r=t.length;r;)e=33*e^t.charCodeAt(--r);return(e>>>0).toString()},l=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},u={parse:function(t,e,r,u,d,c){var h=/\r\n|\n\r|\n|\r/g,f=Object(a.b)(new Uint8Array(t)).trim().replace(h,"\n").split("\n"),p="00:00.000",v=0,g=0,y=0,m=[],b=void 0,E=!0,T=new i.a;T.oncue=function(t){var e=r[u],i=r.ccOffset;e&&e.new&&(void 0!==g?i=r.ccOffset=e.start:l(r,u,y)),y&&(i=y+r.ccOffset-r.presentationOffset),t.startTime+=i-g,t.endTime+=i-g,t.id=s(t.startTime.toString())+s(t.endTime.toString())+s(t.text),t.text=decodeURIComponent(encodeURIComponent(t.text)),t.endTime>0&&m.push(t)},T.onparsingerror=function(t){b=t},T.onflush=function(){if(b&&c)return void c(b);d(m)},f.forEach(function(t){if(E){if(n(t,"X-TIMESTAMP-MAP=")){E=!1,t.substr(16).split(",").forEach(function(t){n(t,"LOCAL:")?p=t.substr(6):n(t,"MPEGTS:")&&(v=parseInt(t.substr(7)))});try{e=e<0?e+8589934592:e,v-=e,g=o(p)/1e3,y=v/9e4,-1===g&&(b=new Error("Malformed X-TIMESTAMP-MAP: "+t))}catch(e){b=new Error("Malformed X-TIMESTAMP-MAP: "+t)}return}""===t&&(E=!1)}T.parse(t+"\n")}),T.flush()}};e.a=u},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)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 o(t){for(var e=[],r=0;r<t.length;r++)"subtitles"===t[r].kind&&e.push(t[r]);return e}var s=r(1),l=r(3),u=r(0),d=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}}(),c=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,s.a.MEDIA_ATTACHED,s.a.MEDIA_DETACHING,s.a.MANIFEST_LOADING,s.a.MANIFEST_LOADED,s.a.SUBTITLE_TRACK_LOADED));return n.tracks=[],n.trackId=-1,n.media=null,n.subtitleDisplay=!0,n}return n(e,t),e.prototype._onTextTracksChanged=function(){if(this.media){for(var t=-1,e=o(this.media.textTracks),r=0;r<e.length;r++)if("hidden"===e[r].mode)t=r;else if("showing"===e[r].mode){t=r;break}this.subtitleTrack=t}},e.prototype.destroy=function(){l.a.prototype.destroy.call(this)},e.prototype.onMediaAttached=function(t){var e=this;this.media=t.media,this.media&&(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=null)},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(s.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;r&&!r.live||(u.b.log("(re)loading playlist for subtitle track "+t),this.hls.trigger(s.a.SUBTITLE_TRACK_LOADING,{url:e.url,id:t}))}},e.prototype.onSubtitleTrackLoaded=function(t){var e=this;t.id<this.tracks.length&&(u.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&&this._stopTimer())},e.prototype.setSubtitleTrackInternal=function(t){var e=this.hls,r=this.tracks;if(!("number"!=typeof t||t<-1||t>=r.length)&&(this._stopTimer(),this.trackId=t,u.b.log("switching to subtitle track "+t),e.trigger(s.a.SUBTITLE_TRACK_SWITCH,{id:t}),-1!==t)){var i=r[t],a=i.details;a&&!a.live||(u.b.log("(re)loading playlist for subtitle track "+t),e.trigger(s.a.SUBTITLE_TRACK_LOADING,{url:i.url,id:t}))}},e.prototype._stopTimer=function(){this.timer&&(clearInterval(this.timer),this.timer=null)},e.prototype._toggleTrackModes=function(t){var e=this.media,r=this.subtitleDisplay,i=this.trackId;if(e){var a=o(e.textTracks);if(-1===t)[].slice.call(a).forEach(function(t){t.mode="disabled"});else{var n=a[i];n&&(n.mode="disabled")}var s=a[t];s&&(s.mode=r?"showing":"hidden")}},d(e,[{key:"subtitleTracks",get:function(){return this.tracks}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(t){this.trackId!==t&&(this._toggleTrackModes(t),this.setSubtitleTrackInternal(t))}}]),e}(l.a);e.a=c},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)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)}var o=r(1),s=r(0),l=r(13),u=r(8),d=window,c=d.performance,h={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING"},f=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,o.a.MEDIA_ATTACHED,o.a.ERROR,o.a.KEY_LOADED,o.a.FRAG_LOADED,o.a.SUBTITLE_TRACKS_UPDATED,o.a.SUBTITLE_TRACK_SWITCH,o.a.SUBTITLE_TRACK_LOADED,o.a.SUBTITLE_FRAG_PROCESSED));return n.config=r.config,n.vttFragSNsProcessed={},n.vttFragQueues=void 0,n.currentlyProcessing=null,n.state=h.STOPPED,n.currentTrackId=-1,n.decrypter=new l.a(r.observer,r.config),n}return n(e,t),e.prototype.onHandlerDestroyed=function(){this.state=h.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(o.a.FRAG_LOADING,{frag:t}),this.state=h.FRAG_LOADING}},e.prototype.onSubtitleFragProcessed=function(t){t.success&&this.vttFragSNsProcessed[t.frag.trackId].push(t.frag.sn),this.currentlyProcessing=null,this.state=h.IDLE,this.nextFrag()},e.prototype.onMediaAttached=function(){this.state=h.IDLE},e.prototype.onError=function(t){var e=t.frag;e&&"subtitle"!==e.type||this.currentlyProcessing&&(this.currentlyProcessing=null,this.nextFrag())},e.prototype.doTick=function(){var t=this;switch(this.state){case h.IDLE:var e=this.tracks,r=this.currentTrackId,i=this.vttFragSNsProcessed[r],a=this.vttFragQueues[r],n=this.currentlyProcessing?this.currentlyProcessing.sn:-1,l=function(t){return i.indexOf(t.sn)>-1},u=function(t){return a.some(function(e){return e.sn===t.sn})};if(!e)break;var d;if(r<e.length&&(d=e[r].details),void 0===d)break;d.fragments.forEach(function(e){l(e)||e.sn===n||u(e)||(e.encrypted?(s.b.log("Loading key for "+e.sn),t.state=h.KEY_LOADING,t.hls.trigger(o.a.KEY_LOADING,{frag:e})):(e.trackId=r,a.push(e),t.nextFrag()))})}},e.prototype.onSubtitleTracksUpdated=function(t){var e=this;s.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){if(this.currentTrackId=t.id,this.tracks&&-1!==this.currentTrackId){var e=this.tracks[this.currentTrackId];e&&e.details&&this.tick()}},e.prototype.onSubtitleTrackLoaded=function(){this.tick()},e.prototype.onKeyLoaded=function(){this.state===h.KEY_LOADING&&(this.state=h.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===h.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=void 0;try{n=c.now()}catch(t){n=Date.now()}this.decrypter.decrypt(t.payload,r.key.buffer,r.iv.buffer,function(t){var e=void 0;try{e=c.now()}catch(t){e=Date.now()}a.trigger(o.a.FRAG_DECRYPTED,{frag:i,payload:t,stats:{tstart:n,tdecrypt:e}})})}},e}(u.a);e.a=f},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)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)}var o=r(3),s=r(1),l=r(2),u=r(0),d=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}}(),c=window,h=c.XMLHttpRequest,f={WIDEVINE:"com.widevine.alpha",PLAYREADY:"com.microsoft.playready"},p=function(t,e,r){var i={videoCapabilities:[]};return e.forEach(function(t){i.videoCapabilities.push({contentType:'video/mp4; codecs="'+t+'"'})}),[i]},v=function(t,e,r){switch(t){case f.WIDEVINE:return p(0,r);default:throw Error("Unknown key-system: "+t)}},g=function(t){function e(r){i(this,e);var n=a(this,t.call(this,r,s.a.MEDIA_ATTACHED,s.a.MANIFEST_PARSED));return n._widevineLicenseUrl=r.config.widevineLicenseUrl,n._licenseXhrSetup=r.config.licenseXhrSetup,n._emeEnabled=r.config.emeEnabled,n._requestMediaKeySystemAccess=r.config.requestMediaKeySystemAccessFunc,n._mediaKeysList=[],n._media=null,n._hasSetMediaKeys=!1,n._isMediaEncrypted=!1,n._requestLicenseFailureCount=0,n}return n(e,t),e.prototype.getLicenseServerUrl=function(t){var e=void 0;switch(t){case f.WIDEVINE:e=this._widevineLicenseUrl;break;default:e=null}return e||(u.b.error('No license server URL configured for key-system "'+t+'"'),this.hls.trigger(s.a.ERROR,{type:l.b.KEY_SYSTEM_ERROR,details:l.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})),e},e.prototype._attemptKeySystemAccess=function(t,e,r){var i=this,a=v(t,0,r);if(!a)return void u.b.warn("Can not create config for key-system (maybe because platform is not supported):",t);u.b.log("Requesting encrypted media key-system access"),this.requestMediaKeySystemAccess(t,a).then(function(e){i._onMediaKeySystemAccessObtained(t,e)}).catch(function(e){u.b.error('Failed to obtain key-system "'+t+'" access:',e)})},e.prototype._onMediaKeySystemAccessObtained=function(t,e){var r=this;u.b.log('Access for key-system "'+t+'" obtained');var i={mediaKeys:null,mediaKeysSession:null,mediaKeysSessionInitialized:!1,mediaKeySystemAccess:e,mediaKeySystemDomain:t};this._mediaKeysList.push(i),e.createMediaKeys().then(function(e){i.mediaKeys=e,u.b.log('Media-keys created for key-system "'+t+'"'),r._onMediaKeysCreated()}).catch(function(t){u.b.error("Failed to create media-keys:",t)})},e.prototype._onMediaKeysCreated=function(){var t=this;this._mediaKeysList.forEach(function(e){e.mediaKeysSession||(e.mediaKeysSession=e.mediaKeys.createSession(),t._onNewMediaKeySession(e.mediaKeysSession))})},e.prototype._onNewMediaKeySession=function(t){var e=this;u.b.log("New key-system session "+t.sessionId),t.addEventListener("message",function(r){e._onKeySessionMessage(t,r.message)},!1)},e.prototype._onKeySessionMessage=function(t,e){u.b.log("Got EME message event, creating license request"),this._requestLicense(e,function(e){u.b.log("Received license data, updating key-session"),t.update(e)})},e.prototype._onMediaEncrypted=function(t,e){u.b.log('Media is encrypted using "'+t+'" init data type'),this._isMediaEncrypted=!0,this._mediaEncryptionInitDataType=t,this._mediaEncryptionInitData=e,this._attemptSetMediaKeys(),this._generateRequestWithPreferredKeySession()},e.prototype._attemptSetMediaKeys=function(){if(!this._hasSetMediaKeys){var t=this._mediaKeysList[0];if(!t||!t.mediaKeys)return u.b.error("Fatal: Media is encrypted but no CDM access or no keys have been obtained yet"),void this.hls.trigger(s.a.ERROR,{type:l.b.KEY_SYSTEM_ERROR,details:l.a.KEY_SYSTEM_NO_KEYS,fatal:!0});u.b.log("Setting keys for encrypted media"),this._media.setMediaKeys(t.mediaKeys),this._hasSetMediaKeys=!0}},e.prototype._generateRequestWithPreferredKeySession=function(){var t=this,e=this._mediaKeysList[0];if(!e)return u.b.error("Fatal: Media is encrypted but not any key-system access has been obtained yet"),void this.hls.trigger(s.a.ERROR,{type:l.b.KEY_SYSTEM_ERROR,details:l.a.KEY_SYSTEM_NO_ACCESS,fatal:!0});if(e.mediaKeysSessionInitialized)return void u.b.warn("Key-Session already initialized but requested again");var r=e.mediaKeysSession;r||(u.b.error("Fatal: Media is encrypted but no key-session existing"),this.hls.trigger(s.a.ERROR,{type:l.b.KEY_SYSTEM_ERROR,details:l.a.KEY_SYSTEM_NO_SESSION,fatal:!0}));var i=this._mediaEncryptionInitDataType,a=this._mediaEncryptionInitData;u.b.log('Generating key-session request for "'+i+'" init data type'),e.mediaKeysSessionInitialized=!0,r.generateRequest(i,a).then(function(){u.b.debug("Key-session generation succeeded")}).catch(function(e){u.b.error("Error generating key-session request:",e),t.hls.trigger(s.a.ERROR,{type:l.b.KEY_SYSTEM_ERROR,details:l.a.KEY_SYSTEM_NO_SESSION,fatal:!1})})},e.prototype._createLicenseXhr=function(t,e,r){var i=new h,a=this._licenseXhrSetup;try{if(a)try{a(i,t)}catch(e){i.open("POST",t,!0),a(i,t)}i.readyState||i.open("POST",t,!0)}catch(t){return u.b.error("Error setting up key-system license XHR",t),void this.hls.trigger(s.a.ERROR,{type:l.b.KEY_SYSTEM_ERROR,details:l.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}return i.responseType="arraybuffer",i.onreadystatechange=this._onLicenseRequestReadyStageChange.bind(this,i,t,e,r),i},e.prototype._onLicenseRequestReadyStageChange=function(t,e,r,i){switch(t.readyState){case 4:if(200===t.status)this._requestLicenseFailureCount=0,u.b.log("License request succeeded"),i(t.response);else{if(u.b.error("License Request XHR failed ("+e+"). Status: "+t.status+" ("+t.statusText+")"),++this._requestLicenseFailureCount<=3){var a=3-this._requestLicenseFailureCount+1;return u.b.warn("Retrying license request, "+a+" attempts left"),void this._requestLicense(r,i)}this.hls.trigger(s.a.ERROR,{type:l.b.KEY_SYSTEM_ERROR,details:l.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}}},e.prototype._generateLicenseRequestChallenge=function(t,e){var r=void 0;return t.mediaKeySystemDomain===f.PLAYREADY?u.b.error("PlayReady is not supported (yet)"):t.mediaKeySystemDomain===f.WIDEVINE?r=e:u.b.error("Unsupported key-system:",t.mediaKeySystemDomain),r},e.prototype._requestLicense=function(t,e){u.b.log("Requesting content license for key-system");var r=this._mediaKeysList[0];if(!r)return u.b.error("Fatal error: Media is encrypted but no key-system access has been obtained yet"),void this.hls.trigger(s.a.ERROR,{type:l.b.KEY_SYSTEM_ERROR,details:l.a.KEY_SYSTEM_NO_ACCESS,fatal:!0});var i=this.getLicenseServerUrl(r.mediaKeySystemDomain),a=this._createLicenseXhr(i,t,e);u.b.log("Sending license request to URL: "+i),a.send(this._generateLicenseRequestChallenge(r,t))},e.prototype.onMediaAttached=function(t){var e=this;if(this._emeEnabled){var r=t.media;this._media=r,r.addEventListener("encrypted",function(t){e._onMediaEncrypted(t.initDataType,t.initData)})}},e.prototype.onManifestParsed=function(t){if(this._emeEnabled){var e=t.levels.map(function(t){return t.audioCodec}),r=t.levels.map(function(t){return t.videoCodec});this._attemptKeySystemAccess(f.WIDEVINE,e,r)}},d(e,[{key:"requestMediaKeySystemAccess",get:function(){if(!this._requestMediaKeySystemAccess)throw new Error("No requestMediaKeySystemAccess function configured");return this._requestMediaKeySystemAccess}}]),e}(o.a);e.a=g},function(t,e,r){"use strict";r.d(e,"a",function(){return i});var i=function(){return"undefined"!=typeof window&&window.navigator&&window.navigator.requestMediaKeySystemAccess?window.navigator.requestMediaKeySystemAccess.bind(window.navigator):null}()},function(t,e){/*! http://mths.be/endswith v0.2.0 by @mathias */ +String.prototype.endsWith||function(){"use strict";var t=function(){try{var t={},e=Object.defineProperty,r=e(t,t,t)&&e}catch(t){}return r}(),e={}.toString,r=function(t){if(null==this)throw TypeError();var r=String(this);if(t&&"[object RegExp]"==e.call(t))throw TypeError();var i=r.length,a=String(t),n=a.length,o=i;if(arguments.length>1){var s=arguments[1];void 0!==s&&(o=s?Number(s):0)!=o&&(o=0)}var l=Math.min(Math.max(o,0),i),u=l-n;if(u<0)return!1;for(var d=-1;++d<n;)if(r.charCodeAt(u+d)!=a.charCodeAt(d))return!1;return!0};t?t(String.prototype,"endsWith",{value:r,configurable:!0,writable:!0}):String.prototype.endsWith=r}()}]).default}); +//# sourceMappingURL=hls.min.js.map \ No newline at end of file diff --git a/grails-app/assets/bower/hls.js/dist/hls.min.js.map b/grails-app/assets/bower/hls.js/dist/hls.min.js.map new file mode 100644 index 000000000..34eae5d2b --- /dev/null +++ b/grails-app/assets/bower/hls.js/dist/hls.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///hls.min.js","webpack:///webpack/bootstrap 8b3896ec37aa881fcca0","webpack:///./src/utils/logger.js","webpack:///./src/events.js","webpack:///./src/errors.js","webpack:///./src/event-handler.js","webpack:///./src/utils/get-self-scope.js","webpack:///./node_modules/url-toolkit/src/url-toolkit.js","webpack:///./src/utils/binary-search.js","webpack:///./src/demux/id3.js","webpack:///./src/task-loop.js","webpack:///./src/loader/fragment.js","webpack:///./src/controller/fragment-tracker.js","webpack:///./src/utils/buffer-helper.js","webpack:///./node_modules/events/events.js","webpack:///./src/crypt/decrypter.js","webpack:///./src/utils/mediasource-helper.js","webpack:///./src/controller/level-helper.js","webpack:///./src/loader/playlist-loader.js","webpack:///./src/demux/mp4demuxer.js","webpack:///./src/loader/level-key.js","webpack:///./src/utils/codecs.js","webpack:///./src/demux/demuxer.js","webpack:///./src/demux/demuxer-inline.js","webpack:///./src/demux/adts.js","webpack:///./src/demux/mpegaudio.js","webpack:///./src/utils/time-ranges.js","webpack:///./src/utils/discontinuities.js","webpack:///./src/utils/texttrack-utils.js","webpack:///./src/utils/vttparser.js","webpack:///./src/hls.js","webpack:///./src/loader/m3u8-parser.js","webpack:///./src/utils/attr-list.js","webpack:///./src/loader/fragment-loader.js","webpack:///./src/loader/key-loader.js","webpack:///./src/controller/stream-controller.js","webpack:///./node_modules/webworkify-webpack/index.js","webpack:///./src/crypt/aes-crypto.js","webpack:///./src/crypt/fast-aes-key.js","webpack:///./src/crypt/aes-decryptor.js","webpack:///./src/demux/aacdemuxer.js","webpack:///./src/demux/tsdemuxer.js","webpack:///./src/demux/exp-golomb.js","webpack:///./src/demux/sample-aes.js","webpack:///./src/demux/mp3demuxer.js","webpack:///./src/remux/mp4-remuxer.js","webpack:///./src/remux/aac-helper.js","webpack:///./src/remux/mp4-generator.js","webpack:///./src/remux/passthrough-remuxer.js","webpack:///./src/demux/demuxer-worker.js","webpack:///./src/controller/fragment-finders.js","webpack:///./src/controller/level-controller.js","webpack:///./src/controller/id3-track-controller.js","webpack:///./src/is-supported.js","webpack:///./src/config.js","webpack:///./src/controller/abr-controller.js","webpack:///./src/utils/ewma-bandwidth-estimator.js","webpack:///./src/utils/ewma.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/cues.js","webpack:///./src/utils/vttcue.js","webpack:///./src/controller/timeline-controller.js","webpack:///./src/utils/cea-608-parser.js","webpack:///./src/utils/output-filter.js","webpack:///./src/utils/webvtt-parser.js","webpack:///./src/controller/subtitle-track-controller.js","webpack:///./src/controller/subtitle-stream-controller.js","webpack:///./src/controller/eme-controller.js","webpack:///./src/utils/mediakeys-helper.js","webpack:///./node_modules/string.prototype.endswith/endswith.js"],"names":["root","factory","exports","module","define","amd","this","modules","__webpack_require__","moduleId","installedModules","i","l","call","m","c","d","name","getter","o","Object","defineProperty","configurable","enumerable","get","n","__esModule","object","property","prototype","hasOwnProperty","p","s","__webpack_exports__","noop","formatMsg","type","msg","consolePrintFn","func","global","console","_len","arguments","length","args","Array","_key","apply","exportLoggerFunctions","debugConfig","_len2","functions","_key2","forEach","exportedLogger","bind","enableLogs","logger","__WEBPACK_IMPORTED_MODULE_0__get_self_scope__","_typeof","Symbol","iterator","obj","constructor","fakeLogger","trace","debug","log","warn","info","error","e","HlsEvents","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_SWITCHING","LEVEL_SWITCHED","LEVEL_LOADING","LEVEL_LOADED","LEVEL_UPDATED","LEVEL_PTS_UPDATED","AUDIO_TRACKS_UPDATED","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","ErrorDetails","NETWORK_ERROR","MEDIA_ERROR","KEY_SYSTEM_ERROR","MUX_ERROR","OTHER_ERROR","KEY_SYSTEM_NO_KEYS","KEY_SYSTEM_NO_ACCESS","KEY_SYSTEM_NO_SESSION","KEY_SYSTEM_LICENSE_REQUEST_FAILED","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_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","_classCallCheck","instance","Constructor","TypeError","__WEBPACK_IMPORTED_MODULE_0__utils_logger__","__WEBPACK_IMPORTED_MODULE_1__errors__","__WEBPACK_IMPORTED_MODULE_2__events__","FORBIDDEN_EVENT_NAMES","Set","EventHandler","hls","onEvent","events","handledEvents","useGenericHandler","registerListeners","destroy","onHandlerDestroying","unregisterListeners","onHandlerDestroyed","isEventHandler","event","has","Error","on","off","data","onEventGeneric","eventToFunction","funcName","replace","err","message","trigger","details","fatal","getSelfScope","window","self","URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","baseParts","path","normalizePath","buildURLFromParts","relativeParts","scheme","netLoc","pathParts","exec","builtParts","params","query","fragment","baseURLPath","newPath","substring","lastIndexOf","url","parts","split","reverse","join","BinarySearch","search","list","comparisonFunction","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","utf8ArrayToStr","ID3","isHeader","offset","isFooter","getID3Data","front","_readSize","subarray","size","getTimeStamp","frames","getID3Frames","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","array","exitOnNull","undefined","len","char2","char3","out","_possibleConstructorReturn","ReferenceError","_inherits","subClass","superClass","create","writable","setPrototypeOf","__proto__","__WEBPACK_IMPORTED_MODULE_0__event_handler__","TaskLoop","_EventHandler","_this","concat","_tickInterval","_tickTimer","_tickCallCount","_boundTick","tick","clearNextTick","clearInterval","hasInterval","hasNextTick","setInterval","_setInterval","_x","toString","millis","_clearInterval","clearTimeout","doTick","setTimeout","__WEBPACK_IMPORTED_MODULE_0_url_toolkit__","__WEBPACK_IMPORTED_MODULE_0_url_toolkit___default","__WEBPACK_IMPORTED_MODULE_1__level_key__","_createClass","defineProperties","target","props","descriptor","protoProps","staticProps","Fragment","_elementaryStreams","_url","_byteRange","_decryptdata","tagList","ElementaryStreamTypes","AUDIO","VIDEO","addElementaryStream","hasElementaryStream","createInitializationVector","segmentNumber","uint8View","fragmentDecryptdataFromLevelkey","levelkey","decryptdata","method","uri","iv","baseuri","reluri","relurl","a","baseurl","set","_programDateTime","rawProgramDateTime","Date","parse","rawByteRange","byteRange","lastByteRangeEndOffset","parseInt","sn","FragmentState","FragmentTracker","__WEBPACK_IMPORTED_MODULE_1__events__","NOT_LOADED","APPENDING","PARTIAL","OK","bufferPadding","fragments","timeRanges","config","getBufferedFrag","position","levelType","bufferedFrags","keys","filter","fragmentEntity","body","buffered","frag","startPTS","endPTS","bufferedFragKey","pop","detectEvictedFragments","elementaryStream","timeRange","_this2","fragmentTimes","time","esData","range","isTimeBuffered","removeFragment","detectPartialFragments","_this3","fragKey","getFragmentKey","getBufferedTimes","startTime","endTime","fragmentPartial","start","max","min","partial","level","urlId","getPartialFragment","_this4","timePadding","bestFragment","bestOverlap","isPartial","getState","state","video","audio","onFragLoaded","isNaN","bitrateTest","onBufferAppended","_this5","onFragBuffered","hasFragment","removeAllFragments","BufferHelper","isBuffered","media","bufferInfo","pos","maxHoleDuration","vbuffered","bufferedInfo","nextStart","buffered2","bufferLen","bufferStart","bufferEnd","bufferStartNext","sort","b","diff","buf2len","buf2end","EventEmitter","_events","_maxListeners","isFunction","arg","isNumber","isObject","isUndefined","defaultMaxListeners","setMaxListeners","emit","er","handler","listeners","context","slice","addListener","listener","newListener","warned","once","g","removeListener","fired","splice","removeAllListeners","listenerCount","evlistener","emitter","__WEBPACK_IMPORTED_MODULE_0__aes_crypto__","__WEBPACK_IMPORTED_MODULE_1__fast_aes_key__","__WEBPACK_IMPORTED_MODULE_2__aes_decryptor__","__WEBPACK_IMPORTED_MODULE_3__errors__","__WEBPACK_IMPORTED_MODULE_4__utils_logger__","__WEBPACK_IMPORTED_MODULE_5__events__","__WEBPACK_IMPORTED_MODULE_6__utils_get_self_scope__","Decrypter","observer","_ref","_ref$removePKCS7Paddi","removePKCS7Padding","logEnabled","browserCrypto","crypto","subtle","webkitSubtle","disableWebCrypto","isSync","enableSoftwareAES","decrypt","callback","decryptor","expandKey","fastAesKey","then","aesKey","catch","onWebCryptoError","result","reason","getMediaSource","MediaSource","WebKitMediaSource","addGroupId","id","audioGroupIds","textGroupIds","updatePTS","fromIdx","toIdx","fragFrom","fragTo","fragToPTS","duration","updateFragPTSDTS","startDTS","endDTS","maxStartPTS","deltaPTS","abs","drift","startSN","endSN","fragIdx","PTSKnown","mergeDetails","oldDetails","newDetails","delta","oldfragments","newfragments","ccOffset","PTSFrag","initSegment","oldFrag","newFrag","cc","backtracked","dropped","sliding","__WEBPACK_IMPORTED_MODULE_0__events__","__WEBPACK_IMPORTED_MODULE_1__event_handler__","__WEBPACK_IMPORTED_MODULE_2__errors__","__WEBPACK_IMPORTED_MODULE_3__utils_logger__","__WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__","__WEBPACK_IMPORTED_MODULE_5__m3u8_parser__","_window","performance","ContextType","MANIFEST","LEVEL","AUDIO_TRACK","SUBTITLE_TRACK","LevelType","MAIN","SUBTITLE","PlaylistLoader","loaders","canHaveQualityLevels","mapContextToLevelType","getResponseUrl","response","indexOf","createInternalLoader","PLoader","pLoader","Loader","loader","InternalLoader","getInternalLoader","resetInternalLoader","contextType","destroyInternalLoaders","onManifestLoading","load","onLevelLoading","onAudioTrackLoading","onSubtitleTrackLoading","loaderContext","abort","maxRetry","timeout","retryDelay","maxRetryDelay","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","responseType","loaderConfig","loaderCallbacks","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","stats","networkDetails","isSidxRequest","_handleSidxRequest","_handlePlaylistLoaded","string","tload","now","_handleManifestParsingError","_handleTrackOrLevelPlaylist","_handleMasterPlaylist","_handleNetworkError","levels","parseMasterPlaylist","audioGroups","map","attrs","codec","audioCodec","audioTracks","parseMasterPlaylistMedia","subtitles","embeddedAudioFound","audioTrack","unshift","levelUrlId","levelId","levelDetails","parseLevelPlaylist","singleLevel","tparsed","needSidxRanges","sidxUrl","rangeStart","rangeEnd","sidxInfo","parseSegmentIndex","references","segmentRef","segRefInfo","moovEndOffset","targetduration","UINT32_MAX","pow","MP4Demuxer","remuxer","resetTimeStamp","initPTS","resetInitSegment","videoCodec","initData","parseInitSegment","tracks","audiovideo","container","probe","findBox","bin2str","readUint16","val","readUint32","writeUint32","results","subresults","endbox","moov","sidx","version","timescale","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","earliestPresentationTime","trak","tkhd","trackId","mdhd","hdlr","hdlrType","soun","vide","codecBox","codecType","getStartDTS","trafs","baseTimes","traf","tfhd","scale","tfdt","isFinite","offsetStartDTS","timeOffset","baseMediaDecodeTime","upper","floor","lower","append","contiguous","accurateTimeOffset","remux","LevelKey","_uri","isCodecType","typeCodes","sampleEntryCodesISO","isCodecSupportedInMp4","isTypeSupported","a3ds","ac-3","ac-4","alac","alaw","dra1","dts+","dts-","dtsc","dtse","dtsh","ec-3","enca","g719","g726","m4ae","mha1","mha2","mhm1","mhm2","mlpa","mp4a","raw ","Opus","samr","sawb","sawp","sevc","sqcp","ssmv","twos","ulaw","avc1","avc2","avc3","avc4","avcp","drac","dvav","dvhe","encv","hev1","hvc1","mjp2","mp4v","mvc1","mvc2","mvc3","mvc4","resv","rv60","s263","svc1","svc2","vc-1","vp08","vp09","__WEBPACK_IMPORTED_MODULE_0_events__","__WEBPACK_IMPORTED_MODULE_0_events___default","__WEBPACK_IMPORTED_MODULE_1_webworkify_webpack__","__WEBPACK_IMPORTED_MODULE_1_webworkify_webpack___default","__WEBPACK_IMPORTED_MODULE_3__demux_demuxer_inline__","__WEBPACK_IMPORTED_MODULE_5__errors__","__WEBPACK_IMPORTED_MODULE_6__utils_mediasource_helper__","__WEBPACK_IMPORTED_MODULE_7__utils_get_self_scope__","Demuxer","forwardMessage","ev","typeSupported","mp4","mpeg","mp3","vendor","navigator","enableWorker","Worker","w","onwmsg","onWorkerMessage","addEventListener","onerror","filename","lineno","postMessage","cmd","JSON","stringify","URL","revokeObjectURL","objectURL","demuxer","removeEventListener","terminate","defaultInitPTS","lastFrag","discontinuity","trackSwitch","nextSN","ArrayBuffer","data1","data2","__WEBPACK_IMPORTED_MODULE_2__crypt_decrypter__","__WEBPACK_IMPORTED_MODULE_3__demux_aacdemuxer__","__WEBPACK_IMPORTED_MODULE_5__demux_tsdemuxer__","__WEBPACK_IMPORTED_MODULE_6__demux_mp3demuxer__","__WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__","__WEBPACK_IMPORTED_MODULE_8__remux_passthrough_remuxer__","__WEBPACK_IMPORTED_MODULE_9__utils_get_self_scope__","DemuxerInline","decrypter","localthis","decryptedData","tstart","tdecrypt","pushDecrypted","muxConfig","demux","mux","setDecryptData","getAudioConfig","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","toLowerCase","manifestCodec","adtsSampleingRates","test","samplerate","channelCount","isHeaderPattern","getHeaderLength","getFullFrameLength","headerLength","frameLength","newOffset","initTrackConfig","track","getFrameDuration","parseFrameHeader","pts","frameIndex","frameDuration","stamp","appendFrame","header","aacSample","unit","dts","samples","sample","MpegAudio","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","TimeRanges","r","toFixed","findFirstFragWithCC","firstFrag","currentFrag","findFragWithCC","CC","__WEBPACK_IMPORTED_MODULE_0__binary_search__","candidate","shouldAlignOnDiscontinuities","lastLevel","shouldAlign","endCC","startCC","findDiscontinuousReferenceFrag","prevDetails","curDetails","prevFrags","curFrags","__WEBPACK_IMPORTED_MODULE_1__utils_logger__","prevStartFrag","adjustPts","alignDiscontinuities","referenceFrag","lastPDT","programDateTime","newPDT","sendAddTrackEvent","videoEl","Event","document","createEvent","initEvent","dispatchEvent","clearCurrentCues","cues","removeCue","VTTParser","decoder","StringDecoder","regionList","parseTimeStamp","input","computeSeconds","h","f","match","Settings","values","parseOptions","keyValueDelim","groupDelim","groups","kv","k","v","parseCue","cue","consumeTimeStamp","ts","oInput","skipWhitespace","substr","settings","region","alt","vals","vals0","integer","percent","center","vertical","line","defaults","lineAlign","snapToLines","align","fixLineBreaks","__WEBPACK_IMPORTED_MODULE_0__vttcue__","decode","decodeURIComponent","encodeURIComponent","dflt","defaultKey","parseFloat","collectNextLine","stream","alreadyCollectedLine","hasSubstring","oncue","flush","onflush","__WEBPACK_IMPORTED_MODULE_2__loader_playlist_loader__","__WEBPACK_IMPORTED_MODULE_3__loader_fragment_loader__","__WEBPACK_IMPORTED_MODULE_4__loader_key_loader__","__WEBPACK_IMPORTED_MODULE_5__controller_fragment_tracker__","__WEBPACK_IMPORTED_MODULE_6__controller_stream_controller__","__WEBPACK_IMPORTED_MODULE_7__controller_level_controller__","__WEBPACK_IMPORTED_MODULE_8__controller_id3_track_controller__","__WEBPACK_IMPORTED_MODULE_9__is_supported__","__WEBPACK_IMPORTED_MODULE_10__utils_logger__","__WEBPACK_IMPORTED_MODULE_11__config__","__WEBPACK_IMPORTED_MODULE_12__events__","__WEBPACK_IMPORTED_MODULE_13_events__","__WEBPACK_IMPORTED_MODULE_13_events___default","Hls","defaultConfig","DefaultConfig","liveSyncDurationCount","liveMaxLatencyDurationCount","liveSyncDuration","liveMaxLatencyDuration","prop","_autoLevelCapping","abrController","bufferController","capLevelController","fpsController","playListLoader","fragmentLoader","keyLoader","id3TrackController","levelController","fragmentTracker","streamController","networkControllers","Controller","audioStreamController","coreComponents","audioTrackController","subtitleTrackController","emeController","subtitleStreamController","timelineController","isSupported","detachMedia","component","attachMedia","loadSource","location","href","startLoad","startPosition","controller","stopLoad","swapAudioCodec","recoverMediaError","currentLevel","newLevel","loadLevel","immediateLevelSwitch","nextLevel","manualLevel","nextLevelSwitch","nextLoadLevel","firstLevel","minAutoLevel","startLevel","minAutoBitrate","realBitrate","bitrate","autoLevelCapping","nextAutoLevel","maxAutoLevel","audioTrackId","liveSyncPosition","subtitleTracks","subtitleTrack","subtitleTrackId","subtitleDisplay","__WEBPACK_IMPORTED_MODULE_1__fragment__","__WEBPACK_IMPORTED_MODULE_2__level_key__","__WEBPACK_IMPORTED_MODULE_3__utils_attr_list__","__WEBPACK_IMPORTED_MODULE_5__utils_codecs__","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","LEVEL_PLAYLIST_REGEX_FAST","RegExp","source","LEVEL_PLAYLIST_REGEX_SLOW","MP4_REGEX_SUFFIX","M3U8Parser","findGroup","mediaGroupId","matchingGroup","group","convertAVC1ToAVCOTI","avcdata","shift","resolve","baseUrl","lastIndex","resolution","decimalResolution","width","height","decimalInteger","NAME","codecs","filtered","preferred","unknownCodecs","CODECS","medias","TYPE","groupId","default","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","URI","lang","LANGUAGE","groupCodec","currentSN","totalduration","live","prevFrag","title","pdt","endPdt","byteRangeEndOffset","value1","value2","toUpperCase","decryptparams","keyAttrs","decryptmethod","enumeratedString","decrypturi","decryptiv","hexadecimalInteger","startParams","startAttrs","startTimeOffset","decimalFloatingPoint","mapAttrs","BYTERANGE","averagetargetduration","every","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","parseAttrList","attr","attrName","intValue","Number","MAX_SAFE_INTEGER","Infinity","stringValue","hexadecimalIntegerAsNumber","res","FragmentLoader","loaderName","onFragLoading","FragmentILoader","fLoader","DefaultILoader","loaded","progressData","byteRangeStartOffset","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","payload","KeyLoader","decryptkey","decrypturl","onKeyLoading","fragLoadingMaxRetry","fragLoadingRetryDelay","__WEBPACK_IMPORTED_MODULE_0__utils_binary_search__","__WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__","__WEBPACK_IMPORTED_MODULE_2__demux_demuxer__","__WEBPACK_IMPORTED_MODULE_3__events__","__WEBPACK_IMPORTED_MODULE_4__fragment_tracker__","__WEBPACK_IMPORTED_MODULE_5__loader_fragment__","__WEBPACK_IMPORTED_MODULE_6__loader_playlist_loader__","__WEBPACK_IMPORTED_MODULE_7__level_helper__","__WEBPACK_IMPORTED_MODULE_8__utils_time_ranges__","__WEBPACK_IMPORTED_MODULE_9__errors__","__WEBPACK_IMPORTED_MODULE_11__utils_discontinuities__","__WEBPACK_IMPORTED_MODULE_12__task_loop__","__WEBPACK_IMPORTED_MODULE_13__fragment_finders__","State","STOPPED","IDLE","FRAG_LOADING_WAITING_RETRY","WAITING_LEVEL","PARSING","PARSED","ENDED","StreamController","_TaskLoop","audioCodecSwap","_state","stallReported","lastCurrentTime","fragLoadError","startFragRequested","loadedmetadata","nextLoadPosition","forceStartLoad","fragCurrent","fragPrevious","_doTickIdle","retryDate","seeking","_checkBuffer","_checkFragmentChanged","levelLastLoaded","startFragPrefetch","currentTime","levelInfo","levelBitrate","maxBufLen","maxBufferSize","maxBufferLength","maxMaxBufferLength","mediaBuffer","maxBufferHole","altAudio","_fetchPayloadOrEos","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","encrypted","_loadKey","_loadFragment","maxLatency","maxFragLookUpTolerance","computeLivePosition","readyState","targetSN","fragNext","foundFrag","curSNIdx","sameLevel","nextFrag","fragState","autoLevel","autoLevelEnabled","_reduceMaxBufferLength","followingBufferedFrag","fragPlayingCurrent","fragPlaying","fragPlayingLevel","immediateSwitch","previouslyPaused","paused","pause","flushMainBuffer","POSITIVE_INFINITY","immediateLevelSwitchEnd","play","fetchdelay","nextBufferedFrag","nextLevelId","fragLastKbps","startOffset","endOffset","flushScope","onMediaAttached","onvseeking","onMediaSeeking","onvseeked","onMediaSeeked","onvended","onMediaEnded","autoStartLoad","onMediaDetaching","ended","tolerance","fragStartOffset","fragEndOffset","stalled","onManifestParsed","aac","heaac","audioCodecSwitch","onLevelLoaded","newLevelId","curLevel","onKeyLoaded","fragLoaded","tbuffered","defaultAudioCodec","lastAudioCodec","pendingBuffering","appended","mediaSeeking","initSegmentData","onFragParsingInitSegment","fragNew","trackName","ua","metadata","levelCodec","parent","content","onFragParsingData","hasAudio","hasVideo","nb","onFragParsed","_checkAppendedParsed","onAudioTrackSwitching","onAudioTrackSwitched","videoBuffer","onBufferCreated","mediaTrack","alternate","pending","total","tfirst","mediaBuffered","delay","levelRetry","minLength","_seekToStartPos","expectedPlaying","tnow","nudgeRetry","stalledDuration","_reportStall","_tryFixBufferStall","onFragLoadEmergencyAborted","onBufferFlushed","targetLatency","_trySkipBufferHole","highBufferWatchdogPeriod","_tryNudgeBuffer","lastEndTime","nudgeMaxRetry","targetTime","nudgeOffset","nextState","previousState","_liveSyncPosition","webpackBootstrapFunc","oe","ENTRY_MODULE","quoteRegExp","str","getModuleDependencies","sources","queueName","retval","fnString","wrapperSignature","webpackRequireName","re","dependencyRegExp","moduleNameReqExp","hasValuesInQueues","queues","reduce","hasValues","getRequiredModules","modulesQueue","main","requiredModules","seenModules","queue","moduleToCheck","newModules","newModulesKeys","j","options","all","src","entryModule","blob","Blob","bare","webkitURL","mozURL","msURL","workerUrl","createObjectURL","worker","AESCrypto","aesIV","FastAESKey","importKey","removePadding","outputBytes","paddingBytes","DataView","getUint8","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","x","xi","sx","x2","x4","x8","t","keyBuffer","sameKey","keySize","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","__WEBPACK_IMPORTED_MODULE_0__adts__","__WEBPACK_IMPORTED_MODULE_2__demux_id3__","AACDemuxer","_audioTrack","sequenceNumber","isAAC","inputTimeScale","id3Samples","__WEBPACK_IMPORTED_MODULE_1__mpegaudio__","__WEBPACK_IMPORTED_MODULE_3__exp_golomb__","__WEBPACK_IMPORTED_MODULE_4__sample_aes__","__WEBPACK_IMPORTED_MODULE_5__utils_logger__","__WEBPACK_IMPORTED_MODULE_6__errors__","RemuxerTrackIdConfig","id3","TSDemuxer","sampleAes","discardEPB","syncOffset","_syncOffset","scanwindow","createTrack","pid","pmtParsed","_pmtId","_avcTrack","_id3Track","_txtTrack","aacOverFlow","aacLastPTS","avcSample","_duration","stt","pes","unknownPIDs","avcTrack","id3Track","avcId","audioId","id3Id","pmtId","avcData","pesData","audioData","parsePAT","_parsePAT","parsePMT","_parsePMT","parsePES","_parsePES","parseAVCPES","_parseAVCPES","parseAACPES","_parseAACPES","parseMPEGPES","_parseMPEGPES","parseID3PES","_parseID3PES","parsedPIDs","avc","decryptAndRemux","videoTrack","textTrack","decryptAacSamples","decryptAndRemuxAvc","decryptAvcSamples","_initPTS","_initDTS","mpegSupported","isSampleAes","sectionLength","tableEnd","programInfoLength","pesFlags","pesLen","pesHdrLen","pesPts","pesDts","payloadStartOffset","newData","dataLen","pushAccesUnit","units","nbSamples","forceKeyFrameOnDiscontinuity","sps","last","_parseAVCNALu","expGolombDecoder","spsfound","createAVCSample","audFound","sliceType","readSliceType","readUByte","payloadType","payloadSize","endOfCaptions","bytesAvailable","readUShort","readUInt","firstByte","secondByte","totalCCs","byteArray","_insertSampleInOrder","bytes","readSPS","pixelRatio","codecarray","codecstring","pps","arr","_getLastNalUnit","lastUnit","overflow","naluState","lastState","unitType","lastUnitStart","lastUnitType","tmp","EPBPositions","newLength","sourceIndex","newPTS","ExpGolomb","bitsAvailable","loadWord","workingBytes","availableBytes","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","skipScalingList","lastScale","nextScale","deltaScale","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","profileIdc","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","scalingListCount","chromaFormatIdc","picOrderCntType","ceil","__WEBPACK_IMPORTED_MODULE_0__crypt_decrypter__","SampleAesDecrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","sync","curUnit","encryptedBuffer","byteOffset","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","decryptAvcSample","unitIndex","curUnits","__WEBPACK_IMPORTED_MODULE_0__demux_id3__","__WEBPACK_IMPORTED_MODULE_2__mpegaudio__","MP3Demuxer","__WEBPACK_IMPORTED_MODULE_0__aac_helper__","__WEBPACK_IMPORTED_MODULE_1__mp4_generator__","MP4Remuxer","isSafari","ISGenerated","defaultTimeStamp","generateIS","nbAudioSamples","nbVideoSamples","audioTimeOffset","videoTimeOffset","audiovideoDeltaDts","remuxAudio","audioTrackLength","remuxVideo","videoData","remuxEmptyAudio","remuxID3","remuxText","audioSamples","videoSamples","computePTSDTS","initDTS","timeScale","mp4SampleDuration","mdat","moof","firstPTS","firstDTS","lastPTS","lastDTS","inputSamples","outputSamples","ptsNormalize","_PTSNormalize","nextAvcDts","deltadts","deltapts","PTSDTSshift","curr","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","setUint32","types","avcSampleUnits","mp4SampleLength","compositionTimeOffset","unitData","unitDataLen","lastFrameDuration","stretchShortVideoTrack","gapTolerance","deltaToFrameEnd","nextAudioPts","cts","flags","isLeading","isDependedOn","hasRedundancy","degradPrio","dependsOn","isNonSync","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","mp4Sample","fillFrame","maxAudioFramesDrift","nextPts","missing","newStamp","getSilentFrame","audioSample","numMissingFrames","unitLen","lastSampleDuration","silentFrame","reference","AAC","MP4","init","avcC","btrt","dinf","dref","esds","ftyp","mdia","mfhd","minf",".mp3","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsd","stsz","stts","trun","trex","vmhd","smhd","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","upperWordDuration","lowerWordDuration","boxes","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","arraylen","paddingValue","movie","PassThroughRemuxer","rawData","streamType","__WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__","__WEBPACK_IMPORTED_MODULE_2__utils_logger__","__WEBPACK_IMPORTED_MODULE_3_events__","__WEBPACK_IMPORTED_MODULE_3_events___default","DemuxerWorker","transferable","calculateNextPDT","parsedDateInt","findFragmentByPDT","PDTValue","isArray","seg","findFragmentBySN","fragmentWithinToleranceTest","candidateLookupTolerance","__WEBPACK_IMPORTED_MODULE_4__utils_codecs__","__WEBPACK_IMPORTED_MODULE_5__level_helper__","LevelController","canload","currentLevelIndex","manualLevelIndex","timer","clearTimer","_levels","levelRetryCount","loadError","onManifestLoaded","bitrateStart","levelSet","levelFromSet","videoCodecFound","audioCodecFound","chromeOrFirefox","fragmentError","SUBTITLES","_ref2","_firstLevel","setLevelInternal","levelProperties","levelError","levelIndex","recoverLevel","errorEvent","errorDetails","redundantLevels","_ref3","targetdurationMs","reloadInterval","trequest","audioGroupId","findIndex","levelObject","_startLevel","configStartLevel","__WEBPACK_IMPORTED_MODULE_3__utils_texttrack_utils__","ID3TrackController","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","mode","Cue","WebKitDataCue","VTTCue","TextTrackCue","addCue","mediaSource","__WEBPACK_IMPORTED_MODULE_0__utils_mediasource_helper__","sourceBuffer","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","appendBuffer","remove","hlsDefaultConfig","__WEBPACK_IMPORTED_MODULE_0__controller_abr_controller__","__WEBPACK_IMPORTED_MODULE_1__controller_buffer_controller__","__WEBPACK_IMPORTED_MODULE_2__controller_cap_level_controller__","__WEBPACK_IMPORTED_MODULE_3__controller_fps_controller__","__WEBPACK_IMPORTED_MODULE_4__utils_xhr_loader__","__WEBPACK_IMPORTED_MODULE_5__controller_audio_track_controller__","__WEBPACK_IMPORTED_MODULE_6__controller_audio_stream_controller__","__WEBPACK_IMPORTED_MODULE_7__utils_cues__","__WEBPACK_IMPORTED_MODULE_8__controller_timeline_controller__","__WEBPACK_IMPORTED_MODULE_9__controller_subtitle_track_controller__","__WEBPACK_IMPORTED_MODULE_10__controller_subtitle_stream_controller__","__WEBPACK_IMPORTED_MODULE_11__controller_eme_controller__","__WEBPACK_IMPORTED_MODULE_12__utils_mediakeys_helper__","capLevelOnFPSDrop","capLevelToPlayerSize","lowBufferWatchdogPeriod","liveDurationInfinity","fpsDroppedMonitoringPeriod","fpsDroppedMonitoringThreshold","appendErrorMaxRetry","xhrSetup","licenseXhrSetup","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","abrBandWidthFactor","abrBandWidthUpFactor","abrMaxWithRealBitrate","maxStarvationDelay","maxLoadingDelay","emeEnabled","widevineLicenseUrl","requestMediaKeySystemAccessFunc","cueHandler","enableCEA708Captions","enableWebVTT","captionsTextTrack1Label","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","__WEBPACK_IMPORTED_MODULE_2__utils_buffer_helper__","__WEBPACK_IMPORTED_MODULE_5__utils_ewma_bandwidth_estimator__","AbrController","lastLoadedFragLevel","_nextAutoLevel","_bwEstimator","onCheck","_abandonRulesCheck","isLive","ewmaFast","ewmaSlow","aborted","playbackRate","requestDelay","loadRate","bw","expectedLen","fragLoadedDelay","bufferStarvationDelay","fragLevelNextLoadedDelay","levelNextBitrate","loadedBytes","loadedDuration","fragLoadingProcessingMs","bwEstimate","getEstimate","bitrateTestDelay","_findBestLevel","currentFragDuration","currentBw","maxFetchDuration","bwFactor","bwUpFactor","avgDuration","adjustedbw","fetchDuration","forcedAutoLevel","bwEstimator","canEstimate","nextABRAutoLevel","_nextABRAutoLevel","avgbw","bestLevel","__WEBPACK_IMPORTED_MODULE_0__utils_ewma__","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","durationMs","numBytes","bandwidth","weight","getTotalWeight","EWMA","halfLife","alpha_","exp","estimate_","totalWeight_","adjAlpha","zeroFactor","__WEBPACK_IMPORTED_MODULE_4__utils_mediasource_helper__","BufferController","_msDuration","_levelDuration","_live","_objectUrl","onsbue","onSBUpdateEnd","onsbe","onSBUpdateError","pendingTracks","onLevelPtsUpdated","audioBuffer","timestampOffset","updating","audioTimestampOffset","audioExpected","videoExpected","sourceBufferNb","onMediaAttaching","ms","onmso","onMediaSourceOpen","onmse","onMediaSourceEnded","onmsc","onMediaSourceClose","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","flushBuffer","appendError","code","typeIn","bufStart","bufEnd","flushStart","flushEnd","CapLevelController","restrictedLevels","_stopCapping","onFpsDropLevelCapping","isLevelAllowed","droppedLevel","HTMLVideoElement","_startCapping","onLevelsUpdated","detectPlayerSize","levelsLength","getMaxLevel","capLevelIndex","validLevels","getMaxLevelByMediaSize","mediaWidth","mediaHeight","maxLevelIndex","clientWidth","offsetWidth","contentScaleFactor","clientHeight","offsetHeight","devicePixelRatio","FPSController","isVideoPlaybackQualityAvailable","getVideoPlaybackQuality","checkFPSInterval","checkFPS","decodedFrames","droppedFrames","lastTime","currentPeriod","currentDropped","lastDroppedFrames","currentDecoded","lastDecodedFrames","droppedFPS","totalDroppedFrames","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","XMLHttpRequest","XhrLoader","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","__WEBPACK_IMPORTED_MODULE_1__task_loop__","AudioTrackController","trackIdBlacklist","onAudioTrackLoaded","updatePeriodMs","_selectInitialAudioTrack","_handleLoadError","_updateTrack","currentAudioTrack","defaultTracks","trackFound","traverseTracks","_needsTrackLoading","_loadTrackDetailsIfNeeded","newId","previousId","_tracks$previousId","language","newTrack","__WEBPACK_IMPORTED_MODULE_4__level_helper__","__WEBPACK_IMPORTED_MODULE_5__utils_time_ranges__","__WEBPACK_IMPORTED_MODULE_7__utils_logger__","__WEBPACK_IMPORTED_MODULE_8__utils_discontinuities__","__WEBPACK_IMPORTED_MODULE_9__task_loop__","__WEBPACK_IMPORTED_MODULE_10__fragment_tracker__","__WEBPACK_IMPORTED_MODULE_11__loader_fragment__","STARTING","PAUSED","WAITING_TRACK","WAITING_INIT_PTS","AudioStreamController","waitingFragment","videoTrackCC","onInitPtsFound","demuxerId","trackDetails","mainBufferInfo","maxConfigBuffer","audioSwitch","loadIdx","fragLoadIdx","nextBuffered","isSeeking","waitingFrag","waitingFragCC","onAudioTracksUpdated","appendObj","pendingData","appendOnBufferFlush","newCue","captionScreen","row","indenting","indent","rows","isEmpty","chars","uchar","cueStartTime","__WEBPACK_IMPORTED_MODULE_0__vttparser__","findDirectionSetting","directionSetting","findAlignSetting","alignSetting","extend","cobj","isIE8","baseObj","createElement","hasBeenReset","_id","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","setting","SyntaxError","autoKeyword","displayState","","lr","rl","middle","left","right","getCueAsHTML","WebVTT","convertCueToDOMTree","reuseVttTextTrack","inUseTrack","manifestTrack","textTrack1","textTrack2","intersection","x1","y1","y2","__WEBPACK_IMPORTED_MODULE_2__utils_cea_608_parser__","__WEBPACK_IMPORTED_MODULE_3__utils_output_filter__","__WEBPACK_IMPORTED_MODULE_4__utils_webvtt_parser__","__WEBPACK_IMPORTED_MODULE_6__utils_texttrack_utils__","TimelineController","enabled","Cues","unparsedVttFrags","cueRanges","captionsTracks","captionsProperties","languageCode","channel1","channel2","cea608Parser","addCues","screen","ranges","merged","cueRange","overlap","getExistingTrack","createCaptionsTrack","_captionsProperties$t","existingTrack","createTextTrack","_cleanTracks","lastSn","prevCC","vttCCs","presentationOffset","inUseTracks","onLevelSwitching","closedCaptions","reset","decryptData","_parseVTTs","success","new","currentTrack","getCueById","textTrackCue","onFragDecrypted","onFragParsingUserdata","ccdatas","extractCea608Data","addData","tmpByte","ccbyte1","ccbyte2","ccValid","ccType","actualCCBytes","specialCea608CharsCodes","42","92","94","95","96","123","124","125","126","127","128","129","130","131","132","133","134","135","136","137","138","139","140","141","142","143","144","145","146","147","148","149","150","151","152","153","154","155","156","157","158","159","160","161","162","163","164","165","166","167","168","169","170","171","172","173","174","175","176","177","178","179","180","181","182","183","184","185","186","187","188","189","190","191","192","193","194","195","196","197","198","199","200","201","202","203","204","205","206","207","getCharForByte","byte","charCode","NR_ROWS","NR_COLS","rowsLowCh1","17","18","21","22","23","16","19","20","rowsHighCh1","rowsLowCh2","25","26","29","30","31","24","27","28","rowsHighCh2","backgroundColors","verboseFilter","DATA","DEBUG","INFO","WARNING","TEXT","verboseLevel","setTime","newTime","severity","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","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","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","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","padding","byteList","cmdFound","charsFound","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","channel","cond1","cond2","case1","case2","interpretPAC","pacIndex","channelNr","charCodes","charCode1","oneCode","hexCodes","OutputFilter","__WEBPACK_IMPORTED_MODULE_1__demux_id3__","startsWith","inputString","searchString","cueString2millis","timeString","secs","mins","hours","hash","calculateOffset","presentationTime","currCC","WebVTTParser","vttByteArray","syncPTS","callBack","errorCallBack","vttLines","cueTime","mpegTs","localTime","parsingError","inHeader","parser","cueOffset","onparsingerror","filterSubtitleTracks","textTrackList","SubtitleTrackController","_onTextTracksChanged","queuedDefaultTrack","trackChangeListener","useTextTrackPolling","subtitlePollingInterval","onTick","onSubtitleTrackLoaded","_stopTimer","setSubtitleTrackInternal","_toggleTrackModes","oldTrack","nextTrack","__WEBPACK_IMPORTED_MODULE_3__task_loop__","SubtitleStreamController","vttFragSNsProcessed","vttFragQueues","currentlyProcessing","currentTrackId","clearVttFragQueues","onSubtitleFragProcessed","processedFragSNs","fragQueue","currentFragSN","alreadyProcessed","alreadyInQueue","some","fragInQueue","onSubtitleTracksUpdated","onSubtitleTrackSwitch","KeySystems","WIDEVINE","PLAYREADY","createWidevineMediaKeySystemConfigurations","audioCodecs","videoCodecs","drmSystemOptions","baseConfig","videoCapabilities","contentType","getSupportedMediaKeySystemConfigurations","keySystem","EMEController","_widevineLicenseUrl","_licenseXhrSetup","_emeEnabled","_requestMediaKeySystemAccess","_mediaKeysList","_media","_hasSetMediaKeys","_isMediaEncrypted","_requestLicenseFailureCount","getLicenseServerUrl","_attemptKeySystemAccess","mediaKeySystemConfigs","requestMediaKeySystemAccess","mediaKeySystemAccess","_onMediaKeySystemAccessObtained","mediaKeysListItem","mediaKeys","mediaKeysSession","mediaKeysSessionInitialized","mediaKeySystemDomain","createMediaKeys","_onMediaKeysCreated","createSession","_onNewMediaKeySession","keySession","sessionId","_onKeySessionMessage","_requestLicense","update","_onMediaEncrypted","initDataType","_mediaEncryptionInitDataType","_mediaEncryptionInitData","_attemptSetMediaKeys","_generateRequestWithPreferredKeySession","keysListItem","setMediaKeys","_this6","generateRequest","_createLicenseXhr","keyMessage","_onLicenseRequestReadyStageChange","attemptsLeft","_generateLicenseRequestChallenge","challenge","_this7","endsWith","$defineProperty","stringLength","searchLength"],"mappings":"CAAA,SAAAA,EAAAC,GACA,gBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,IACA,kBAAAG,gBAAAC,IACAD,UAAAH,GACA,gBAAAC,SACAA,QAAA,IAAAD,IAEAD,EAAA,IAAAC,KACCK,KAAA,WACD,MCAgB,UAAUC,GCN1B,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAP,OAGA,IAAAC,GAAAO,EAAAD,IACAE,EAAAF,EACAG,GAAA,EACAV,WAUA,OANAK,GAAAE,GAAAI,KAAAV,EAAAD,QAAAC,IAA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AAA,EACA,QAGA,KADA,GAAAnI,IAAA,IACAA,EAAAyzE,GACA,GAAAr+D,EAAA0mC,WAAA3zC,EAAAnI,IAAAmsE,EAAArwB,WAAA97C,GACA,QAGA,UAEArQ,GACAA,EAAAgP,OAAAxO,UAAA,YACA+P,MAAAozE,EACA1jF,cAAA,EACAqR,UAAA,IAGAtC,OAAAxO,UAAAmjF,iB1Eu3lBqB","file":"hls.min.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","(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 /******/ (function(modules) { // webpackBootstrap\n/******/ \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 = 28);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return enableLogs; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return logger; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__get_self_scope__ = __webpack_require__(4);\nvar _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; };\n\n\n\nfunction noop() {}\n\nvar fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nvar exportedLogger = fakeLogger;\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\nvar global = Object(__WEBPACK_IMPORTED_MODULE_0__get_self_scope__[\"a\" /* getSelfScope */])();\n\nfunction consolePrintFn(type) {\n var func = global.console[type];\n if (func) {\n return function () {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n\n func.apply(global.console, args);\n };\n }\n return noop;\n}\n\nfunction exportLoggerFunctions(debugConfig) {\n for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n functions[_key2 - 1] = arguments[_key2];\n }\n\n functions.forEach(function (type) {\n exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);\n });\n}\n\nvar enableLogs = function enableLogs(debugConfig) {\n if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {\n exportLoggerFunctions(debugConfig,\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug', 'log', 'info', 'warn', 'error');\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 } else {\n exportedLogger = fakeLogger;\n }\n};\n\nvar logger = exportedLogger;\n\n/***/ }),\n/* 1 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/**\n * @readonly\n * @enum {string}\n */\nvar HlsEvents = {\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 }\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 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/* harmony default export */ __webpack_exports__[\"a\"] = (HlsEvents);\n\n/***/ }),\n/* 2 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return ErrorTypes; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return ErrorDetails; });\nvar 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 // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR: 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nvar ErrorDetails = {\n KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',\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 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/* 3 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\nvar _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; };\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/*\n*\n* All objects in the event handling chain should inherit from this class\n*\n*/\n\n\n\n\n\nvar FORBIDDEN_EVENT_NAMES = new Set(['hlsEventGeneric', 'hlsHandlerDestroying', 'hlsHandlerDestroyed']);\n\nvar EventHandler = function () {\n function EventHandler(hls) {\n _classCallCheck(this, EventHandler);\n\n this.hls = hls;\n this.onEvent = this.onEvent.bind(this);\n\n for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n events[_key - 1] = arguments[_key];\n }\n\n this.handledEvents = events;\n this.useGenericHandler = true;\n\n this.registerListeners();\n }\n\n EventHandler.prototype.destroy = function destroy() {\n this.onHandlerDestroying();\n this.unregisterListeners();\n this.onHandlerDestroyed();\n };\n\n EventHandler.prototype.onHandlerDestroying = function onHandlerDestroying() {};\n\n EventHandler.prototype.onHandlerDestroyed = function onHandlerDestroyed() {};\n\n EventHandler.prototype.isEventHandler = function isEventHandler() {\n return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';\n };\n\n EventHandler.prototype.registerListeners = function registerListeners() {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function (event) {\n if (FORBIDDEN_EVENT_NAMES.has(event)) {\n throw new Error('Forbidden event-name: ' + event);\n }\n\n this.hls.on(event, this.onEvent);\n }, this);\n }\n };\n\n EventHandler.prototype.unregisterListeners = function 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\n\n EventHandler.prototype.onEvent = function onEvent(event, data) {\n this.onEventGeneric(event, data);\n };\n\n EventHandler.prototype.onEventGeneric = function onEventGeneric(event, data) {\n var eventToFunction = function eventToFunction(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\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].error('An internal error happened while handling event ' + event + '. Error message: \"' + err.message + '\". Here is a stacktrace:', err);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_1__errors__[\"b\" /* ErrorTypes */].OTHER_ERROR, details: __WEBPACK_IMPORTED_MODULE_1__errors__[\"a\" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: false, event: event, err: err });\n }\n };\n\n return EventHandler;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (EventHandler);\n\n/***/ }),\n/* 4 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = getSelfScope;\nfunction getSelfScope() {\n // see https://stackoverflow.com/a/11237259/589493\n if (typeof window === 'undefined') {\n /* eslint-disable-next-line no-undef */\n return self;\n } else {\n return window;\n }\n}\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n// see https://tools.ietf.org/html/rfc1808\r\n\r\n/* jshint ignore:start */\r\n(function(root) { \r\n/* jshint ignore:end */\r\n\r\n var URL_REGEX = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\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 (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(true)\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/* 6 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nvar 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 search(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 } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n\n return null;\n }\n};\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (BinarySearch);\n\n/***/ }),\n/* 7 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return utf8ArrayToStr; });\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * ID3 parser\n */\nvar ID3 = function () {\n function ID3() {\n _classCallCheck(this, ID3);\n }\n\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 ID3.isHeader = function 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\n\n ID3.isFooter = function 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\n\n ID3.getID3Data = function getID3Data(data, offset) {\n var front = offset;\n var length = 0;\n\n while (ID3.isHeader(data, offset)) {\n // ID3 header is 10 bytes\n length += 10;\n\n var 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 ID3._readSize = function _readSize(data, offset) {\n var 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\n\n ID3.getTimeStamp = function getTimeStamp(data) {\n var frames = ID3.getID3Frames(data);\n for (var i = 0; i < frames.length; i++) {\n var 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\n\n ID3.isTimeStampFrame = function isTimeStampFrame(frame) {\n return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';\n };\n\n ID3._getFrameData = function _getFrameData(data) {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n var type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n var size = ID3._readSize(data, 4);\n\n // skip frame id, size, and flags\n var offset = 10;\n\n return { type: type, size: 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\n\n ID3.getID3Frames = function getID3Frames(id3Data) {\n var offset = 0;\n var frames = [];\n\n while (ID3.isHeader(id3Data, offset)) {\n var size = ID3._readSize(id3Data, offset + 6);\n // skip past ID3 header\n offset += 10;\n var end = offset + size;\n // loop through frames in the ID3 tag\n while (offset + 8 < end) {\n var frameData = ID3._getFrameData(id3Data.subarray(offset));\n var frame = ID3._decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\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 ID3._decodeFrame = function _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 ID3._readTimeStamp = function _readTimeStamp(timeStampFrame) {\n if (timeStampFrame.data.byteLength === 8) {\n var 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 var pts33Bit = data[3] & 0x1;\n var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];\n timestamp /= 45;\n\n if (pts33Bit) {\n timestamp += 47721858.84;\n } // 2^32 / 90\n\n return Math.round(timestamp);\n }\n\n return undefined;\n };\n\n ID3._decodePrivFrame = function _decodePrivFrame(frame) {\n /*\n Format: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n var owner = ID3._utf8ArrayToStr(frame.data, true);\n var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n };\n\n ID3._decodeTextFrame = function _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 var index = 1;\n var description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n var 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 var text = ID3._utf8ArrayToStr(frame.data.subarray(1));\n return { key: frame.type, data: text };\n }\n };\n\n ID3._decodeURLFrame = function _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 var index = 1;\n var description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n var 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 var 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\n\n ID3._utf8ArrayToStr = function _utf8ArrayToStr(array) {\n var exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var len = array.length;\n var c = void 0;\n var char2 = void 0;\n var char3 = void 0;\n var out = '';\n var i = 0;\n while (i < len) {\n c = array[i++];\n if (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\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 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);\n break;\n default:\n }\n }\n return out;\n };\n\n return ID3;\n}();\n\nvar utf8ArrayToStr = ID3._utf8ArrayToStr;\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (ID3);\n\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__event_handler__ = __webpack_require__(3);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n\n\n/**\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\n\nvar TaskLoop = function (_EventHandler) {\n _inherits(TaskLoop, _EventHandler);\n\n function TaskLoop(hls) {\n _classCallCheck(this, TaskLoop);\n\n for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n events[_key - 1] = arguments[_key];\n }\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call.apply(_EventHandler, [this, hls].concat(events)));\n\n _this._tickInterval = null;\n _this._tickTimer = null;\n _this._tickCallCount = 0;\n _this._boundTick = _this.tick.bind(_this);\n return _this;\n }\n\n /**\n * @override\n */\n\n\n TaskLoop.prototype.onHandlerDestroying = function onHandlerDestroying() {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n };\n\n /**\n * @returns {boolean}\n */\n\n\n TaskLoop.prototype.hasInterval = function hasInterval() {\n return !!this._tickInterval;\n };\n\n /**\n * @returns {boolean}\n */\n\n\n TaskLoop.prototype.hasNextTick = function hasNextTick() {\n return !!this._tickTimer;\n };\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n */\n\n\n TaskLoop.prototype.setInterval = function (_setInterval) {\n function setInterval(_x) {\n return _setInterval.apply(this, arguments);\n }\n\n setInterval.toString = function () {\n return _setInterval.toString();\n };\n\n return setInterval;\n }(function (millis) {\n if (!this._tickInterval) {\n this._tickInterval = setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n });\n\n /**\n * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n */\n\n\n TaskLoop.prototype.clearInterval = function (_clearInterval) {\n function clearInterval() {\n return _clearInterval.apply(this, arguments);\n }\n\n clearInterval.toString = function () {\n return _clearInterval.toString();\n };\n\n return clearInterval;\n }(function () {\n if (this._tickInterval) {\n clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n });\n\n /**\n * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n\n\n TaskLoop.prototype.clearNextTick = function clearNextTick() {\n if (this._tickTimer) {\n clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n };\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n\n\n TaskLoop.prototype.tick = function tick() {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.clearNextTick();\n this._tickTimer = setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n };\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n\n\n TaskLoop.prototype.doTick = function doTick() {};\n\n return TaskLoop;\n}(__WEBPACK_IMPORTED_MODULE_0__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (TaskLoop);\n\n/***/ }),\n/* 9 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit__ = __webpack_require__(5);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_url_toolkit__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__level_key__ = __webpack_require__(18);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\nvar Fragment = function () {\n function Fragment() {\n var _elementaryStreams;\n\n _classCallCheck(this, Fragment);\n\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n this.tagList = [];\n\n // Holds the types of data this fragment supports\n this._elementaryStreams = (_elementaryStreams = {}, _elementaryStreams[Fragment.ElementaryStreamTypes.AUDIO] = false, _elementaryStreams[Fragment.ElementaryStreamTypes.VIDEO] = false, _elementaryStreams);\n }\n\n /**\n * `type` property for this._elementaryStreams\n *\n * @enum\n */\n\n\n /**\n * @param {ElementaryStreamType} type\n */\n Fragment.prototype.addElementaryStream = function addElementaryStream(type) {\n this._elementaryStreams[type] = true;\n };\n\n /**\n * @param {ElementaryStreamType} type\n */\n\n\n Fragment.prototype.hasElementaryStream = function hasElementaryStream(type) {\n return this._elementaryStreams[type] === true;\n };\n\n /**\n * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n * @returns {Uint8Array}\n */\n\n\n Fragment.prototype.createInitializationVector = function 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\n\n Fragment.prototype.fragmentDecryptdataFromLevelkey = function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {\n var decryptdata = levelkey;\n\n if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {\n decryptdata = new __WEBPACK_IMPORTED_MODULE_1__level_key__[\"a\" /* default */]();\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 _createClass(Fragment, [{\n key: 'url',\n get: function get() {\n if (!this._url && this.relurl) {\n this._url = __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default.a.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\n\n return this._url;\n },\n set: function set(value) {\n this._url = value;\n }\n }, {\n key: 'programDateTime',\n get: function get() {\n if (!this._programDateTime && this.rawProgramDateTime) {\n this._programDateTime = new Date(Date.parse(this.rawProgramDateTime));\n }\n\n return this._programDateTime;\n }\n }, {\n key: 'byteRange',\n get: function get() {\n if (!this._byteRange && !this.rawByteRange) {\n return [];\n }\n\n if (this._byteRange) {\n return this._byteRange;\n }\n\n var byteRange = [];\n if (this.rawByteRange) {\n var params = this.rawByteRange.split('@', 2);\n if (params.length === 1) {\n var lastByteRangeEndOffset = this.lastByteRangeEndOffset;\n byteRange[0] = lastByteRangeEndOffset || 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n return byteRange;\n }\n\n /**\n * @type {number}\n */\n\n }, {\n key: 'byteRangeStartOffset',\n get: function get() {\n return this.byteRange[0];\n }\n }, {\n key: 'byteRangeEndOffset',\n get: function get() {\n return this.byteRange[1];\n }\n }, {\n key: 'decryptdata',\n get: function get() {\n if (!this._decryptdata) {\n this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);\n }\n\n return this._decryptdata;\n }\n }, {\n key: 'encrypted',\n get: function get() {\n return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);\n }\n }], [{\n key: 'ElementaryStreamTypes',\n get: function get() {\n return {\n AUDIO: 'audio',\n VIDEO: 'video'\n };\n }\n }]);\n\n return Fragment;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (Fragment);\n\n/***/ }),\n/* 10 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return FragmentState; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return FragmentTracker; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n\n\n\nvar FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nvar FragmentTracker = function (_EventHandler) {\n _inherits(FragmentTracker, _EventHandler);\n\n function FragmentTracker(hls) {\n _classCallCheck(this, FragmentTracker);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].BUFFER_APPENDED, __WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_BUFFERED, __WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_LOADED));\n\n _this.bufferPadding = 0.2;\n\n _this.fragments = Object.create(null);\n _this.timeRanges = Object.create(null);\n\n _this.config = hls.config;\n return _this;\n }\n\n FragmentTracker.prototype.destroy = function destroy() {\n this.fragments = null;\n this.timeRanges = null;\n this.config = null;\n __WEBPACK_IMPORTED_MODULE_0__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n _EventHandler.prototype.destroy.call(this);\n };\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n\n\n FragmentTracker.prototype.getBufferedFrag = function getBufferedFrag(position, levelType) {\n var fragments = this.fragments;\n var bufferedFrags = Object.keys(fragments).filter(function (key) {\n var fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n var frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n var bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n };\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n\n\n FragmentTracker.prototype.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) {\n var _this2 = this;\n\n var fragmentTimes = void 0,\n time = void 0;\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(function (key) {\n var fragmentEntity = _this2.fragments[key];\n if (fragmentEntity.buffered === true) {\n var esData = fragmentEntity.range[elementaryStream];\n if (esData) {\n fragmentTimes = esData.time;\n for (var i = 0; i < fragmentTimes.length; i++) {\n time = fragmentTimes[i];\n\n if (_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {\n // Unregister partial fragment as it needs to load again to be reused\n _this2.removeFragment(fragmentEntity.body);\n break;\n }\n }\n }\n }\n });\n };\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n\n\n FragmentTracker.prototype.detectPartialFragments = function detectPartialFragments(fragment) {\n var _this3 = this;\n\n var fragKey = this.getFragmentKey(fragment);\n var fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(function (elementaryStream) {\n if (fragment.hasElementaryStream(elementaryStream) === true) {\n var timeRange = _this3.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n };\n\n FragmentTracker.prototype.getBufferedTimes = function getBufferedTimes(startPTS, endPTS, timeRange) {\n var fragmentTimes = [];\n var startTime = void 0,\n endTime = void 0;\n var fragmentPartial = false;\n for (var i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n };\n\n FragmentTracker.prototype.getFragmentKey = function getFragmentKey(fragment) {\n return fragment.type + '_' + fragment.level + '_' + fragment.urlId + '_' + fragment.sn;\n };\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n\n\n FragmentTracker.prototype.getPartialFragment = function getPartialFragment(time) {\n var _this4 = this;\n\n var timePadding = void 0,\n startTime = void 0,\n endTime = void 0;\n var bestFragment = null;\n var bestOverlap = 0;\n Object.keys(this.fragments).forEach(function (key) {\n var fragmentEntity = _this4.fragments[key];\n if (_this4.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;\n endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n };\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n\n\n FragmentTracker.prototype.getState = function getState(fragment) {\n var fragKey = this.getFragmentKey(fragment);\n var fragmentEntity = this.fragments[fragKey];\n var state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n };\n\n FragmentTracker.prototype.isPartial = function isPartial(fragmentEntity) {\n return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);\n };\n\n FragmentTracker.prototype.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {\n var startTime = void 0,\n endTime = void 0;\n for (var i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n };\n\n /**\n * Fires when a fragment loading is completed\n */\n\n\n FragmentTracker.prototype.onFragLoaded = function onFragLoaded(e) {\n var fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!isNaN(fragment.sn) && !fragment.bitrateTest) {\n var fragKey = this.getFragmentKey(fragment);\n var fragmentEntity = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n this.fragments[fragKey] = fragmentEntity;\n }\n };\n\n /**\n * Fires when the buffer is updated\n */\n\n\n FragmentTracker.prototype.onBufferAppended = function onBufferAppended(e) {\n var _this5 = this;\n\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(function (elementaryStream) {\n var timeRange = _this5.timeRanges[elementaryStream];\n _this5.detectEvictedFragments(elementaryStream, timeRange);\n });\n };\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n\n\n FragmentTracker.prototype.onFragBuffered = function onFragBuffered(e) {\n this.detectPartialFragments(e.frag);\n };\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n\n\n FragmentTracker.prototype.hasFragment = function hasFragment(fragment) {\n var fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n };\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n\n\n FragmentTracker.prototype.removeFragment = function removeFragment(fragment) {\n var fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n };\n\n /**\n * Remove all fragments from fragment tracker.\n */\n\n\n FragmentTracker.prototype.removeAllFragments = function removeAllFragments() {\n this.fragments = Object.create(null);\n };\n\n return FragmentTracker;\n}(__WEBPACK_IMPORTED_MODULE_0__event_handler__[\"a\" /* default */]);\n\n/***/ }),\n/* 11 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return BufferHelper; });\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\nvar BufferHelper = function () {\n function BufferHelper() {\n _classCallCheck(this, BufferHelper);\n }\n\n /**\n * Return true if `media`'s buffered include `position`\n * @param {HTMLMediaElement|SourceBuffer} media\n * @param {number} position\n * @returns {boolean}\n */\n BufferHelper.isBuffered = function isBuffered(media, position) {\n try {\n if (media) {\n var buffered = media.buffered;\n for (var i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n };\n\n BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {\n try {\n if (media) {\n var vbuffered = media.buffered,\n buffered = [],\n i = void 0;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });\n }\n\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n };\n\n BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {\n var buffered2 = [],\n\n // bufferStart and bufferEnd are buffer boundaries around current video position\n bufferLen = void 0,\n bufferStart = void 0,\n bufferEnd = void 0,\n bufferStartNext = void 0,\n i = void 0;\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 return BufferHelper;\n}();\n\n/***/ }),\n/* 12 */\n/***/ (function(module, exports) {\n\n// 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/* 13 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__aes_crypto__ = __webpack_require__(35);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__fast_aes_key__ = __webpack_require__(36);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__aes_decryptor__ = __webpack_require__(37);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_get_self_scope__ = __webpack_require__(4);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\n\n\n\n\n\n\n\n// see https://stackoverflow.com/a/11237259/589493\nvar global = Object(__WEBPACK_IMPORTED_MODULE_6__utils_get_self_scope__[\"a\" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread\n\nvar Decrypter = function () {\n function Decrypter(observer, config) {\n var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},\n _ref$removePKCS7Paddi = _ref.removePKCS7Padding,\n removePKCS7Padding = _ref$removePKCS7Paddi === undefined ? true : _ref$removePKCS7Paddi;\n\n _classCallCheck(this, Decrypter);\n\n this.logEnabled = true;\n this.observer = observer;\n this.config = config;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n var browserCrypto = global.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {}\n }\n this.disableWebCrypto = !this.subtle;\n }\n\n Decrypter.prototype.isSync = function isSync() {\n return this.disableWebCrypto && this.config.enableSoftwareAES;\n };\n\n Decrypter.prototype.decrypt = function decrypt(data, key, iv, callback) {\n var _this = this;\n\n if (this.disableWebCrypto && this.config.enableSoftwareAES) {\n if (this.logEnabled) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('JS AES decrypt');\n this.logEnabled = false;\n }\n var decryptor = this.decryptor;\n if (!decryptor) {\n this.decryptor = decryptor = new __WEBPACK_IMPORTED_MODULE_2__aes_decryptor__[\"a\" /* default */]();\n }\n\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));\n } else {\n if (this.logEnabled) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('WebCrypto AES decrypt');\n this.logEnabled = false;\n }\n var subtle = this.subtle;\n if (this.key !== key) {\n this.key = key;\n this.fastAesKey = new __WEBPACK_IMPORTED_MODULE_1__fast_aes_key__[\"a\" /* default */](subtle, key);\n }\n\n this.fastAesKey.expandKey().then(function (aesKey) {\n // decrypt using web crypto\n var crypto = new __WEBPACK_IMPORTED_MODULE_0__aes_crypto__[\"a\" /* default */](subtle, iv);\n crypto.decrypt(data, aesKey).catch(function (err) {\n _this.onWebCryptoError(err, data, key, iv, callback);\n }).then(function (result) {\n callback(result);\n });\n }).catch(function (err) {\n _this.onWebCryptoError(err, data, key, iv, callback);\n });\n }\n };\n\n Decrypter.prototype.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) {\n if (this.config.enableSoftwareAES) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('WebCrypto Error, disable WebCrypto API');\n this.disableWebCrypto = true;\n this.logEnabled = true;\n this.decrypt(data, key, iv, callback);\n } else {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].error('decrypting error : ' + err.message);\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_5__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });\n }\n };\n\n Decrypter.prototype.destroy = function destroy() {\n var decryptor = this.decryptor;\n if (decryptor) {\n decryptor.destroy();\n this.decryptor = undefined;\n }\n };\n\n return Decrypter;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (Decrypter);\n\n/***/ }),\n/* 14 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = getMediaSource;\n/**\n * MediaSource helper\n */\n\nfunction getMediaSource() {\n if (typeof window !== 'undefined') {\n return window.MediaSource || window.WebKitMediaSource;\n }\n}\n\n/***/ }),\n/* 15 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = addGroupId;\n/* unused harmony export updatePTS */\n/* harmony export (immutable) */ __webpack_exports__[\"c\"] = updateFragPTSDTS;\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = mergeDetails;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\n/**\n * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\n\n\nfunction addGroupId(level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nfunction updatePTS(fragments, fromIdx, toIdx) {\n var fragFrom = fragments[fromIdx],\n fragTo = fragments[toIdx],\n 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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\nfunction updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {\n // update frag PTS/DTS\n var maxStartPTS = startPTS;\n if (!isNaN(frag.startPTS)) {\n // delta PTS between audio and video\n var 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\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 var 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 var sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n\n var fragIdx = void 0,\n fragments = void 0,\n i = void 0;\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\n details.PTSKnown = true;\n // logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);\n\n return drift;\n}\n\nfunction 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 = void 0;\n\n // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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/* 16 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__ = __webpack_require__(17);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__ = __webpack_require__(29);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\n\n\n\n\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\n\nvar ContextType = {\n MANIFEST: 'manifest',\n LEVEL: 'level',\n AUDIO_TRACK: 'audioTrack',\n SUBTITLE_TRACK: 'subtitleTrack'\n};\n\n/**\n * @enum {string}\n */\nvar LevelType = {\n MAIN: 'main',\n AUDIO: 'audio',\n SUBTITLE: 'subtitle'\n};\n\n/**\n * @constructor\n */\n\nvar PlaylistLoader = function (_EventHandler) {\n _inherits(PlaylistLoader, _EventHandler);\n\n /**\n * @constructs\n * @param {Hls} hls\n */\n function PlaylistLoader(hls) {\n _classCallCheck(this, PlaylistLoader);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_LOADING));\n\n _this.loaders = {};\n return _this;\n }\n\n /**\n * @param {ContextType} type\n * @returns {boolean}\n */\n PlaylistLoader.canHaveQualityLevels = function canHaveQualityLevels(type) {\n return type !== ContextType.AUDIO_TRACK && type !== ContextType.SUBTITLE_TRACK;\n };\n\n /**\n * Map context.type to LevelType\n * @param {{type: ContextType}} context\n * @returns {LevelType}\n */\n\n\n PlaylistLoader.mapContextToLevelType = function mapContextToLevelType(context) {\n var type = context.type;\n\n\n switch (type) {\n case ContextType.AUDIO_TRACK:\n return LevelType.AUDIO;\n case ContextType.SUBTITLE_TRACK:\n return LevelType.SUBTITLE;\n default:\n return LevelType.MAIN;\n }\n };\n\n PlaylistLoader.getResponseUrl = function getResponseUrl(response, context) {\n var url = response.url;\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 return url;\n };\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {object} context\n * @returns {XHRLoader} or other compatible configured overload\n */\n\n\n PlaylistLoader.prototype.createInternalLoader = function createInternalLoader(context) {\n var config = this.hls.config;\n var PLoader = config.pLoader;\n var Loader = config.loader;\n var InternalLoader = PLoader || Loader;\n\n var loader = new InternalLoader(config);\n\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n };\n\n PlaylistLoader.prototype.getInternalLoader = function getInternalLoader(context) {\n return this.loaders[context.type];\n };\n\n PlaylistLoader.prototype.resetInternalLoader = function resetInternalLoader(contextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n };\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n\n\n PlaylistLoader.prototype.destroyInternalLoaders = function destroyInternalLoaders() {\n for (var contextType in this.loaders) {\n var loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n };\n\n PlaylistLoader.prototype.destroy = function destroy() {\n this.destroyInternalLoaders();\n\n _EventHandler.prototype.destroy.call(this);\n };\n\n PlaylistLoader.prototype.onManifestLoading = function onManifestLoading(data) {\n this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });\n };\n\n PlaylistLoader.prototype.onLevelLoading = function onLevelLoading(data) {\n this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });\n };\n\n PlaylistLoader.prototype.onAudioTrackLoading = function onAudioTrackLoading(data) {\n this.load(data.url, { type: ContextType.AUDIO_TRACK, level: 0, id: data.id });\n };\n\n PlaylistLoader.prototype.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) {\n this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: 0, id: data.id });\n };\n\n PlaylistLoader.prototype.load = function load(url, context) {\n var config = this.hls.config;\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].debug('Loading playlist of type ' + context.type + ', level: ' + context.level + ', id: ' + context.id);\n\n // Check if a loader for this context already exists\n var loader = this.getInternalLoader(context);\n if (loader) {\n var loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) {\n // same URL can't overlap\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].trace('playlist request ongoing');\n return false;\n } else {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].warn('aborting previous loader for type: ' + context.type);\n loader.abort();\n }\n }\n\n var maxRetry = void 0,\n timeout = void 0,\n retryDelay = void 0,\n maxRetryDelay = void 0;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case ContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case ContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n context.url = url;\n context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)\n\n var loaderConfig = {\n timeout: timeout,\n maxRetry: maxRetry,\n retryDelay: retryDelay,\n maxRetryDelay: maxRetryDelay\n };\n\n var loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].debug('Calling internal loader delegate for URL: ' + url);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n };\n\n PlaylistLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {\n var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n\n var string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n };\n\n PlaylistLoader.prototype.loaderror = function loaderror(response, context) {\n var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n this._handleNetworkError(context, networkDetails);\n };\n\n PlaylistLoader.prototype.loadtimeout = function loadtimeout(stats, context) {\n var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n this._handleNetworkError(context, networkDetails, true);\n };\n\n PlaylistLoader.prototype._handleMasterPlaylist = function _handleMasterPlaylist(response, stats, context, networkDetails) {\n var hls = this.hls;\n var string = response.data;\n\n var url = PlaylistLoader.getResponseUrl(response, context);\n\n var levels = __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__[\"a\" /* default */].parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n\n var audioGroups = levels.map(function (level) {\n return {\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n };\n });\n\n var audioTracks = __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__[\"a\" /* default */].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n var subtitles = __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__[\"a\" /* default */].parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n var embeddedAudioFound = false;\n audioTracks.forEach(function (audioTrack) {\n if (!audioTrack.url) {\n embeddedAudioFound = true;\n }\n });\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('audio codec signaled in quality level, but no embedded audio track signaled, create one');\n audioTracks.unshift({\n type: 'main',\n name: 'main'\n });\n }\n }\n\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADED, {\n levels: levels,\n audioTracks: audioTracks,\n subtitles: subtitles,\n url: url,\n stats: stats,\n networkDetails: networkDetails\n });\n };\n\n PlaylistLoader.prototype._handleTrackOrLevelPlaylist = function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {\n var hls = this.hls;\n\n var id = context.id,\n level = context.level,\n type = context.type;\n\n\n var url = PlaylistLoader.getResponseUrl(response, context);\n\n var levelUrlId = isNaN(id) ? 0 : id;\n var levelId = isNaN(level) ? levelUrlId : level; // level -> id -> 0\n var levelType = PlaylistLoader.mapContextToLevelType(context);\n\n var levelDetails = __WEBPACK_IMPORTED_MODULE_5__m3u8_parser__[\"a\" /* default */].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n levelDetails.tload = stats.tload;\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === ContextType.MANIFEST) {\n var singleLevel = {\n url: url,\n details: levelDetails\n };\n\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url: url,\n stats: stats,\n networkDetails: networkDetails\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n var sidxUrl = levelDetails.initSegment.url;\n this.load(sidxUrl, {\n isSidxRequest: true,\n type: type,\n level: level,\n levelDetails: levelDetails,\n id: id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n };\n\n PlaylistLoader.prototype._handleSidxRequest = function _handleSidxRequest(response, context) {\n var sidxInfo = __WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__[\"a\" /* default */].parseSegmentIndex(new Uint8Array(response.data));\n sidxInfo.references.forEach(function (segmentRef, index) {\n var segRefInfo = segmentRef.info;\n var frag = context.levelDetails.fragments[index];\n\n if (frag.byteRange.length === 0) {\n frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);\n }\n });\n\n context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';\n };\n\n PlaylistLoader.prototype._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) {\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason: reason,\n networkDetails: networkDetails\n });\n };\n\n PlaylistLoader.prototype._handleNetworkError = function _handleNetworkError(context, networkDetails) {\n var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].info('A network error occured while loading a ' + context.type + '-type playlist');\n\n var details = void 0;\n var fatal = void 0;\n\n var loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case ContextType.MANIFEST:\n details = timeout ? __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].MANIFEST_LOAD_TIMEOUT : __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].MANIFEST_LOAD_ERROR;\n fatal = true;\n break;\n case ContextType.LEVEL:\n details = timeout ? __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT : __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_ERROR;\n fatal = false;\n break;\n case ContextType.AUDIO_TRACK:\n details = timeout ? __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT : __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR;\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR,\n details: details,\n fatal: fatal,\n url: loader.url,\n loader: loader,\n context: context,\n networkDetails: networkDetails\n });\n };\n\n PlaylistLoader.prototype._handlePlaylistLoaded = function _handlePlaylistLoaded(response, stats, context, networkDetails) {\n var type = context.type,\n level = context.level,\n id = context.id,\n levelDetails = context.levelDetails;\n\n\n if (!levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats: stats,\n networkDetails: networkDetails\n });\n } else {\n switch (type) {\n case ContextType.AUDIO_TRACK:\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id: id,\n stats: stats,\n networkDetails: networkDetails\n });\n break;\n case ContextType.SUBTITLE_TRACK:\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id: id,\n stats: stats,\n networkDetails: networkDetails\n });\n break;\n }\n }\n };\n\n _createClass(PlaylistLoader, null, [{\n key: 'ContextType',\n get: function get() {\n return ContextType;\n }\n }, {\n key: 'LevelType',\n get: function get() {\n return LevelType;\n }\n }]);\n\n return PlaylistLoader;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (PlaylistLoader);\n\n/***/ }),\n/* 17 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * MP4 demuxer\n */\n\n\n\nvar UINT32_MAX = Math.pow(2, 32) - 1;\n\nvar MP4Demuxer = function () {\n function MP4Demuxer(observer, remuxer) {\n _classCallCheck(this, MP4Demuxer);\n\n this.observer = observer;\n this.remuxer = remuxer;\n }\n\n MP4Demuxer.prototype.resetTimeStamp = function resetTimeStamp(initPTS) {\n this.initPTS = initPTS;\n };\n\n MP4Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {\n // jshint unused:false\n if (initSegment && initSegment.byteLength) {\n var 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\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\n if (initData.video) {\n tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };\n }\n }\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\n\n if (videoCodec) {\n this.videoCodec = videoCodec;\n }\n }\n };\n\n MP4Demuxer.probe = function 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 MP4Demuxer.bin2str = function bin2str(buffer) {\n return String.fromCharCode.apply(null, buffer);\n };\n\n MP4Demuxer.readUint16 = function readUint16(buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n var val = buffer[offset] << 8 | buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\n };\n\n MP4Demuxer.readUint32 = function readUint32(buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];\n return val < 0 ? 4294967296 + val : val;\n };\n\n MP4Demuxer.writeUint32 = function 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 // Find the data for a box specified by its path\n\n\n MP4Demuxer.findBox = function findBox(data, path) {\n var results = [],\n i = void 0,\n size = void 0,\n type = void 0,\n end = void 0,\n subresults = void 0,\n start = void 0,\n endbox = void 0;\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 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 MP4Demuxer.parseSegmentIndex = function parseSegmentIndex(initSegment) {\n var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n var index = 0;\n var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n var references = void 0;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n var version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n var timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n var earliestPresentationTime = 0;\n var firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n var startByte = sidx.end + firstOffset;\n\n var referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (var i = 0; i < referencesCount; i++) {\n var referenceIndex = index;\n\n var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n var referenceSize = referenceInfo & 0x7FFFFFFF;\n var referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize: referenceSize,\n subsegmentDuration: subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime: earliestPresentationTime,\n timescale: timescale,\n version: version,\n referencesCount: referencesCount,\n references: references,\n moovEndOffset: moovEndOffset\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\n\n MP4Demuxer.parseInitSegment = function parseInitSegment(initSegment) {\n var result = [];\n var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);\n\n traks.forEach(function (trak) {\n var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n var version = tkhd.data[tkhd.start];\n var index = version === 0 ? 12 : 20;\n var trackId = MP4Demuxer.readUint32(tkhd, index);\n\n var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd.data[mdhd.start];\n index = version === 0 ? 12 : 20;\n var timescale = MP4Demuxer.readUint32(mdhd, index);\n\n var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));\n var 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 var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);\n if (codecBox.length) {\n codecBox = codecBox[0];\n var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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 * 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 */\n\n\n MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) {\n var trafs = void 0,\n baseTimes = void 0,\n result = void 0;\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 = void 0,\n scale = void 0,\n baseTime = void 0;\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 = void 0,\n result = void 0;\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 MP4Demuxer.offsetStartDTS = function 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 var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n var 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\n\n MP4Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {\n var initData = this.initData;\n if (!initData) {\n this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);\n initData = this.initData;\n }\n var startDTS = void 0,\n initPTS = this.initPTS;\n if (initPTS === undefined) {\n var _startDTS = MP4Demuxer.getStartDTS(initData, data);\n this.initPTS = initPTS = _startDTS - timeOffset;\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].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 MP4Demuxer.prototype.destroy = function destroy() {};\n\n return MP4Demuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (MP4Demuxer);\n\n/***/ }),\n/* 18 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit__ = __webpack_require__(5);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_url_toolkit__);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\nvar LevelKey = function () {\n function LevelKey() {\n _classCallCheck(this, LevelKey);\n\n this.method = null;\n this.key = null;\n this.iv = null;\n this._uri = null;\n }\n\n _createClass(LevelKey, [{\n key: 'uri',\n get: function get() {\n if (!this._uri && this.reluri) {\n this._uri = __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default.a.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });\n }\n\n return this._uri;\n }\n }]);\n\n return LevelKey;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (LevelKey);\n\n/***/ }),\n/* 19 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return isCodecType; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return isCodecSupportedInMp4; });\n// from http://mp4ra.org/codecs.html\nvar 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 var typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nfunction isCodecSupportedInMp4(codec, type) {\n return window.MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs=\"' + codec + '\"');\n}\n\n\n\n/***/ }),\n/* 20 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_events__ = __webpack_require__(12);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_events__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_webworkify_webpack__ = __webpack_require__(34);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_webworkify_webpack___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_webworkify_webpack__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__demux_demuxer_inline__ = __webpack_require__(21);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_mediasource_helper__ = __webpack_require__(14);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_get_self_scope__ = __webpack_require__(4);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\n\n\n\n\n\n\n// see https://stackoverflow.com/a/11237259/589493\nvar global = Object(__WEBPACK_IMPORTED_MODULE_7__utils_get_self_scope__[\"a\" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread\nvar MediaSource = Object(__WEBPACK_IMPORTED_MODULE_6__utils_mediasource_helper__[\"a\" /* getMediaSource */])();\n\nvar Demuxer = function () {\n function Demuxer(hls, id) {\n _classCallCheck(this, Demuxer);\n\n this.hls = hls;\n this.id = id;\n // observer setup\n var observer = this.observer = new __WEBPACK_IMPORTED_MODULE_0_events___default.a();\n var config = hls.config;\n observer.trigger = function trigger(event) {\n for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n data[_key - 1] = arguments[_key];\n }\n\n observer.emit.apply(observer, [event, event].concat(data));\n };\n\n observer.off = function off(event) {\n for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n data[_key2 - 1] = arguments[_key2];\n }\n\n observer.removeListener.apply(observer, [event].concat(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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_DECRYPTED, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_DATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSED, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_METADATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].INIT_PTS_FOUND, forwardMessage);\n\n var 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 var vendor = navigator.vendor;\n if (config.enableWorker && typeof Worker !== 'undefined') {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('demuxing in webworker');\n var w = void 0;\n try {\n w = this.w = __WEBPACK_IMPORTED_MODULE_1_webworkify_webpack___default()(/*require.resolve*/(47));\n this.onwmsg = this.onWorkerMessage.bind(this);\n w.addEventListener('message', this.onwmsg);\n w.onerror = function (event) {\n hls.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_5__errors__[\"b\" /* ErrorTypes */].OTHER_ERROR, details: __WEBPACK_IMPORTED_MODULE_5__errors__[\"a\" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });\n };\n w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });\n } catch (err) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 global.URL.revokeObjectURL(w.objectURL);\n }\n this.demuxer = new __WEBPACK_IMPORTED_MODULE_3__demux_demuxer_inline__[\"a\" /* default */](observer, typeSupported, config, vendor);\n this.w = undefined;\n }\n } else {\n this.demuxer = new __WEBPACK_IMPORTED_MODULE_3__demux_demuxer_inline__[\"a\" /* default */](observer, typeSupported, config, vendor);\n }\n }\n\n Demuxer.prototype.destroy = function destroy() {\n var w = this.w;\n if (w) {\n w.removeEventListener('message', this.onwmsg);\n w.terminate();\n this.w = null;\n } else {\n var demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n this.demuxer = null;\n }\n }\n var observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n this.observer = null;\n }\n };\n\n Demuxer.prototype.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {\n var w = this.w;\n var timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start;\n var decryptdata = frag.decryptdata;\n var lastFrag = this.frag;\n var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);\n var trackSwitch = !(lastFrag && frag.level === lastFrag.level);\n var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;\n var contiguous = !trackSwitch && nextSN;\n if (discontinuity) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log(this.id + ':discontinuity detected');\n }\n\n if (trackSwitch) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log(this.id + ':switch detected');\n }\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: 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] : []);\n } else {\n var 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 Demuxer.prototype.onWorkerMessage = function onWorkerMessage(ev) {\n var data = ev.data,\n hls = this.hls;\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 global.URL.revokeObjectURL(this.w.objectURL);\n break;\n // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects\n case __WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].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\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 return Demuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (Demuxer);\n\n/***/ }),\n/* 21 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__crypt_decrypter__ = __webpack_require__(13);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__demux_aacdemuxer__ = __webpack_require__(38);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__ = __webpack_require__(17);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__demux_tsdemuxer__ = __webpack_require__(39);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__demux_mp3demuxer__ = __webpack_require__(42);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__ = __webpack_require__(43);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__remux_passthrough_remuxer__ = __webpack_require__(46);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_get_self_scope__ = __webpack_require__(4);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n// see https://stackoverflow.com/a/11237259/589493\nvar global = Object(__WEBPACK_IMPORTED_MODULE_9__utils_get_self_scope__[\"a\" /* getSelfScope */])(); // safeguard for code that might run both on worker and main thread\nvar performance = global;\n\nvar DemuxerInline = function () {\n function DemuxerInline(observer, typeSupported, config, vendor) {\n _classCallCheck(this, DemuxerInline);\n\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n }\n\n DemuxerInline.prototype.destroy = function destroy() {\n var demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n };\n\n DemuxerInline.prototype.push = function 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 var decrypter = this.decrypter;\n if (decrypter == null) {\n decrypter = this.decrypter = new __WEBPACK_IMPORTED_MODULE_2__crypt_decrypter__[\"a\" /* default */](this.observer, this.config);\n }\n\n var localthis = this;\n // performance.now() not available on WebWorker, at least on Safari Desktop\n var startTime = void 0;\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 = void 0;\n try {\n endTime = performance.now();\n } catch (error) {\n endTime = Date.now();\n }\n localthis.observer.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 DemuxerInline.prototype.pushDecrypted = function 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, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n // so let's check that current demuxer is still valid\n (discontinuity || trackSwitch) && !this.probe(data)) {\n var observer = this.observer;\n var typeSupported = this.typeSupported;\n var config = this.config;\n // probing order is TS/AAC/MP3/MP4\n var muxConfig = [{ demux: __WEBPACK_IMPORTED_MODULE_5__demux_tsdemuxer__[\"a\" /* default */], remux: __WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__[\"a\" /* default */] }, { demux: __WEBPACK_IMPORTED_MODULE_4__demux_mp4demuxer__[\"a\" /* default */], remux: __WEBPACK_IMPORTED_MODULE_8__remux_passthrough_remuxer__[\"a\" /* default */] }, { demux: __WEBPACK_IMPORTED_MODULE_3__demux_aacdemuxer__[\"a\" /* default */], remux: __WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__[\"a\" /* default */] }, { demux: __WEBPACK_IMPORTED_MODULE_6__demux_mp3demuxer__[\"a\" /* default */], remux: __WEBPACK_IMPORTED_MODULE_7__remux_mp4_remuxer__[\"a\" /* default */] }];\n\n // probe for content type\n for (var i = 0, len = muxConfig.length; i < len; i++) {\n var mux = muxConfig[i];\n var probe = mux.demux.probe;\n if (probe(data)) {\n var _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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_1__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_1__errors__[\"a\" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });\n return;\n }\n this.demuxer = demuxer;\n }\n var 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\n demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);\n };\n\n return DemuxerInline;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (DemuxerInline);\n\n/***/ }),\n/* 22 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export getAudioConfig */\n/* unused harmony export isHeaderPattern */\n/* unused harmony export getHeaderLength */\n/* unused harmony export getFullFrameLength */\n/* harmony export (immutable) */ __webpack_exports__[\"d\"] = isHeader;\n/* harmony export (immutable) */ __webpack_exports__[\"e\"] = probe;\n/* harmony export (immutable) */ __webpack_exports__[\"c\"] = initTrackConfig;\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = getFrameDuration;\n/* unused harmony export parseFrameHeader */\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = appendFrame;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_get_self_scope__ = __webpack_require__(4);\n/**\n * ADTS parser helper\n */\n\n\n\n\n\n\n\nfunction getAudioConfig(observer, data, offset, audioCodec) {\n var adtsObjectType = void 0,\n // :int\n adtsSampleingIndex = void 0,\n // :int\n adtsExtensionSampleingIndex = void 0,\n // :int\n adtsChanelConfig = void 0,\n // :int\n config = void 0,\n userAgent = navigator.userAgent.toLowerCase(),\n manifestCodec = audioCodec,\n adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_1__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_1__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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 || audioCodec.indexOf('mp4a.40.5') !== -1) || !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 || /vivaldi/i.test(userAgent)) || !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\nfunction isHeaderPattern(data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nfunction getHeaderLength(data, offset) {\n return data[offset + 1] & 0x01 ? 7 : 9;\n}\n\nfunction getFullFrameLength(data, offset) {\n return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;\n}\n\nfunction 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\n return false;\n}\n\nfunction 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 var headerLength = getHeaderLength(data, offset);\n // ADTS frame Length\n var frameLength = headerLength;\n if (offset + 5 < data.length) {\n frameLength = getFullFrameLength(data, offset);\n }\n\n var 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\nfunction 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);\n }\n}\n\nfunction getFrameDuration(samplerate) {\n return 1024 * 90000 / samplerate;\n}\n\nfunction parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {\n var headerLength = void 0,\n frameLength = void 0,\n stamp = void 0;\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: headerLength, frameLength: frameLength, stamp: stamp };\n }\n\n return undefined;\n}\n\nfunction 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/* 23 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/**\n * MPEG parser helper\n */\n\nvar MpegAudio = {\n\n 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],\n\n SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],\n\n SamplesCoefficients: [\n // MPEG 2.5\n [0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]],\n\n BytesInSlot: [0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\n\n appendFrame: function appendFrame(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 = header.samplesPerFrame * 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: sample, length: header.frameLength };\n }\n\n return undefined;\n },\n\n parseHeader: function parseHeader(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] >> 1 & 1;\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 channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n var bytesInSlot = MpegAudio.BytesInSlot[headerC];\n var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame };\n }\n\n return undefined;\n },\n\n isHeaderPattern: function isHeaderPattern(data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n },\n\n isHeader: function isHeader(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\n return false;\n },\n\n probe: function probe(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 var headerLength = 4;\n // MPEG frame Length\n var header = this.parseHeader(data, offset);\n var frameLength = headerLength;\n if (header && header.frameLength) {\n frameLength = header.frameLength;\n }\n\n var 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\n/* harmony default export */ __webpack_exports__[\"a\"] = (MpegAudio);\n\n/***/ }),\n/* 24 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/**\n * TimeRanges to string helper\n */\n\nvar TimeRanges = {\n toString: function toString(r) {\n var log = '',\n 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\n return log;\n }\n};\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (TimeRanges);\n\n/***/ }),\n/* 25 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export findFirstFragWithCC */\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = findFragWithCC;\n/* unused harmony export shouldAlignOnDiscontinuities */\n/* unused harmony export findDiscontinuousReferenceFrag */\n/* unused harmony export adjustPts */\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = alignDiscontinuities;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__binary_search__ = __webpack_require__(6);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_logger__ = __webpack_require__(0);\n\n\n\nfunction findFirstFragWithCC(fragments, cc) {\n var firstFrag = null;\n\n for (var i = 0; i < fragments.length; i += 1) {\n var currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nfunction findFragWithCC(fragments, CC) {\n return __WEBPACK_IMPORTED_MODULE_0__binary_search__[\"a\" /* default */].search(fragments, function (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\nfunction shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {\n var 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\nfunction findDiscontinuousReferenceFrag(prevDetails, curDetails) {\n var prevFrags = prevDetails.fragments;\n var curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('No fragments to align');\n return;\n }\n\n var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nfunction adjustPts(sliding, details) {\n details.fragments.forEach(function (frag) {\n if (frag) {\n var 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\nfunction alignDiscontinuities(lastFrag, lastLevel, details) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);\n if (referenceFrag) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* 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 && lastLevel.details.fragments && lastLevel.details.fragments.length) {\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 var lastPDT = lastLevel.details.programDateTime;\n var newPDT = details.programDateTime;\n // date diff is in ms. frag.start is in seconds\n var sliding = (newPDT - lastPDT) / 1000 + lastLevel.details.fragments[0].start;\n if (!isNaN(sliding)) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3));\n adjustPts(sliding, details);\n }\n }\n}\n\n/***/ }),\n/* 26 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = sendAddTrackEvent;\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = clearCurrentCues;\n\nfunction sendAddTrackEvent(track, videoEl) {\n var event = null;\n try {\n event = new window.Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n event.track = track;\n videoEl.dispatchEvent(event);\n}\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\n/***/ }),\n/* 27 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return fixLineBreaks; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__vttcue__ = __webpack_require__(63);\n/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716\n */\n\n\n\nvar StringDecoder = function StringDecoder() {\n return {\n decode: function decode(data) {\n if (!data) {\n return '';\n }\n\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\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// Try to parse input as a time stamp.\nfunction parseTimeStamp(input) {\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 set(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 get(k, dflt, defaultKey) {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n\n return this.has(k) ? this.values[k] : dflt;\n },\n // Check whether we have a value for a key.\n has: function has(k) {\n return k in this.values;\n },\n // Accept a setting if its one of the given alternatives.\n alt: function alt(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 integer(k, v) {\n if (/^-?\\d+$/.test(v)) {\n // integer\n this.set(k, parseInt(v, 10));\n }\n },\n // Accept a setting if its a valid percentage.\n percent: function percent(k, v) {\n var m = void 0;\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\n var kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n var k = kv[0];\n var v = kv[1];\n callback(k, v);\n }\n}\n\nvar defaults = new __WEBPACK_IMPORTED_MODULE_0__vttcue__[\"a\" /* default */](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\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\n settings.alt(k, vals0, ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\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\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) !== '-->') {\n // (3) next characters must match '-->'\n throw new Error('Malformed time stamp (time stamps must be separated by \\'-->\\'): ' + 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 parse(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\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\n if (buffer[pos] === '\\n') {\n ++pos;\n }\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 = void 0;\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\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\n self.cue = new __WEBPACK_IMPORTED_MODULE_0__vttcue__[\"a\" /* default */](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\n self.cue = null;\n self.state = 'ID';\n continue;\n }\n if (self.cue.text) {\n self.cue.text += '\\n';\n }\n\n self.cue.text += line;\n continue;\n case 'BADCUE':\n // BADCUE\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n self.state = 'ID';\n }\n\n continue;\n }\n }\n } catch (e) {\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\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 flush() {\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\n return this;\n }\n};\n\n\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (VTTParser);\n\n/***/ }),\n/* 28 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit__ = __webpack_require__(5);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_url_toolkit__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__loader_playlist_loader__ = __webpack_require__(16);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__loader_fragment_loader__ = __webpack_require__(31);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__loader_key_loader__ = __webpack_require__(32);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__controller_fragment_tracker__ = __webpack_require__(10);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__controller_stream_controller__ = __webpack_require__(33);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__controller_level_controller__ = __webpack_require__(49);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__controller_id3_track_controller__ = __webpack_require__(50);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__is_supported__ = __webpack_require__(51);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__config__ = __webpack_require__(52);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13_events__ = __webpack_require__(12);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_13_events__);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// polyfill for IE11\n__webpack_require__(72);\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\n\nvar Hls = function () {\n\n /**\n * @type {boolean}\n */\n Hls.isSupported = function isSupported() {\n return Object(__WEBPACK_IMPORTED_MODULE_9__is_supported__[\"a\" /* isSupported */])();\n };\n\n /**\n * @type {HlsEvents}\n */\n\n\n _createClass(Hls, null, [{\n key: 'version',\n\n /**\n * @type {string}\n */\n get: function get() {\n return \"0.10.0\";\n }\n }, {\n key: 'Events',\n get: function get() {\n return __WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */];\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n\n }, {\n key: 'ErrorTypes',\n get: function get() {\n return __WEBPACK_IMPORTED_MODULE_1__errors__[\"b\" /* ErrorTypes */];\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n\n }, {\n key: 'ErrorDetails',\n get: function get() {\n return __WEBPACK_IMPORTED_MODULE_1__errors__[\"a\" /* ErrorDetails */];\n }\n\n /**\n * @type {HlsConfig}\n */\n\n }, {\n key: 'DefaultConfig',\n get: function get() {\n if (!Hls.defaultConfig) {\n return __WEBPACK_IMPORTED_MODULE_11__config__[\"a\" /* hlsDefaultConfig */];\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n ,\n set: function set(defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n\n }]);\n\n function Hls() {\n var _this = this;\n\n var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Hls);\n\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 Object(__WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"a\" /* enableLogs */])(config.debug);\n this.config = config;\n this._autoLevelCapping = -1;\n // observer setup\n var observer = this.observer = new __WEBPACK_IMPORTED_MODULE_13_events___default.a();\n observer.trigger = function trigger(event) {\n for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n data[_key - 1] = arguments[_key];\n }\n\n observer.emit.apply(observer, [event, event].concat(data));\n };\n\n observer.off = function off(event) {\n for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n data[_key2 - 1] = arguments[_key2];\n }\n\n observer.removeListener.apply(observer, [event].concat(data));\n };\n this.on = observer.on.bind(observer);\n this.off = observer.off.bind(observer);\n this.once = observer.once.bind(observer);\n this.trigger = observer.trigger.bind(observer);\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n var abrController = this.abrController = new config.abrController(this);\n\n var bufferController = new config.bufferController(this);\n var capLevelController = new config.capLevelController(this);\n var fpsController = new config.fpsController(this);\n var playListLoader = new __WEBPACK_IMPORTED_MODULE_2__loader_playlist_loader__[\"a\" /* default */](this);\n var fragmentLoader = new __WEBPACK_IMPORTED_MODULE_3__loader_fragment_loader__[\"a\" /* default */](this);\n var keyLoader = new __WEBPACK_IMPORTED_MODULE_4__loader_key_loader__[\"a\" /* default */](this);\n var id3TrackController = new __WEBPACK_IMPORTED_MODULE_8__controller_id3_track_controller__[\"a\" /* default */](this);\n\n // network controllers\n\n /**\n * @member {LevelController} levelController\n */\n var levelController = this.levelController = new __WEBPACK_IMPORTED_MODULE_7__controller_level_controller__[\"a\" /* default */](this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n var fragmentTracker = new __WEBPACK_IMPORTED_MODULE_5__controller_fragment_tracker__[\"b\" /* FragmentTracker */](this);\n\n /**\n * @member {StreamController} streamController\n */\n var streamController = this.streamController = new __WEBPACK_IMPORTED_MODULE_6__controller_stream_controller__[\"a\" /* default */](this, fragmentTracker);\n\n var networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n var Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n var audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n var subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n coreComponents.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n var emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\n }\n\n // optional subtitle controller\n [config.subtitleStreamController, config.timelineController].forEach(function (Controller) {\n if (Controller) {\n coreComponents.push(new Controller(_this));\n }\n });\n\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n\n\n Hls.prototype.destroy = function destroy() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('destroy');\n this.trigger(__WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */].DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(function (component) {\n component.destroy();\n });\n this.url = null;\n this.observer.removeAllListeners();\n this._autoLevelCapping = -1;\n };\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n\n\n Hls.prototype.attachMedia = function attachMedia(media) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('attachMedia');\n this.media = media;\n this.trigger(__WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */].MEDIA_ATTACHING, { media: media });\n };\n\n /**\n * Detach from the media\n */\n\n\n Hls.prototype.detachMedia = function detachMedia() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('detachMedia');\n this.trigger(__WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */].MEDIA_DETACHING);\n this.media = null;\n };\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\n */\n\n\n Hls.prototype.loadSource = function loadSource(url) {\n url = __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default.a.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('loadSource:' + url);\n this.url = url;\n // when attaching to a source URL, trigger a playlist load\n this.trigger(__WEBPACK_IMPORTED_MODULE_12__events__[\"a\" /* default */].MANIFEST_LOADING, { url: url });\n };\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n\n\n Hls.prototype.startLoad = function startLoad() {\n var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;\n\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('startLoad(' + startPosition + ')');\n this.networkControllers.forEach(function (controller) {\n controller.startLoad(startPosition);\n });\n };\n\n /**\n * Stop loading of any stream data.\n */\n\n\n Hls.prototype.stopLoad = function stopLoad() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('stopLoad');\n this.networkControllers.forEach(function (controller) {\n controller.stopLoad();\n });\n };\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n\n\n Hls.prototype.swapAudioCodec = function swapAudioCodec() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n };\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n\n\n Hls.prototype.recoverMediaError = function recoverMediaError() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('recoverMediaError');\n var media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n };\n\n /**\n * @type {QualityLevel[]}\n */\n\n\n _createClass(Hls, [{\n key: 'levels',\n get: function get() {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n\n }, {\n key: 'currentLevel',\n get: function get() {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @type {number} -1 for automatic level selection\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set currentLevel:' + newLevel);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n\n }, {\n key: 'nextLevel',\n get: function get() {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set nextLevel:' + newLevel);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n\n }, {\n key: 'loadLevel',\n get: function get() {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set loadLevel:' + newLevel);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n\n }, {\n key: 'nextLoadLevel',\n get: function get() {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n ,\n set: function set(level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n\n }, {\n key: 'firstLevel',\n get: function get() {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set firstLevel:' + newLevel);\n this.levelController.firstLevel = newLevel;\n }\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\n * (determined from download of first segment)\n * @type {number}\n */\n\n }, {\n key: 'startLevel',\n get: function get() {\n return this.levelController.startLevel;\n }\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\n * (determined from download of first segment)\n * @type {number} newLevel\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set startLevel:' + newLevel);\n var 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\n hls.levelController.startLevel = newLevel;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n\n }, {\n key: 'autoLevelCapping',\n get: function get() {\n return this._autoLevelCapping;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n ,\n set: function set(newLevel) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('set autoLevelCapping:' + newLevel);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n\n }, {\n key: 'autoLevelEnabled',\n get: function get() {\n return this.levelController.manualLevel === -1;\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n\n }, {\n key: 'manualLevel',\n get: function get() {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\n\n }, {\n key: 'minAutoLevel',\n get: function get() {\n var hls = this,\n levels = hls.levels,\n minAutoBitrate = hls.config.minAutoBitrate,\n len = levels ? levels.length : 0;\n for (var i = 0; i < len; i++) {\n var 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 /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\n\n }, {\n key: 'maxAutoLevel',\n get: function get() {\n var hls = this;\n var levels = hls.levels;\n var autoLevelCapping = hls.autoLevelCapping;\n var maxAutoLevel = void 0;\n if (autoLevelCapping === -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\n\n }, {\n key: 'nextAutoLevel',\n get: function get() {\n var 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 /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * 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,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n ,\n set: function set(nextLevel) {\n var hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n\n }, {\n key: 'audioTracks',\n get: function get() {\n var audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n\n }, {\n key: 'audioTrack',\n get: function get() {\n var audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n ,\n set: function set(audioTrackId) {\n var audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n\n }, {\n key: 'liveSyncPosition',\n get: function get() {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n\n }, {\n key: 'subtitleTracks',\n get: function get() {\n var subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n\n }, {\n key: 'subtitleTrack',\n get: function get() {\n var subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type{number}\n */\n ,\n set: function set(subtitleTrackId) {\n var subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n\n }, {\n key: 'subtitleDisplay',\n get: function get() {\n var subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\n */\n ,\n set: function set(value) {\n var subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n }]);\n\n return Hls;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Hls);\n\n/***/ }),\n/* 29 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit__ = __webpack_require__(5);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_url_toolkit__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__fragment__ = __webpack_require__(9);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__level_key__ = __webpack_require__(18);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__ = __webpack_require__(30);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_codecs__ = __webpack_require__(19);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n\n\n\n\n\n\n\n\n\n/**\n * M3U8 parser\n * @module\n */\n\n// https://regex101.com is your friend\nvar MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)/g;\nvar MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nvar LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#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\nvar 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\nvar MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nvar M3U8Parser = function () {\n function M3U8Parser() {\n _classCallCheck(this, M3U8Parser);\n }\n\n M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {\n if (!groups) {\n return null;\n }\n\n var matchingGroup = null;\n\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n if (group.id === mediaGroupId) {\n matchingGroup = group;\n }\n }\n\n return matchingGroup;\n };\n\n M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {\n var result = void 0,\n 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 M3U8Parser.resolve = function resolve(url, baseUrl) {\n return __WEBPACK_IMPORTED_MODULE_0_url_toolkit___default.a.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n };\n\n M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {\n var levels = [],\n result = void 0;\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n function setCodecs(codecs, level) {\n ['video', 'audio'].forEach(function (type) {\n var filtered = codecs.filter(function (codec) {\n return Object(__WEBPACK_IMPORTED_MODULE_5__utils_codecs__[\"b\" /* isCodecType */])(codec, type);\n });\n if (filtered.length) {\n var preferred = filtered.filter(function (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(function (codec) {\n return filtered.indexOf(codec) === -1;\n });\n }\n });\n\n level.unknownCodecs = codecs;\n }\n\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n var level = {};\n\n var attrs = level.attrs = new __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](result[1]);\n level.url = M3U8Parser.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 = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n }\n return levels;\n };\n\n M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type) {\n var audioGroups = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];\n\n var result = void 0;\n var medias = [];\n var id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n var media = {};\n var attrs = new __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](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 = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n media.lang = attrs.LANGUAGE;\n if (!media.name) {\n media.name = media.lang;\n }\n\n if (audioGroups.length) {\n var groupCodec = M3U8Parser.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 M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {\n var currentSN = 0,\n totalduration = 0,\n level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 },\n levelkey = new __WEBPACK_IMPORTED_MODULE_2__level_key__[\"a\" /* default */](),\n cc = 0,\n prevFrag = null,\n frag = new __WEBPACK_IMPORTED_MODULE_1__fragment__[\"a\" /* default */](),\n result = void 0,\n i = void 0;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n var duration = result[1];\n if (duration) {\n // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n var title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);\n } else if (result[3]) {\n // url\n if (!isNaN(frag.duration)) {\n var 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.urlId = levelUrlId;\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 if (level.programDateTime) {\n if (prevFrag) {\n if (frag.rawProgramDateTime) {\n // PDT discontinuity found\n frag.pdt = Date.parse(frag.rawProgramDateTime);\n } else {\n // Contiguous fragment\n frag.pdt = prevFrag.pdt + prevFrag.duration * 1000;\n }\n } else {\n // First fragment\n frag.pdt = Date.parse(level.programDateTime);\n }\n frag.endPdt = frag.pdt + frag.duration * 1000;\n }\n\n level.fragments.push(frag);\n prevFrag = frag;\n totalduration += frag.duration;\n\n frag = new __WEBPACK_IMPORTED_MODULE_1__fragment__[\"a\" /* default */]();\n }\n } else if (result[4]) {\n // X-BYTERANGE\n frag.rawByteRange = (' ' + result[4]).slice(1);\n if (prevFrag) {\n var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;\n if (lastByteRangeEndOffset) {\n frag.lastByteRangeEndOffset = lastByteRangeEndOffset;\n }\n }\n } else if (result[5]) {\n // 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 var value1 = (' ' + result[i + 1]).slice(1);\n var 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 __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](decryptparams);\n var decryptmethod = keyAttrs.enumeratedString('METHOD'),\n decrypturi = keyAttrs.URI,\n decryptiv = keyAttrs.hexadecimalInteger('IV');\n if (decryptmethod) {\n levelkey = new __WEBPACK_IMPORTED_MODULE_2__level_key__[\"a\" /* default */]();\n if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].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 var startParams = value1;\n var startAttrs = new __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](startParams);\n var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n // TIME-OFFSET can be 0\n if (!isNaN(startTimeOffset)) {\n level.startTimeOffset = startTimeOffset;\n }\n\n break;\n case 'MAP':\n var mapAttrs = new __WEBPACK_IMPORTED_MODULE_3__utils_attr_list__[\"a\" /* default */](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 __WEBPACK_IMPORTED_MODULE_1__fragment__[\"a\" /* default */]();\n break;\n default:\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every(function (frag) {\n return MP4_REGEX_SUFFIX.test(frag.relurl);\n })) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new __WEBPACK_IMPORTED_MODULE_1__fragment__[\"a\" /* default */]();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n return level;\n };\n\n return M3U8Parser;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (M3U8Parser);\n\n/***/ }),\n/* 30 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nvar ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\n\nvar AttrList = function () {\n function AttrList(attrs) {\n _classCallCheck(this, AttrList);\n\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (var attr in attrs) {\n if (attrs.hasOwnProperty(attr)) {\n this[attr] = attrs[attr];\n }\n }\n }\n\n AttrList.prototype.decimalInteger = function decimalInteger(attrName) {\n var intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n };\n\n AttrList.prototype.hexadecimalInteger = function hexadecimalInteger(attrName) {\n if (this[attrName]) {\n var stringValue = (this[attrName] || '0x').slice(2);\n stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;\n\n var value = new Uint8Array(stringValue.length / 2);\n for (var i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n };\n\n AttrList.prototype.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {\n var intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n };\n\n AttrList.prototype.decimalFloatingPoint = function decimalFloatingPoint(attrName) {\n return parseFloat(this[attrName]);\n };\n\n AttrList.prototype.enumeratedString = function enumeratedString(attrName) {\n return this[attrName];\n };\n\n AttrList.prototype.decimalResolution = function decimalResolution(attrName) {\n var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n };\n\n AttrList.parseAttrList = function parseAttrList(input) {\n var match = void 0,\n attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n var value = match[2],\n quote = '\"';\n\n if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {\n value = value.slice(1, -1);\n }\n\n attrs[match[1]] = value;\n }\n return attrs;\n };\n\n return AttrList;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AttrList);\n\n/***/ }),\n/* 31 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Fragment Loader\n*/\n\n\n\n\n\n\nvar FragmentLoader = function (_EventHandler) {\n _inherits(FragmentLoader, _EventHandler);\n\n function FragmentLoader(hls) {\n _classCallCheck(this, FragmentLoader);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADING));\n\n _this.loaders = {};\n return _this;\n }\n\n FragmentLoader.prototype.destroy = function destroy() {\n var loaders = this.loaders;\n for (var loaderName in loaders) {\n var loader = loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n\n _EventHandler.prototype.destroy.call(this);\n };\n\n FragmentLoader.prototype.onFragLoading = function onFragLoading(data) {\n var frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n var loader = loaders[type];\n if (loader) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].warn('abort previous fragment loader for type: ' + type);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n var loaderContext = void 0,\n loaderConfig = void 0,\n loaderCallbacks = void 0;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n var start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (!isNaN(start) && !isNaN(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\n loader.load(loaderContext, loaderConfig, loaderCallbacks);\n };\n\n FragmentLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {\n var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n\n var payload = response.data,\n frag = context.frag;\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });\n };\n\n FragmentLoader.prototype.loaderror = function loaderror(response, context) {\n var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n var loader = context.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR, details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });\n };\n\n FragmentLoader.prototype.loadtimeout = function loadtimeout(stats, context) {\n var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n var loader = context.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR, details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });\n };\n\n // data will be used for progressive parsing\n\n\n FragmentLoader.prototype.loadprogress = function loadprogress(stats, context, data) {\n var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n // jshint ignore:line\n var frag = context.frag;\n frag.loaded = stats.loaded;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });\n };\n\n return FragmentLoader;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (FragmentLoader);\n\n/***/ }),\n/* 32 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Decrypt key Loader\n*/\n\n\n\n\n\n\nvar KeyLoader = function (_EventHandler) {\n _inherits(KeyLoader, _EventHandler);\n\n function KeyLoader(hls) {\n _classCallCheck(this, KeyLoader);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].KEY_LOADING));\n\n _this.loaders = {};\n _this.decryptkey = null;\n _this.decrypturl = null;\n return _this;\n }\n\n KeyLoader.prototype.destroy = function destroy() {\n for (var loaderName in this.loaders) {\n var loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n KeyLoader.prototype.onKeyLoading = function onKeyLoading(data) {\n var 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 var config = this.hls.config;\n\n if (loader) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* 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 var loaderContext = void 0,\n loaderConfig = void 0,\n loaderCallbacks = void 0;\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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].KEY_LOADED, { frag: frag });\n }\n };\n\n KeyLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {\n var 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].KEY_LOADED, { frag: frag });\n };\n\n KeyLoader.prototype.loaderror = function loaderror(response, context) {\n var frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR, details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });\n };\n\n KeyLoader.prototype.loadtimeout = function loadtimeout(stats, context) {\n var frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[context.type] = undefined;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR, details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_TIMEOUT, fatal: false, frag: frag });\n };\n\n return KeyLoader;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (KeyLoader);\n\n/***/ }),\n/* 33 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export State */\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__ = __webpack_require__(6);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__ = __webpack_require__(11);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__demux_demuxer__ = __webpack_require__(20);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__fragment_tracker__ = __webpack_require__(10);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__loader_fragment__ = __webpack_require__(9);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__loader_playlist_loader__ = __webpack_require__(16);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__level_helper__ = __webpack_require__(15);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_time_ranges__ = __webpack_require__(24);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_discontinuities__ = __webpack_require__(25);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__task_loop__ = __webpack_require__(8);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__fragment_finders__ = __webpack_require__(48);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Stream Controller\n*/\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar 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\nvar StreamController = function (_TaskLoop) {\n _inherits(StreamController, _TaskLoop);\n\n function StreamController(hls, fragmentTracker) {\n _classCallCheck(this, StreamController);\n\n var _this = _possibleConstructorReturn(this, _TaskLoop.call(this, hls, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MEDIA_ATTACHED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MANIFEST_LOADING, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MANIFEST_PARSED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].LEVEL_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].KEY_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSING_DATA, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHING, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_CREATED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_APPENDED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_FLUSHED));\n\n _this.fragmentTracker = fragmentTracker;\n _this.config = hls.config;\n _this.audioCodecSwap = false;\n _this._state = State.STOPPED;\n _this.stallReported = false;\n return _this;\n }\n\n StreamController.prototype.onHandlerDestroying = function onHandlerDestroying() {\n this.stopLoad();\n _TaskLoop.prototype.onHandlerDestroying.call(this);\n };\n\n StreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n _TaskLoop.prototype.onHandlerDestroyed.call(this);\n };\n\n StreamController.prototype.startLoad = function startLoad(startPosition) {\n if (this.levels) {\n var lastCurrentTime = this.lastCurrentTime,\n hls = this.hls;\n this.stopLoad();\n this.setInterval(100);\n this.level = -1;\n this.fragLoadError = 0;\n if (!this.startFragRequested) {\n // determine load level\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 StreamController.prototype.stopLoad = function stopLoad() {\n var frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.clearInterval();\n this.state = State.STOPPED;\n this.forceStartLoad = false;\n };\n\n StreamController.prototype.doTick = function doTick() {\n switch (this.state) {\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\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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\n\n StreamController.prototype._doTickIdle = function _doTickIdle() {\n var hls = this.hls,\n config = hls.config,\n media = this.media;\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 || !media && (this.startFragRequested || !config.startFragPrefetch)) {\n return;\n }\n\n // if we have not yet loaded any fragment, start loading from start position\n var pos = void 0;\n if (this.loadedmetadata) {\n pos = media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n\n // determine next load level\n var level = hls.nextLoadLevel,\n levelInfo = this.levels[level];\n\n if (!levelInfo) {\n return;\n }\n\n var levelBitrate = levelInfo.bitrate,\n maxBufLen = void 0;\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\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 var bufferInfo = __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 var 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 (!levelDetails || 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 var 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 var 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 var data = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 StreamController.prototype._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {\n var 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 var start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n bufferEnd = bufferInfo.end,\n frag = void 0;\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 var initialLiveManifestSize = this.config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 } 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\n if (frag) {\n if (frag.encrypted) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);\n this._loadKey(frag);\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));\n this._loadFragment(frag);\n }\n }\n };\n\n StreamController.prototype._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {\n var config = this.hls.config,\n media = this.media;\n\n var frag = void 0;\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 var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n\n if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {\n var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n __WEBPACK_IMPORTED_MODULE_10__utils_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));\n bufferEnd = liveSyncPosition;\n if (media && media.readyState && media.duration > liveSyncPosition) {\n media.currentTime = liveSyncPosition;\n }\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 if (!levelDetails.programDateTime) {\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n var targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n var fragNext = fragments[targetSN - levelDetails.startSN];\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 = __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__[\"a\" /* default */].search(fragments, function (frag) {\n return fragPrevious.cc - frag.cc;\n });\n if (frag) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist, switching playlist, load frag with same CC: ' + frag.sn);\n }\n }\n } else {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n frag = Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"b\" /* findFragmentByPDT */])(fragments, fragPrevious.endPdt + 1);\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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);\n }\n }\n return frag;\n };\n\n StreamController.prototype._findFragment = function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {\n var config = this.hls.config;\n var fragBySN = function fragBySN() {\n return Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"c\" /* findFragmentBySN */])(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n };\n var frag = void 0;\n var foundFrag = void 0;\n\n if (bufferEnd < end) {\n if (!levelDetails.programDateTime) {\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"c\" /* findFragmentBySN */])(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n } else {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"b\" /* findFragmentByPDT */])(fragments, Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"a\" /* calculateNextPDT */])(start, bufferEnd, levelDetails));\n if (!foundFrag || Object(__WEBPACK_IMPORTED_MODULE_13__fragment_finders__[\"d\" /* fragmentWithinToleranceTest */])(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) {\n // Fall back to SN order if finding by PDT returns a frag which won't fit within the stream\n // fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN');\n foundFrag = fragBySN();\n }\n }\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen - 1];\n }\n if (foundFrag) {\n frag = foundFrag;\n var curSNIdx = frag.sn - levelDetails.startSN;\n var sameLevel = fragPrevious && frag.level === fragPrevious.level;\n var prevFrag = fragments[curSNIdx - 1];\n var 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 var 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 __WEBPACK_IMPORTED_MODULE_10__utils_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');\n } else {\n frag = nextFrag;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');\n frag.dropped = 0;\n if (prevFrag) {\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 StreamController.prototype._loadKey = function _loadKey(frag) {\n this.state = State.KEY_LOADING;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].KEY_LOADING, { frag: frag });\n };\n\n StreamController.prototype._loadFragment = function _loadFragment(frag) {\n // Check if fragment is not loaded\n var fragState = this.fragmentTracker.getState(frag);\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\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === __WEBPACK_IMPORTED_MODULE_4__fragment_tracker__[\"a\" /* FragmentState */].NOT_LOADED || fragState === __WEBPACK_IMPORTED_MODULE_4__fragment_tracker__[\"a\" /* FragmentState */].PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 __WEBPACK_IMPORTED_MODULE_2__demux_demuxer__[\"a\" /* default */](this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === __WEBPACK_IMPORTED_MODULE_4__fragment_tracker__[\"a\" /* FragmentState */].APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\n }\n };\n\n StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) {\n return this.fragmentTracker.getBufferedFrag(position, __WEBPACK_IMPORTED_MODULE_6__loader_playlist_loader__[\"a\" /* default */].LevelType.MAIN);\n };\n\n StreamController.prototype.followingBufferedFrag = function 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 StreamController.prototype._checkFragmentChanged = function _checkFragmentChanged() {\n var fragPlayingCurrent = void 0,\n currentTime = void 0,\n 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 > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\n\n if (__WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getBufferedFrag(currentTime);\n } else if (__WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_CHANGED, { frag: fragPlaying });\n var fragPlayingLevel = fragPlaying.level;\n if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].LEVEL_SWITCHED, { level: fragPlayingLevel });\n }\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\n\n StreamController.prototype.immediateLevelSwitch = function immediateLevelSwitch() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('immediateLevelSwitch');\n if (!this.immediateSwitch) {\n this.immediateSwitch = true;\n var media = this.media,\n previouslyPaused = void 0;\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\n this.fragCurrent = null;\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\n\n StreamController.prototype.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() {\n var media = this.media;\n if (media && media.buffered.length) {\n this.immediateSwitch = false;\n if (__WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* 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 /**\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\n\n StreamController.prototype.nextLevelSwitch = function nextLevelSwitch() {\n var media = this.media;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media && media.readyState) {\n var fetchdelay = void 0,\n fragPlayingCurrent = void 0,\n nextBufferedFrag = void 0;\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,\n nextLevel = this.levels[nextLevelId],\n 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\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 StreamController.prototype.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {\n this.state = State.BUFFER_FLUSHING;\n var 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\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_FLUSHING, flushScope);\n };\n\n StreamController.prototype.onMediaAttached = function 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 var config = this.config;\n if (this.levels && config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n };\n\n StreamController.prototype.onMediaDetaching = function onMediaDetaching() {\n var media = this.media;\n if (media && media.ended) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment backtracked flag\n var levels = this.levels;\n if (levels) {\n levels.forEach(function (level) {\n if (level.details) {\n level.details.fragments.forEach(function (fragment) {\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 StreamController.prototype.onMediaSeeking = function onMediaSeeking() {\n var media = this.media,\n currentTime = media ? media.currentTime : undefined,\n config = this.config;\n if (!isNaN(currentTime)) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('media seeking to ' + currentTime.toFixed(3));\n }\n\n var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n var bufferInfo = __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(mediaBuffer, currentTime, this.config.maxBufferHole);\n if (this.state === State.FRAG_LOADING) {\n var 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 var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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\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\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\n // tick to speed up processing\n this.tick();\n };\n\n StreamController.prototype.onMediaSeeked = function onMediaSeeked() {\n var media = this.media,\n currentTime = media ? media.currentTime : undefined;\n if (!isNaN(currentTime)) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('media seeked to ' + currentTime.toFixed(3));\n }\n\n // tick to speed up FRAGMENT_PLAYING triggering\n this.tick();\n };\n\n StreamController.prototype.onMediaEnded = function onMediaEnded() {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('media ended');\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n };\n\n StreamController.prototype.onManifestLoading = function onManifestLoading() {\n // reset buffer on manifest loading\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('trigger BUFFER_RESET');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n };\n\n StreamController.prototype.onManifestParsed = function onManifestParsed(data) {\n var aac = false,\n heaac = false,\n codec = void 0;\n data.levels.forEach(function (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\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = aac && heaac;\n if (this.audioCodecSwitch) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');\n }\n\n this.levels = data.levels;\n this.startFragRequested = false;\n var config = this.config;\n if (config.autoStartLoad || this.forceStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n };\n\n StreamController.prototype.onLevelLoaded = function onLevelLoaded(data) {\n var newDetails = data.details;\n var newLevelId = data.level;\n var lastLevel = this.levels[this.levelLastLoaded];\n var curLevel = this.levels[newLevelId];\n var duration = newDetails.totalduration;\n var sliding = 0;\n\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_7__level_helper__[\"b\" /* mergeDetails */](curDetails, newDetails);\n sliding = newDetails.fragments[0].start;\n this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown && !isNaN(sliding)) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist sliding:' + sliding.toFixed(3));\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist - outdated PTS, unknown sliding');\n Object(__WEBPACK_IMPORTED_MODULE_11__utils_discontinuities__[\"a\" /* alignDiscontinuities */])(this.fragPrevious, lastLevel, newDetails);\n }\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('live playlist - first load, unknown sliding');\n newDetails.PTSKnown = false;\n Object(__WEBPACK_IMPORTED_MODULE_11__utils_discontinuities__[\"a\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 var startTimeOffset = newDetails.startTimeOffset;\n if (!isNaN(startTimeOffset)) {\n if (startTimeOffset < 0) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');\n startTimeOffset = sliding + duration + startTimeOffset;\n }\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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\n // trigger handler right now\n this.tick();\n };\n\n StreamController.prototype.onKeyLoaded = function onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n };\n\n StreamController.prototype.onFragLoaded = function onFragLoaded(data) {\n var fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {\n var stats = data.stats;\n var currentLevel = this.levels[fragCurrent.level];\n var details = currentLevel.details;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 = window.performance.now();\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 = window.performance.now();\n details.initSegment.data = data.payload;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 var duration = details.totalduration,\n level = fragCurrent.level,\n sn = fragCurrent.sn,\n audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('swapping playlist audio codec');\n if (audioCodec === undefined) {\n audioCodec = this.lastAudioCodec;\n }\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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc);\n var demuxer = this.demuxer;\n if (!demuxer) {\n demuxer = this.demuxer = new __WEBPACK_IMPORTED_MODULE_2__demux_demuxer__[\"a\" /* default */](this.hls, 'main');\n }\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 var media = this.media;\n var mediaSeeking = media && media.seeking;\n var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);\n var 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 StreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) {\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n\n if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {\n var tracks = data.tracks,\n trackName = void 0,\n track = void 0;\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\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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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') {\n // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });\n }\n }\n // trigger handler right now\n this.tick();\n }\n };\n\n StreamController.prototype.onFragParsingData = function onFragParsingData(data) {\n var _this2 = this;\n\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n 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\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 if (data.hasAudio === true) {\n frag.addElementaryStream(__WEBPACK_IMPORTED_MODULE_5__loader_fragment__[\"a\" /* default */].ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(__WEBPACK_IMPORTED_MODULE_5__loader_fragment__[\"a\" /* default */].ElementaryStreamTypes.VIDEO);\n }\n\n __WEBPACK_IMPORTED_MODULE_10__utils_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));\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 var levelDetails = level.details;\n if (levelDetails && frag.sn === levelDetails.startSN) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('missing video frame(s) on first frag, appending with gap', frag.sn);\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('missing video frame(s), backtracking fragment', frag.sn);\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 this.fragmentTracker.removeFragment(frag);\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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('Already backtracked on this fragment, appending with the gap', frag.sn);\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 = __WEBPACK_IMPORTED_MODULE_7__level_helper__[\"c\" /* updateFragPTSDTS */](level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),\n hls = this.hls;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });\n // has remuxer dropped video frames located before first keyframe ?\n [data.data1, data.data2].forEach(function (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 && _this2.state === State.PARSING) {\n _this2.appended = true;\n // arm pending Buffering flag before appending a segment\n _this2.pendingBuffering = true;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 StreamController.prototype.onFragParsed = function onFragParsed(data) {\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {\n this.stats.tparsed = window.performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n };\n\n StreamController.prototype.onAudioTrackSwitching = function 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('switching on main audio, use media.buffered to schedule main fragment loading');\n this.mediaBuffer = this.media;\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 var hls = this.hls;\n // switching to main audio, flush all audio and trigger track switched\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId });\n this.altAudio = false;\n }\n };\n\n StreamController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) {\n var trackId = data.id,\n altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 StreamController.prototype.onBufferCreated = function onBufferCreated(data) {\n var tracks = data.tracks,\n mediaTrack = void 0,\n name = void 0,\n alternate = false;\n for (var type in tracks) {\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 StreamController.prototype.onBufferAppended = function onBufferAppended(data) {\n if (data.parent === 'main') {\n var 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 StreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n var frag = this.fragCurrent;\n if (frag) {\n var media = this.mediaBuffer ? this.mediaBuffer : this.media;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('main buffered : ' + __WEBPACK_IMPORTED_MODULE_8__utils_time_ranges__[\"a\" /* default */].toString(media.buffered));\n this.fragPrevious = frag;\n var stats = this.stats;\n stats.tbuffered = window.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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });\n this.state = State.IDLE;\n }\n this.tick();\n }\n };\n\n StreamController.prototype.onError = function onError(data) {\n var 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\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n var mediaBuffered = !!this.media && __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].isBuffered(this.media, this.media.currentTime) && __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].isBuffered(this.media, this.media.currentTime + 0.5);\n\n switch (data.details) {\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* 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 var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('mediaController: frag loading failed, retry in ' + delay + ' ms');\n this.retryDate = window.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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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 StreamController.prototype._reduceMaxBufferLength = function _reduceMaxBufferLength(minLength) {\n var 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 __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's');\n return true;\n }\n return false;\n };\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n\n\n StreamController.prototype._checkBuffer = function _checkBuffer() {\n var config = this.config,\n media = this.media;\n\n var stallDebounceInterval = 1000;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n var currentTime = media.currentTime;\n var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n var buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n var expectedPlaying = !(media.paused && media.readyState > 1 || // not playing when media is paused and sufficiently buffered\n media.ended || // not playing when media is ended\n media.buffered.length === 0); // not playing if nothing buffered\n var tnow = window.performance.now();\n\n if (currentTime !== this.lastCurrentTime) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(tnow - this.stalled) + 'ms');\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n } else if (expectedPlaying) {\n // The playhead isn't moving but it should be\n // Allow some slack time to for small stalls to resolve themselves\n var stalledDuration = tnow - this.stalled;\n var bufferInfo = __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(media, currentTime, config.maxBufferHole);\n if (!this.stalled) {\n this.stalled = tnow;\n return;\n } else if (stalledDuration >= stallDebounceInterval) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n this._tryFixBufferStall(bufferInfo, stalledDuration);\n }\n }\n };\n\n StreamController.prototype.onFragLoadEmergencyAborted = function 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 StreamController.prototype.onBufferFlushed = function 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 var media = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n this.fragmentTracker.detectEvictedFragments(__WEBPACK_IMPORTED_MODULE_5__loader_fragment__[\"a\" /* default */].ElementaryStreamTypes.VIDEO, media.buffered);\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 StreamController.prototype.swapAudioCodec = function swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n };\n\n StreamController.prototype.computeLivePosition = function computeLivePosition(sliding, levelDetails) {\n var 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 /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDuration - The amount of time Hls.js has been stalling for.\n * @private\n */\n\n\n StreamController.prototype._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDuration) {\n var config = this.config,\n media = this.media;\n\n var currentTime = media.currentTime;\n var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end\n\n var partial = this.fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n this._trySkipBufferHole(partial);\n }\n\n if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n };\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n\n\n StreamController.prototype._reportStall = function _reportStall(bufferLen) {\n var hls = this.hls,\n media = this.media,\n stallReported = this.stallReported;\n\n if (!stallReported) {\n // Report stalled error once\n this.stallReported = true;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('Playback stalling at @' + media.currentTime + ' due to low buffer');\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_9__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n };\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n\n\n StreamController.prototype._trySkipBufferHole = function _trySkipBufferHole(partial) {\n var hls = this.hls,\n media = this.media;\n\n var currentTime = media.currentTime;\n var lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (var i = 0; i < media.buffered.length; i++) {\n var startTime = media.buffered.start(i);\n if (currentTime >= lastEndTime && currentTime < startTime) {\n media.currentTime = Math.max(startTime, media.currentTime + 0.1);\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].warn('skipping hole, adjusting currentTime from ' + currentTime + ' to ' + media.currentTime);\n this.stalled = null;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_9__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: 'fragment loaded with buffer holes, seeking from ' + currentTime + ' to ' + media.currentTime,\n frag: partial\n });\n return;\n }\n lastEndTime = media.buffered.end(i);\n }\n };\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n\n\n StreamController.prototype._tryNudgeBuffer = function _tryNudgeBuffer() {\n var config = this.config,\n hls = this.hls,\n media = this.media;\n\n var currentTime = media.currentTime;\n var nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n var targetTime = currentTime + nudgeRetry * config.nudgeOffset;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_9__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_9__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_9__errors__[\"a\" /* ErrorDetails */].BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n };\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n\n\n StreamController.prototype._seekToStartPos = function _seekToStartPos() {\n var media = this.media;\n\n var currentTime = media.currentTime;\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 var startPosition = media.seeking ? currentTime : this.startPosition;\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition) {\n // if startPosition not buffered, let's seek to buffered.start(0)\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition + ' from current time ' + currentTime + ' ');\n media.currentTime = startPosition;\n }\n };\n\n _createClass(StreamController, [{\n key: 'state',\n set: function set(nextState) {\n if (this.state !== nextState) {\n var previousState = this.state;\n this._state = nextState;\n __WEBPACK_IMPORTED_MODULE_10__utils_logger__[\"b\" /* logger */].log('main stream:' + previousState + '->' + nextState);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });\n }\n },\n get: function get() {\n return this._state;\n }\n }, {\n key: 'currentLevel',\n get: function get() {\n var media = this.media;\n if (media) {\n var frag = this.getBufferedFrag(media.currentTime);\n if (frag) {\n return frag.level;\n }\n }\n return -1;\n }\n }, {\n key: 'nextBufferedFrag',\n get: function get() {\n var 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 key: 'nextLevel',\n get: function get() {\n var frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n } else {\n return -1;\n }\n }\n }, {\n key: 'liveSyncPosition',\n get: function get() {\n return this._liveSyncPosition;\n },\n set: function set(value) {\n this._liveSyncPosition = value;\n }\n }]);\n\n return StreamController;\n}(__WEBPACK_IMPORTED_MODULE_12__task_loop__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (StreamController);\n\n/***/ }),\n/* 34 */\n/***/ (function(module, exports, __webpack_require__) {\n\nfunction 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\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\((\\/\\\\*.*?\\\\*\\/)?\\s?.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_require__.m\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\\n'\n })\n\n src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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/* 35 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar AESCrypto = function () {\n function AESCrypto(subtle, iv) {\n _classCallCheck(this, AESCrypto);\n\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n AESCrypto.prototype.decrypt = function decrypt(data, key) {\n return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);\n };\n\n return AESCrypto;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AESCrypto);\n\n/***/ }),\n/* 36 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar FastAESKey = function () {\n function FastAESKey(subtle, key) {\n _classCallCheck(this, FastAESKey);\n\n this.subtle = subtle;\n this.key = key;\n }\n\n FastAESKey.prototype.expandKey = function expandKey() {\n return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);\n };\n\n return FastAESKey;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (FastAESKey);\n\n/***/ }),\n/* 37 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export removePadding */\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n// PKCS7\nfunction removePadding(buffer) {\n var outputBytes = buffer.byteLength;\n var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return buffer.slice(0, outputBytes - paddingBytes);\n } else {\n return buffer;\n }\n}\n\nvar AESDecryptor = function () {\n function AESDecryptor() {\n _classCallCheck(this, AESDecryptor);\n\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\n\n AESDecryptor.prototype.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {\n var view = new DataView(arrayBuffer);\n var newArray = new Uint32Array(4);\n for (var i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n\n return newArray;\n };\n\n AESDecryptor.prototype.initTable = function initTable() {\n var sBox = this.sBox;\n var invSBox = this.invSBox;\n var subMix = this.subMix;\n var subMix0 = subMix[0];\n var subMix1 = subMix[1];\n var subMix2 = subMix[2];\n var subMix3 = subMix[3];\n var invSubMix = this.invSubMix;\n var invSubMix0 = invSubMix[0];\n var invSubMix1 = invSubMix[1];\n var invSubMix2 = invSubMix[2];\n var invSubMix3 = invSubMix[3];\n\n var d = new Uint32Array(256);\n var x = 0;\n var xi = 0;\n var 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 var 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 var x2 = d[x];\n var x4 = d[x2];\n var x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n var 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 AESDecryptor.prototype.expandKey = function expandKey(keyBuffer) {\n // convert keyBuffer to Uint32Array\n var key = this.uint8ArrayToUint32Array_(keyBuffer);\n var sameKey = true;\n var 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 var 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 var ksRows = this.ksRows = (keySize + 6 + 1) * 4;\n var ksRow = void 0;\n var invKsRow = void 0;\n\n var keySchedule = this.keySchedule = new Uint32Array(ksRows);\n var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);\n var sbox = this.sBox;\n var rcon = this.rcon;\n\n var invSubMix = this.invSubMix;\n var invSubMix0 = invSubMix[0];\n var invSubMix1 = invSubMix[1];\n var invSubMix2 = invSubMix[2];\n var invSubMix3 = invSubMix[3];\n\n var prev = void 0;\n var t = void 0;\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\n\n AESDecryptor.prototype.networkToHostOrderSwap = function networkToHostOrderSwap(word) {\n return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;\n };\n\n AESDecryptor.prototype.decrypt = function decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {\n var nRounds = this.keySize + 6;\n var invKeySchedule = this.invKeySchedule;\n var invSBOX = this.invSBox;\n\n var invSubMix = this.invSubMix;\n var invSubMix0 = invSubMix[0];\n var invSubMix1 = invSubMix[1];\n var invSubMix2 = invSubMix[2];\n var invSubMix3 = invSubMix[3];\n\n var initVector = this.uint8ArrayToUint32Array_(aesIV);\n var initVector0 = initVector[0];\n var initVector1 = initVector[1];\n var initVector2 = initVector[2];\n var initVector3 = initVector[3];\n\n var inputInt32 = new Int32Array(inputArrayBuffer);\n var outputInt32 = new Int32Array(inputInt32.length);\n\n var t0 = void 0,\n t1 = void 0,\n t2 = void 0,\n t3 = void 0;\n var s0 = void 0,\n s1 = void 0,\n s2 = void 0,\n s3 = void 0;\n var inputWords0 = void 0,\n inputWords1 = void 0,\n inputWords2 = void 0,\n inputWords3 = void 0;\n\n var ksRow = void 0,\n i = void 0;\n var 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 removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;\n };\n\n AESDecryptor.prototype.destroy = function 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 return AESDecryptor;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AESDecryptor);\n\n/***/ }),\n/* 38 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__adts__ = __webpack_require__(22);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__demux_id3__ = __webpack_require__(7);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * AAC demuxer\n */\n\n\n\n\nvar AACDemuxer = function () {\n function AACDemuxer(observer, remuxer, config) {\n _classCallCheck(this, AACDemuxer);\n\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n AACDemuxer.prototype.resetInitSegment = function 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 AACDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};\n\n AACDemuxer.probe = function probe(data) {\n if (!data) {\n return false;\n }\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 var id3Data = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].getID3Data(data, 0) || [];\n var offset = id3Data.length;\n\n for (var length = data.length; offset < length; offset++) {\n if (__WEBPACK_IMPORTED_MODULE_0__adts__[\"e\" /* probe */](data, offset)) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* 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\n\n AACDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {\n var track = this._audioTrack;\n var id3Data = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].getID3Data(data, 0) || [];\n var timestamp = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].getTimeStamp(id3Data);\n var pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n var frameIndex = 0;\n var stamp = pts;\n var length = data.length;\n var offset = id3Data.length;\n\n var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];\n\n while (offset < length - 1) {\n if (__WEBPACK_IMPORTED_MODULE_0__adts__[\"d\" /* isHeader */](data, offset) && offset + 5 < length) {\n __WEBPACK_IMPORTED_MODULE_0__adts__[\"c\" /* initTrackConfig */](track, this.observer, data, offset, track.manifestCodec);\n var frame = __WEBPACK_IMPORTED_MODULE_0__adts__[\"a\" /* appendFrame */](track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('Unable to parse AAC frame');\n break;\n }\n } else if (__WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].isHeader(data, offset)) {\n id3Data = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].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, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);\n };\n\n AACDemuxer.prototype.destroy = function destroy() {};\n\n return AACDemuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AACDemuxer);\n\n/***/ }),\n/* 39 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__adts__ = __webpack_require__(22);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__mpegaudio__ = __webpack_require__(23);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__exp_golomb__ = __webpack_require__(40);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__sample_aes__ = __webpack_require__(41);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__errors__ = __webpack_require__(2);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n*/\n\n\n\n\n\n\n// import Hex from '../utils/hex';\n\n\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.\nvar RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nvar TSDemuxer = function () {\n function TSDemuxer(observer, remuxer, config, typeSupported) {\n _classCallCheck(this, TSDemuxer);\n\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.remuxer = remuxer;\n this.sampleAes = null;\n }\n\n TSDemuxer.prototype.setDecryptData = function setDecryptData(decryptdata) {\n if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {\n this.sampleAes = new __WEBPACK_IMPORTED_MODULE_4__sample_aes__[\"a\" /* default */](this.observer, this.config, decryptdata, this.discardEPB);\n } else {\n this.sampleAes = null;\n }\n };\n\n TSDemuxer.probe = function probe(data) {\n var syncOffset = TSDemuxer._syncOffset(data);\n if (syncOffset < 0) {\n return false;\n } else {\n if (syncOffset) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?');\n }\n\n return true;\n }\n };\n\n TSDemuxer._syncOffset = function _syncOffset(data) {\n // scan 1000 first bytes\n var scanwindow = Math.min(1000, data.length - 3 * 188);\n var 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\n\n TSDemuxer.createTrack = function createTrack(type, duration) {\n return {\n container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type: 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\n\n TSDemuxer.prototype.resetInitSegment = function 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\n\n TSDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};\n\n // feed incoming data to the front of the parsing pipeline\n\n\n TSDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {\n var start = void 0,\n len = data.length,\n stt = void 0,\n pid = void 0,\n atf = void 0,\n offset = void 0,\n pes = void 0,\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 var 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)) && pes.pts !== undefined) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n parseID3PES(pes);\n }\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\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n var 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\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\n if (unknownPIDs && !pmtParsed) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_6__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* 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)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n\n audioTrack.pesData = null;\n } else {\n if (audioData && audioData.size) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].log('last AAC PES packet truncated,might overlap between fragments');\n }\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)) && pes.pts !== undefined) {\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 TSDemuxer.prototype.decryptAndRemux = function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (audioTrack.samples && audioTrack.isAAC) {\n var 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 TSDemuxer.prototype.decryptAndRemuxAvc = function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (videoTrack.samples) {\n var 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 TSDemuxer.prototype.destroy = function destroy() {\n this._initPTS = this._initDTS = undefined;\n this._duration = 0;\n };\n\n TSDemuxer.prototype._parsePAT = function _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 TSDemuxer.prototype._parsePMT = function _parsePMT(data, offset, mpegSupported, isSampleAes) {\n var sectionLength = void 0,\n tableEnd = void 0,\n programInfoLength = void 0,\n pid = void 0,\n 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:\n // SAMPLE-AES AAC\n if (!isSampleAes) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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\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\n break;\n\n case 0xdb:\n // SAMPLE-AES AVC\n if (!isSampleAes) {\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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\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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].warn('HEVC stream type found, not supported for now');\n break;\n\n default:\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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 TSDemuxer.prototype._parsePES = function _parsePES(stream) {\n var i = 0,\n frag = void 0,\n pesFlags = void 0,\n pesPrefix = void 0,\n pesLen = void 0,\n pesHdrLen = void 0,\n pesData = void 0,\n pesPts = void 0,\n pesDts = void 0,\n payloadStartOffset = void 0,\n 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 var 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\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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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 (var j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n var 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 TSDemuxer.prototype.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n var samples = avcTrack.samples;\n var 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 || avcSample.key === true || 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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n };\n\n TSDemuxer.prototype._parseAVCPES = function _parseAVCPES(pes, last) {\n var _this = this;\n\n // logger.log('parse new PES');\n var track = this._avcTrack,\n units = this._parseAVCNALu(pes.data),\n debug = false,\n expGolombDecoder = void 0,\n avcSample = this.avcSample,\n push = void 0,\n spsfound = false,\n i = void 0,\n pushAccesUnit = this.pushAccesUnit.bind(this),\n createAVCSample = function createAVCSample(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(function (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\n if (debug) {\n avcSample.debug += 'NDR ';\n }\n\n avcSample.frame = true;\n var 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 var sliceType = new __WEBPACK_IMPORTED_MODULE_3__exp_golomb__[\"a\" /* default */](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\n if (debug) {\n avcSample.debug += 'IDR ';\n }\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\n expGolombDecoder = new __WEBPACK_IMPORTED_MODULE_3__exp_golomb__[\"a\" /* default */](_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 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 } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\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\n if (!track.sps) {\n expGolombDecoder = new __WEBPACK_IMPORTED_MODULE_3__exp_golomb__[\"a\" /* default */](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\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\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\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\n break;\n }\n if (avcSample && push) {\n var _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 TSDemuxer.prototype._insertSampleInOrder = function _insertSampleInOrder(arr, data) {\n var len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\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 } else {\n arr.push(data);\n }\n };\n\n TSDemuxer.prototype._getLastNalUnit = function _getLastNalUnit() {\n var avcSample = this.avcSample,\n lastUnit = void 0;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n var track = this._avcTrack,\n samples = track.samples;\n avcSample = samples[samples.length - 1];\n }\n if (avcSample) {\n var units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n };\n\n TSDemuxer.prototype._parseAVCNALu = function _parseAVCNALu(array) {\n var i = 0,\n len = array.byteLength,\n value = void 0,\n overflow = void 0,\n track = this._avcTrack,\n state = track.naluState || 0,\n lastState = state;\n var units = [],\n unit = void 0,\n unitType = void 0,\n lastUnitStart = -1,\n lastUnitType = void 0;\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 var 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 var 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 var _lastUnit = this._getLastNalUnit();\n if (_lastUnit) {\n var _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\n\n TSDemuxer.prototype.discardEPB = function discardEPB(data) {\n var length = data.byteLength,\n EPBPositions = [],\n i = 1,\n newLength = void 0,\n newData = void 0;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 && data[i + 1] === 0 && 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 TSDemuxer.prototype._parseAACPES = function _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 = void 0,\n frameIndex = void 0,\n offset = void 0,\n stamp = void 0,\n len = void 0;\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 (__WEBPACK_IMPORTED_MODULE_0__adts__[\"d\" /* 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 = void 0,\n fatal = void 0;\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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].warn('parsing error:' + reason);\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_6__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: fatal, reason: reason });\n if (fatal) {\n return;\n }\n }\n\n __WEBPACK_IMPORTED_MODULE_0__adts__[\"c\" /* initTrackConfig */](track, this.observer, data, offset, this.audioCodec);\n frameIndex = 0;\n frameDuration = __WEBPACK_IMPORTED_MODULE_0__adts__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* 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 (__WEBPACK_IMPORTED_MODULE_0__adts__[\"d\" /* isHeader */](data, offset) && offset + 5 < len) {\n var frame = __WEBPACK_IMPORTED_MODULE_0__adts__[\"a\" /* 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\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n };\n\n TSDemuxer.prototype._parseMPEGPES = function _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 (__WEBPACK_IMPORTED_MODULE_1__mpegaudio__[\"a\" /* default */].isHeader(data, offset)) {\n var frame = __WEBPACK_IMPORTED_MODULE_1__mpegaudio__[\"a\" /* default */].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 TSDemuxer.prototype._parseID3PES = function _parseID3PES(pes) {\n this._id3Track.samples.push(pes);\n };\n\n return TSDemuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (TSDemuxer);\n\n/***/ }),\n/* 40 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n*/\n\n\n\nvar ExpGolomb = function () {\n function ExpGolomb(data) {\n _classCallCheck(this, ExpGolomb);\n\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\n\n ExpGolomb.prototype.loadWord = function loadWord() {\n var 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\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\n\n ExpGolomb.prototype.skipBits = function skipBits(count) {\n var skipBytes = void 0; // :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\n\n ExpGolomb.prototype.readBits = function readBits(size) {\n var bits = Math.min(this.bitsAvailable, size),\n // :uint\n valu = this.word >>> 32 - bits; // :uint\n if (size > 32) {\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].error('Cannot read more than 32 bits at a time');\n }\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\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\n\n ExpGolomb.prototype.skipLZ = function skipLZ() {\n var leadingZeroCount = void 0; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {\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\n\n ExpGolomb.prototype.skipUEG = function skipUEG() {\n this.skipBits(1 + this.skipLZ());\n };\n\n // ():void\n\n\n ExpGolomb.prototype.skipEG = function skipEG() {\n this.skipBits(1 + this.skipLZ());\n };\n\n // ():uint\n\n\n ExpGolomb.prototype.readUEG = function readUEG() {\n var clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n };\n\n // ():int\n\n\n ExpGolomb.prototype.readEG = function 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\n\n ExpGolomb.prototype.readBoolean = function readBoolean() {\n return this.readBits(1) === 1;\n };\n\n // ():int\n\n\n ExpGolomb.prototype.readUByte = function readUByte() {\n return this.readBits(8);\n };\n\n // ():int\n\n\n ExpGolomb.prototype.readUShort = function readUShort() {\n return this.readBits(16);\n };\n // ():int\n\n\n ExpGolomb.prototype.readUInt = function 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\n\n ExpGolomb.prototype.skipScalingList = function skipScalingList(count) {\n var lastScale = 8,\n nextScale = 8,\n j = void 0,\n deltaScale = void 0;\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\n\n ExpGolomb.prototype.readSPS = function readSPS() {\n var frameCropLeftOffset = 0,\n frameCropRightOffset = 0,\n frameCropTopOffset = 0,\n frameCropBottomOffset = 0,\n profileIdc = void 0,\n profileCompat = void 0,\n levelIdc = void 0,\n numRefFramesInPicOrderCntCycle = void 0,\n picWidthInMbsMinus1 = void 0,\n picHeightInMapUnitsMinus1 = void 0,\n frameMbsOnlyFlag = void 0,\n scalingListCount = void 0,\n i = void 0,\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 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {\n var chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // 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()) {\n // seq_scaling_matrix_present_flag\n scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) {\n // 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();\n } // offset_for_ref_frame[ i ]\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);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) {\n // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n var pixelRatio = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n var aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1:\n pixelRatio = [1, 1];break;\n case 2:\n pixelRatio = [12, 11];break;\n case 3:\n pixelRatio = [10, 11];break;\n case 4:\n pixelRatio = [16, 11];break;\n case 5:\n pixelRatio = [40, 33];break;\n case 6:\n pixelRatio = [24, 11];break;\n case 7:\n pixelRatio = [20, 11];break;\n case 8:\n pixelRatio = [32, 11];break;\n case 9:\n pixelRatio = [80, 33];break;\n case 10:\n pixelRatio = [18, 11];break;\n case 11:\n pixelRatio = [15, 11];break;\n case 12:\n pixelRatio = [64, 33];break;\n case 13:\n pixelRatio = [160, 99];break;\n case 14:\n pixelRatio = [4, 3];break;\n case 15:\n pixelRatio = [3, 2];break;\n case 16:\n pixelRatio = [2, 1];break;\n case 255:\n {\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 ExpGolomb.prototype.readSliceType = function 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 return ExpGolomb;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (ExpGolomb);\n\n/***/ }),\n/* 41 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__crypt_decrypter__ = __webpack_require__(13);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * SAMPLE-AES decrypter\n*/\n\n\n\nvar SampleAesDecrypter = function () {\n function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {\n _classCallCheck(this, SampleAesDecrypter);\n\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new __WEBPACK_IMPORTED_MODULE_0__crypt_decrypter__[\"a\" /* default */](observer, config, { removePKCS7Padding: false });\n }\n\n SampleAesDecrypter.prototype.decryptBuffer = function 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\n\n SampleAesDecrypter.prototype.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {\n var curUnit = samples[sampleIndex].unit;\n var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);\n var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);\n\n var 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 SampleAesDecrypter.prototype.decryptAacSamples = function 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 var 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\n\n SampleAesDecrypter.prototype.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {\n var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n var encryptedData = new Int8Array(encryptedDataLen);\n var outputPos = 0;\n for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {\n encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return encryptedData;\n };\n\n SampleAesDecrypter.prototype.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n var inputPos = 0;\n for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {\n decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return decodedData;\n };\n\n SampleAesDecrypter.prototype.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {\n var decodedData = this.discardEPB(curUnit.data);\n var encryptedData = this.getAvcEncryptedData(decodedData);\n var 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 SampleAesDecrypter.prototype.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {\n for (;; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n var curUnits = samples[sampleIndex].units;\n for (;; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n var curUnit = curUnits[unitIndex];\n if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {\n continue;\n }\n\n var 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 return SampleAesDecrypter;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (SampleAesDecrypter);\n\n/***/ }),\n/* 42 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demux_id3__ = __webpack_require__(7);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__mpegaudio__ = __webpack_require__(23);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * MP3 demuxer\n */\n\n\n\n\nvar MP3Demuxer = function () {\n function MP3Demuxer(observer, remuxer, config) {\n _classCallCheck(this, MP3Demuxer);\n\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n MP3Demuxer.prototype.resetInitSegment = function 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 MP3Demuxer.prototype.resetTimeStamp = function resetTimeStamp() {};\n\n MP3Demuxer.probe = function probe(data) {\n // check if data contains ID3 timestamp and MPEG sync word\n var offset = void 0,\n length = void 0;\n var id3Data = __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].getID3Data(data, 0);\n if (id3Data && __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].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 (__WEBPACK_IMPORTED_MODULE_2__mpegaudio__[\"a\" /* default */].probe(data, offset)) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* 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\n\n MP3Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {\n var id3Data = __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].getID3Data(data, 0);\n var timestamp = __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].getTimeStamp(id3Data);\n var pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n var offset = id3Data.length;\n var length = data.length;\n var frameIndex = 0,\n stamp = 0;\n var track = this._audioTrack;\n\n var id3Samples = [{ pts: pts, dts: pts, data: id3Data }];\n\n while (offset < length) {\n if (__WEBPACK_IMPORTED_MODULE_2__mpegaudio__[\"a\" /* default */].isHeader(data, offset)) {\n var frame = __WEBPACK_IMPORTED_MODULE_2__mpegaudio__[\"a\" /* default */].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 (__WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].isHeader(data, offset)) {\n id3Data = __WEBPACK_IMPORTED_MODULE_0__demux_id3__[\"a\" /* default */].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, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);\n };\n\n MP3Demuxer.prototype.destroy = function destroy() {};\n\n return MP3Demuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (MP3Demuxer);\n\n/***/ }),\n/* 43 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__aac_helper__ = __webpack_require__(44);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__mp4_generator__ = __webpack_require__(45);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * fMP4 remuxer\n*/\n\n\n\n\n\n\n\n\n\n// 10 seconds\nvar MAX_SILENT_FRAME_DURATION = 10 * 1000;\n\nvar MP4Remuxer = function () {\n function MP4Remuxer(observer, config, typeSupported, vendor) {\n _classCallCheck(this, MP4Remuxer);\n\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n var userAgent = navigator.userAgent;\n this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');\n this.ISGenerated = false;\n }\n\n MP4Remuxer.prototype.destroy = function destroy() {};\n\n MP4Remuxer.prototype.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {\n this._initPTS = this._initDTS = defaultTimeStamp;\n };\n\n MP4Remuxer.prototype.resetInitSegment = function resetInitSegment() {\n this.ISGenerated = false;\n };\n\n MP4Remuxer.prototype.remux = function 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 var nbAudioSamples = audioTrack.samples.length;\n var nbVideoSamples = videoTrack.samples.length;\n var audioTimeOffset = timeOffset;\n var 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 var 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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('regenerate InitSegment as audio detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n var audioTrackLength = void 0;\n if (audioData) {\n audioTrackLength = audioData.endPTS - audioData.startPTS;\n }\n\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.timescale) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSED);\n };\n\n MP4Remuxer.prototype.generateIS = function 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 = void 0,\n initDTS = void 0;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('audio sampling rate : ' + audioTrack.samplerate);\n if (!audioTrack.isAAC) {\n if (typeSupported.mpeg) {\n // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) {\n // 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() : __WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].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 var inputTimeScale = videoTrack.inputTimeScale;\n videoTrack.timescale = inputTimeScale;\n tracks.video = {\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: __WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].INIT_PTS_FOUND, { initPTS: initPTS });\n }\n }\n\n if (Object.keys(tracks).length) {\n observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });\n }\n };\n\n MP4Remuxer.prototype.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {\n var offset = 8,\n timeScale = track.timescale,\n mp4SampleDuration = void 0,\n mdat = void 0,\n moof = void 0,\n firstPTS = void 0,\n firstDTS = void 0,\n nextDTS = void 0,\n lastPTS = void 0,\n lastDTS = void 0,\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 var nextAvcDts = this.nextAvcDts;\n\n var isSafari = this.isSafari;\n\n if (nbSamples === 0) {\n return;\n }\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 && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initDTS) < timeScale / 5);\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 var deltadts = a.dts - b.dts;\n var deltapts = a.pts - b.pts;\n return deltadts || deltapts || a.id - b.id;\n });\n\n // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)\n var PTSDTSshift = inputSamples.reduce(function (prev, curr) {\n return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);\n }, 0);\n if (PTSDTSshift < 0) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');\n for (var 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 var 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 var 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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('AVC:' + delta + ' ms hole between fragments detected,filling it');\n } else if (delta < -1) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log('AVC:' + -delta + ' ms overlapping between fragments detected');\n }\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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 var nbNalu = 0,\n naluLen = 0;\n for (var _i = 0; _i < nbSamples; _i++) {\n // compute total/avc sample length and nb of NAL units\n var _sample = inputSamples[_i],\n units = _sample.units,\n nbUnits = units.length,\n sampleLen = 0;\n for (var j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\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 var mdatSize = naluLen + 4 * nbNalu + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MUX_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating video mdat ' + mdatSize });\n return;\n }\n var view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(__WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].types.mdat, 4);\n\n for (var _i2 = 0; _i2 < nbSamples; _i2++) {\n var avcSample = inputSamples[_i2],\n avcSampleUnits = avcSample.units,\n mp4SampleLength = 0,\n compositionTimeOffset = void 0;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {\n var 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 (_i2 < nbSamples - 1) {\n mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;\n } else {\n var config = this.config,\n lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].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 maxBufferHole.\n // 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 var maxBufferHole = config.maxBufferHole,\n gapTolerance = Math.floor(maxBufferHole * 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 should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\n\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 // 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 var 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 var 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 = __WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].moof(track.sequenceNumber++, firstDTS, track);\n track.samples = [];\n\n var 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 hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: dropped\n };\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_DATA, data);\n return data;\n };\n\n MP4Remuxer.prototype.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {\n var 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 = void 0,\n mp4Sample = void 0,\n fillFrame = void 0,\n mdat = void 0,\n moof = void 0,\n firstPTS = void 0,\n lastPTS = void 0,\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 && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initDTS) < 20 * inputSampleDuration);\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter(function (sample) {\n return sample.pts >= 0;\n });\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = timeOffset * inputTimeScale;\n }\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 if (track.isAAC) {\n var maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (var 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],\n delta;\n var pts = sample.pts;\n delta = pts - nextPts;\n\n var 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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 } // eslint-disable-line brace-style\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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 var newStamp = Math.max(nextPts, 0);\n fillFrame = __WEBPACK_IMPORTED_MODULE_0__aac_helper__[\"a\" /* default */].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {\n var audioSample = inputSamples[_j2];\n var unit = audioSample.unit;\n var _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 var _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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].log(_delta + ' ms hole between AAC samples detected,filling it');\n if (numMissingFrames > 0) {\n fillFrame = __WEBPACK_IMPORTED_MODULE_0__aac_helper__[\"a\" /* default */].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n fillFrame = unit.subarray();\n }\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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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\n firstPTS = _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 var 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MUX_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating audio mdat ' + mdatSize });\n return;\n }\n if (!rawMPEG) {\n var view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(__WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n for (var _i3 = 0; _i3 < numMissingFrames; _i3++) {\n fillFrame = __WEBPACK_IMPORTED_MODULE_0__aac_helper__[\"a\" /* default */].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 var 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 = __WEBPACK_IMPORTED_MODULE_1__mp4_generator__[\"a\" /* default */].moof(track.sequenceNumber++, firstPTS / scaleFactor, track);\n }\n\n track.samples = [];\n var start = firstPTS / inputTimeScale;\n var end = nextAudioPts / inputTimeScale;\n var audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type: 'audio',\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples\n };\n this.observer.trigger(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_DATA, audioData);\n return audioData;\n }\n return null;\n };\n\n MP4Remuxer.prototype.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {\n var inputTimeScale = track.inputTimeScale,\n mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,\n scaleFactor = inputTimeScale / mp4timeScale,\n nextAudioPts = this.nextAudioPts,\n\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\n // one sample's duration value\n sampleDuration = 1024,\n frameDuration = scaleFactor * sampleDuration,\n\n\n // samples count of this segment's duration\n nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),\n\n\n // silent frame\n silentFrame = __WEBPACK_IMPORTED_MODULE_0__aac_helper__[\"a\" /* default */].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');\n return;\n }\n\n var 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 MP4Remuxer.prototype.remuxID3 = function remuxID3(track, timeOffset) {\n var length = track.samples.length,\n sample = void 0;\n var inputTimeScale = track.inputTimeScale;\n var initPTS = this._initPTS;\n var 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_METADATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n timeOffset = timeOffset;\n };\n\n MP4Remuxer.prototype.remuxText = function remuxText(track, timeOffset) {\n track.samples.sort(function (a, b) {\n return a.pts - b.pts;\n });\n\n var length = track.samples.length,\n sample = void 0;\n var inputTimeScale = track.inputTimeScale;\n var 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(__WEBPACK_IMPORTED_MODULE_2__events__[\"a\" /* default */].FRAG_PARSING_USERDATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n timeOffset = timeOffset;\n };\n\n MP4Remuxer.prototype._PTSNormalize = function _PTSNormalize(value, reference) {\n var offset = void 0;\n if (reference === undefined) {\n return value;\n }\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\n return value;\n };\n\n return MP4Remuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (MP4Remuxer);\n\n/***/ }),\n/* 44 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * AAC helper\n */\n\nvar AAC = function () {\n function AAC() {\n _classCallCheck(this, AAC);\n }\n\n AAC.getSilentFrame = function 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\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 return AAC;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AAC);\n\n/***/ }),\n/* 45 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * Generate MP4 Box\n*/\n\nvar UINT32_MAX = Math.pow(2, 32) - 1;\n\nvar MP4 = function () {\n function MP4() {\n _classCallCheck(this, MP4);\n }\n\n MP4.init = function 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 = void 0;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];\n }\n }\n\n var videoHdlr = new Uint8Array([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, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n ]);\n\n var audioHdlr = new Uint8Array([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, 0x64, 0x48, 0x61, 0x6e, 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([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([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([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([0x00, // version\n 0x00, 0x00, 0x01, // flags\n 0x00, 0x00, // graphicsmode\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor\n ]);\n MP4.SMHD = new Uint8Array([0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, // balance\n 0x00, 0x00 // reserved\n ]);\n\n MP4.STSD = new Uint8Array([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 MP4.box = function box(type) {\n var payload = Array.prototype.slice.call(arguments, 1),\n size = 8,\n i = payload.length,\n len = i,\n result = void 0;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\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 MP4.hdlr = function hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n };\n\n MP4.mdat = function mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n };\n\n MP4.mdhd = function mdhd(timescale, duration) {\n duration *= timescale;\n var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.mdhd, new Uint8Array([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, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale\n 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)\n 0x00, 0x00]));\n };\n\n MP4.mdia = function 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 MP4.mfhd = function mfhd(sequenceNumber) {\n return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags\n sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number\n ]));\n };\n\n MP4.minf = function 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 MP4.moof = function 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\n\n MP4.moov = function moov(tracks) {\n var 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 MP4.mvex = function mvex(tracks) {\n var i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));\n };\n\n MP4.mvhd = function mvhd(timescale, duration) {\n duration *= timescale;\n var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n var bytes = new Uint8Array([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, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale\n 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\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, 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\n 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\n 0xff, 0xff, 0xff, 0xff // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n };\n\n MP4.sdtp = function sdtp(track) {\n var samples = track.samples || [],\n bytes = new Uint8Array(4 + samples.length),\n flags = void 0,\n i = void 0;\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 | flags.isDependedOn << 2 | flags.hasRedundancy;\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n };\n\n MP4.stbl = function 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 MP4.avc1 = function avc1(track) {\n var sps = [],\n pps = [],\n i = void 0,\n data = void 0,\n len = void 0;\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\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\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\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n var avcc = MP4.box(MP4.types.avcC, new Uint8Array([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([track.pps.length // numOfPictureParameterSets\n ]).concat(pps))),\n // \"PPS\"\n width = track.width,\n height = track.height,\n hSpacing = track.pixelRatio[0],\n vSpacing = track.pixelRatio[1];\n\n return MP4.box(MP4.types.avc1, new Uint8Array([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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined\n width >> 8 & 0xFF, width & 0xff, // width\n height >> 8 & 0xFF, 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, 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js\n 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\n 0x00, 0x18, // depth = 24\n 0x11, 0x11]), // pre_defined = -1\n avcc, MP4.box(MP4.types.btrt, new Uint8Array([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([hSpacing >> 24, // hSpacing\n hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing\n vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));\n };\n\n MP4.esds = function esds(track) {\n var configlen = track.config.length;\n return new Uint8Array([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 MP4.mp4a = function mp4a(track) {\n var samplerate = track.samplerate;\n return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00, 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, samplerate & 0xff, //\n 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));\n };\n\n MP4.mp3 = function mp3(track) {\n var samplerate = track.samplerate;\n return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00, 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, samplerate & 0xff, //\n 0x00, 0x00]));\n };\n\n MP4.stsd = function 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\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 MP4.tkhd = function 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([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, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID\n 0x00, 0x00, 0x00, 0x00, // reserved\n 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\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, 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\n width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width\n height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height\n ]));\n };\n\n MP4.traf = function 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, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF]) // track_ID\n ), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 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\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\n\n MP4.trak = function trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n };\n\n MP4.trex = function trex(track) {\n var id = track.id;\n return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, 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 MP4.trun = function trun(track, offset) {\n var samples = track.samples || [],\n len = samples.length,\n arraylen = 12 + 16 * len,\n array = new Uint8Array(arraylen),\n i = void 0,\n sample = void 0,\n duration = void 0,\n size = void 0,\n flags = void 0,\n cts = void 0;\n offset += 8 + arraylen;\n array.set([0x00, // version 0\n 0x00, 0x0f, 0x01, // flags\n len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count\n offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, 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([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration\n size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size\n 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\n cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset\n ], 12 + 16 * i);\n }\n return MP4.box(MP4.types.trun, array);\n };\n\n MP4.initSegment = function initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n var movie = MP4.moov(tracks),\n result = void 0;\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 return MP4;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (MP4);\n\n/***/ }),\n/* 46 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * passthrough remuxer\n*/\n\n\nvar PassThroughRemuxer = function () {\n function PassThroughRemuxer(observer) {\n _classCallCheck(this, PassThroughRemuxer);\n\n this.observer = observer;\n }\n\n PassThroughRemuxer.prototype.destroy = function destroy() {};\n\n PassThroughRemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};\n\n PassThroughRemuxer.prototype.resetInitSegment = function resetInitSegment() {};\n\n PassThroughRemuxer.prototype.remux = function 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\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\n nb: 1,\n dropped: 0\n });\n // notify end of parsing\n observer.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_PARSED);\n };\n\n return PassThroughRemuxer;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (PassThroughRemuxer);\n\n/***/ }),\n/* 47 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__ = __webpack_require__(21);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events__ = __webpack_require__(12);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_events__);\n/* demuxer web worker.\n * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.\n * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.\n */\n\n\n\n\n\n\nvar DemuxerWorker = function DemuxerWorker(self) {\n // observer setup\n var observer = new __WEBPACK_IMPORTED_MODULE_3_events___default.a();\n observer.trigger = function trigger(event) {\n for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n data[_key - 1] = arguments[_key];\n }\n\n observer.emit.apply(observer, [event, event].concat(data));\n };\n\n observer.off = function off(event) {\n for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n data[_key2 - 1] = arguments[_key2];\n }\n\n observer.removeListener.apply(observer, [event].concat(data));\n };\n\n var forwardMessage = function forwardMessage(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 var config = JSON.parse(data.config);\n self.demuxer = new __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__[\"a\" /* default */](observer, data.typeSupported, config, data.vendor);\n try {\n Object(__WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"a\" /* 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(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_DECRYPTED, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSED, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_METADATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].INIT_PTS_FOUND, forwardMessage);\n\n // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)\n observer.on(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].FRAG_PARSING_DATA, function (ev, data) {\n var transferable = [];\n var 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\n/* harmony default export */ __webpack_exports__[\"default\"] = (DemuxerWorker);\n\n/***/ }),\n/* 48 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = calculateNextPDT;\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = findFragmentByPDT;\n/* harmony export (immutable) */ __webpack_exports__[\"c\"] = findFragmentBySN;\n/* harmony export (immutable) */ __webpack_exports__[\"d\"] = fragmentWithinToleranceTest;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__ = __webpack_require__(6);\n\n\n/**\n * Calculates the PDT of the next load position.\n * bufferEnd in this function is usually the position of the playhead.\n * @param {number} [start = 0] - The PTS of the first fragment within the level\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level\n * @returns {number} nextPdt - The computed PDT\n */\nfunction calculateNextPDT() {\n var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var bufferEnd = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var levelDetails = arguments[2];\n\n var pdt = 0;\n if (levelDetails.programDateTime) {\n var parsedDateInt = Date.parse(levelDetails.programDateTime);\n if (!isNaN(parsedDateInt)) {\n pdt = bufferEnd * 1000 + parsedDateInt - 1000 * start;\n }\n }\n return pdt;\n}\n\n/**\n * Finds the first fragment whose endPDT value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @returns {*|null} fragment - The best matching fragment\n */\nfunction findFragmentByPDT(fragments) {\n var PDTValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n\n if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) {\n return null;\n }\n\n // if less than start\n var firstSegment = fragments[0];\n\n if (PDTValue < firstSegment.pdt) {\n return null;\n }\n\n var lastSegment = fragments[fragments.length - 1];\n\n if (PDTValue >= lastSegment.endPdt) {\n return null;\n }\n\n for (var seg = 0; seg < fragments.length; ++seg) {\n var frag = fragments[seg];\n if (PDTValue < frag.endPdt) {\n return frag;\n }\n }\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} [end = 0] - The computed end time of the stream\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nfunction findFragmentBySN(fragPrevious, fragments) {\n var bufferEnd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n var maxFragLookUpTolerance = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;\n\n var foundFrag = void 0;\n var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__[\"a\" /* default */].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n }\n }\n return foundFrag;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nfunction fragmentWithinToleranceTest() {\n var bufferEnd = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var maxFragLookUpTolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var candidate = arguments[2];\n\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 var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n/***/ }),\n/* 49 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_codecs__ = __webpack_require__(19);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__level_helper__ = __webpack_require__(15);\nvar _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; };\n\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Level Controller\n*/\n\n\n\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\nvar LevelController = function (_EventHandler) {\n _inherits(LevelController, _EventHandler);\n\n function LevelController(hls) {\n _classCallCheck(this, LevelController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR));\n\n _this.canload = false;\n _this.currentLevelIndex = null;\n _this.manualLevelIndex = -1;\n _this.timer = null;\n return _this;\n }\n\n LevelController.prototype.onHandlerDestroying = function onHandlerDestroying() {\n this.clearTimer();\n this.manualLevelIndex = -1;\n };\n\n LevelController.prototype.clearTimer = function clearTimer() {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n };\n\n LevelController.prototype.startLoad = function startLoad() {\n var 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(function (level) {\n level.loadError = 0;\n var 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 !== null) {\n this.loadLevel();\n }\n };\n\n LevelController.prototype.stopLoad = function stopLoad() {\n this.canload = false;\n };\n\n LevelController.prototype.onManifestLoaded = function onManifestLoaded(data) {\n var levels = [];\n var bitrateStart = void 0;\n var levelSet = {};\n var levelFromSet = null;\n var videoCodecFound = false;\n var audioCodecFound = false;\n var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());\n var audioTracks = [];\n\n // regroup redundant levels together\n data.levels.forEach(function (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 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (level.attrs && level.attrs.AUDIO) {\n Object(__WEBPACK_IMPORTED_MODULE_5__level_helper__[\"a\" /* addGroupId */])(levelFromSet || level, 'audio', level.attrs.AUDIO);\n }\n\n if (level.attrs && level.attrs.SUBTITLES) {\n Object(__WEBPACK_IMPORTED_MODULE_5__level_helper__[\"a\" /* addGroupId */])(levelFromSet || level, 'text', level.attrs.SUBTITLES);\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\n levels = levels.filter(function (_ref) {\n var videoCodec = _ref.videoCodec;\n return !!videoCodec;\n });\n }\n\n // only keep levels with supported audio/video codecs\n levels = levels.filter(function (_ref2) {\n var audioCodec = _ref2.audioCodec,\n videoCodec = _ref2.videoCodec;\n\n return (!audioCodec || Object(__WEBPACK_IMPORTED_MODULE_4__utils_codecs__[\"a\" /* isCodecSupportedInMp4 */])(audioCodec)) && (!videoCodec || Object(__WEBPACK_IMPORTED_MODULE_4__utils_codecs__[\"a\" /* isCodecSupportedInMp4 */])(videoCodec));\n });\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(function (track) {\n return !track.audioCodec || Object(__WEBPACK_IMPORTED_MODULE_4__utils_codecs__[\"a\" /* isCodecSupportedInMp4 */])(track.audioCodec, 'audio');\n });\n }\n\n if (levels.length > 0) {\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 (var i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);\n break;\n }\n }\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_PARSED, {\n levels: levels,\n audioTracks: audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: audioTracks.length > 0 && videoCodecFound\n });\n } else {\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* 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 LevelController.prototype.setLevelInternal = function setLevelInternal(newLevel) {\n var levels = this._levels;\n var 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.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('switching to level ' + newLevel);\n this.currentLevelIndex = newLevel;\n var levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_SWITCHING, levelProperties);\n }\n var level = levels[newLevel];\n var levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n var urlId = level.urlId;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });\n }\n } else {\n // invalid level id given, trigger error\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].OTHER_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n };\n\n LevelController.prototype.onError = function onError(data) {\n if (data.fatal) {\n if (data.type === __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n var levelError = false,\n fragmentError = false;\n var levelIndex = void 0;\n\n // try to recover not fatal errors\n switch (data.details) {\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_TIMEOUT:\n levelIndex = data.frag.level;\n fragmentError = true;\n break;\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT:\n levelIndex = data.context.level;\n levelError = true;\n break;\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].REMUX_ALLOC_ERROR:\n levelIndex = data.level;\n levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n };\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n\n\n LevelController.prototype.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {\n var _this2 = this;\n\n var config = this.hls.config;\n var errorDetails = errorEvent.details;\n\n var level = this._levels[levelIndex];\n var redundantLevels = void 0,\n delay = void 0,\n nextLevel = void 0;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(function () {\n return _this2.loadLevel();\n }, delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount);\n } else {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('level controller, cannot recover from ' + errorDetails + ' error');\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('level controller, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant URL-id ' + level.urlId);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('level controller, ' + errorDetails + ': switch to ' + nextLevel);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('level controller, ' + errorDetails + ': reload a fragment');\n this.currentLevelIndex = null;\n }\n }\n }\n };\n\n // reset errors on the successful load of a fragment\n\n\n LevelController.prototype.onFragLoaded = function onFragLoaded(_ref3) {\n var frag = _ref3.frag;\n\n if (frag !== undefined && frag.type === 'main') {\n var 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 LevelController.prototype.onLevelLoaded = function onLevelLoaded(data) {\n var _this3 = this;\n\n var levelId = data.level;\n // only process level loaded events matching with expected level\n if (levelId !== this.currentLevelIndex) {\n return;\n }\n\n var 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) {\n curLevel.loadError = 0;\n this.levelRetryCount = 0;\n }\n var newDetails = data.details;\n // if current playlist is a live playlist, arm a timer to reload it\n if (newDetails.live) {\n var targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration);\n var reloadInterval = targetdurationMs,\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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 half of target duration\n reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval));\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('live playlist, reload in ' + Math.round(reloadInterval) + ' ms');\n this.timer = setTimeout(function () {\n return _this3.loadLevel();\n }, reloadInterval);\n } else {\n this.clearTimer();\n }\n };\n\n LevelController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) {\n var audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n var currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n var urlId = currentLevel.audioGroupIds.findIndex(function (groupId) {\n return groupId === audioGroupId;\n });\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n };\n\n LevelController.prototype.loadLevel = function loadLevel() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n var levelObject = this._levels[this.currentLevelIndex];\n\n if ((typeof levelObject === 'undefined' ? 'undefined' : _typeof(levelObject)) === 'object' && levelObject.url.length > 0) {\n var level = this.currentLevelIndex;\n var id = levelObject.urlId;\n var url = levelObject.url[id];\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('Attempt loading level index ' + level + ' with URL-id ' + id);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADING, { url: url, level: level, id: id });\n }\n }\n };\n\n _createClass(LevelController, [{\n key: 'levels',\n get: function get() {\n return this._levels;\n }\n }, {\n key: 'level',\n get: function get() {\n return this.currentLevelIndex;\n },\n set: function set(newLevel) {\n var levels = this._levels;\n if (levels) {\n newLevel = Math.min(newLevel, levels.length - 1);\n if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {\n this.setLevelInternal(newLevel);\n }\n }\n }\n }, {\n key: 'manualLevel',\n get: function get() {\n return this.manualLevelIndex;\n },\n set: function set(newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n }, {\n key: 'firstLevel',\n get: function get() {\n return this._firstLevel;\n },\n set: function set(newLevel) {\n this._firstLevel = newLevel;\n }\n }, {\n key: 'startLevel',\n get: function get() {\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 var 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 set: function set(newLevel) {\n this._startLevel = newLevel;\n }\n }, {\n key: 'nextLoadLevel',\n get: function get() {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n },\n set: function set(nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n }]);\n\n return LevelController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (LevelController);\n\n/***/ }),\n/* 50 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__demux_id3__ = __webpack_require__(7);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_texttrack_utils__ = __webpack_require__(26);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * id3 metadata track controller\n*/\n\n\n\n\n\n\nvar ID3TrackController = function (_EventHandler) {\n _inherits(ID3TrackController, _EventHandler);\n\n function ID3TrackController(hls) {\n _classCallCheck(this, ID3TrackController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_PARSING_METADATA));\n\n _this.id3Track = undefined;\n _this.media = undefined;\n return _this;\n }\n\n ID3TrackController.prototype.destroy = function destroy() {\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n // Add ID3 metatadata text track.\n\n\n ID3TrackController.prototype.onMediaAttached = function onMediaAttached(data) {\n this.media = data.media;\n if (!this.media) {}\n };\n\n ID3TrackController.prototype.onMediaDetaching = function onMediaDetaching() {\n Object(__WEBPACK_IMPORTED_MODULE_3__utils_texttrack_utils__[\"a\" /* clearCurrentCues */])(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n };\n\n ID3TrackController.prototype.getID3Track = function getID3Track(textTracks) {\n for (var i = 0; i < textTracks.length; i++) {\n var textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n Object(__WEBPACK_IMPORTED_MODULE_3__utils_texttrack_utils__[\"b\" /* sendAddTrackEvent */])(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n };\n\n ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) {\n var fragment = data.frag;\n var samples = data.samples;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.getID3Track(this.media.textTracks);\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 var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;\n\n for (var i = 0; i < samples.length; i++) {\n var frames = __WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].getID3Frames(samples[i].data);\n if (frames) {\n var startTime = samples[i].pts;\n var 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 (var j = 0; j < frames.length; j++) {\n var frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!__WEBPACK_IMPORTED_MODULE_2__demux_id3__[\"a\" /* default */].isTimeStampFrame(frame)) {\n var cue = new Cue(startTime, endTime, '');\n cue.value = frame;\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n };\n\n return ID3TrackController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (ID3TrackController);\n\n/***/ }),\n/* 51 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = isSupported;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_mediasource_helper__ = __webpack_require__(14);\n\n\nfunction isSupported() {\n var mediaSource = Object(__WEBPACK_IMPORTED_MODULE_0__utils_mediasource_helper__[\"a\" /* getMediaSource */])();\n var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;\n var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && 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 var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';\n return !!isTypeSupported && !!sourceBufferValidAPI;\n}\n\n/***/ }),\n/* 52 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return hlsDefaultConfig; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__controller_abr_controller__ = __webpack_require__(53);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__controller_buffer_controller__ = __webpack_require__(56);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__controller_cap_level_controller__ = __webpack_require__(57);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__controller_fps_controller__ = __webpack_require__(58);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_xhr_loader__ = __webpack_require__(59);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__controller_audio_track_controller__ = __webpack_require__(60);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__controller_audio_stream_controller__ = __webpack_require__(61);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_cues__ = __webpack_require__(62);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__controller_timeline_controller__ = __webpack_require__(64);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__controller_subtitle_track_controller__ = __webpack_require__(68);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__controller_subtitle_stream_controller__ = __webpack_require__(69);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__controller_eme_controller__ = __webpack_require__(70);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__utils_mediakeys_helper__ = __webpack_require__(71);\n/**\n * HLS config\n */\n\n\n\n\n\n\n// import FetchLoader from './utils/fetch-loader';\n\n\n\n\n\n\n\n\n\n\n\n\nvar 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\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 liveDurationInfinity: false, // used by buffer-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 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: __WEBPACK_IMPORTED_MODULE_4__utils_xhr_loader__[\"a\" /* default */],\n // loader: FetchLoader,\n fLoader: undefined, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\n // fetchSetup: undefined,\n abrController: __WEBPACK_IMPORTED_MODULE_0__controller_abr_controller__[\"a\" /* default */],\n bufferController: __WEBPACK_IMPORTED_MODULE_1__controller_buffer_controller__[\"a\" /* default */],\n capLevelController: __WEBPACK_IMPORTED_MODULE_2__controller_cap_level_controller__[\"a\" /* default */],\n fpsController: __WEBPACK_IMPORTED_MODULE_3__controller_fps_controller__[\"a\" /* default */],\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 emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n requestMediaKeySystemAccessFunc: __WEBPACK_IMPORTED_MODULE_12__utils_mediakeys_helper__[\"a\" /* requestMediaKeySystemAccess */] // used by eme-controller\n};\n\nif (true) {\n hlsDefaultConfig.subtitleStreamController = __WEBPACK_IMPORTED_MODULE_10__controller_subtitle_stream_controller__[\"a\" /* default */];\n hlsDefaultConfig.subtitleTrackController = __WEBPACK_IMPORTED_MODULE_9__controller_subtitle_track_controller__[\"a\" /* default */];\n hlsDefaultConfig.timelineController = __WEBPACK_IMPORTED_MODULE_8__controller_timeline_controller__[\"a\" /* default */];\n hlsDefaultConfig.cueHandler = __WEBPACK_IMPORTED_MODULE_7__utils_cues__; // used by timeline-controller\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 (true) {\n hlsDefaultConfig.audioStreamController = __WEBPACK_IMPORTED_MODULE_6__controller_audio_stream_controller__[\"a\" /* default */];\n hlsDefaultConfig.audioTrackController = __WEBPACK_IMPORTED_MODULE_5__controller_audio_track_controller__[\"a\" /* default */];\n}\n\nif (true) {\n hlsDefaultConfig.emeController = __WEBPACK_IMPORTED_MODULE_11__controller_eme_controller__[\"a\" /* default */];\n}\n\n/***/ }),\n/* 53 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_buffer_helper__ = __webpack_require__(11);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_ewma_bandwidth_estimator__ = __webpack_require__(54);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * simple ABR Controller\n * - compute next level based on last fragment bw heuristics\n * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling\n */\n\n\n\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\nvar AbrController = function (_EventHandler) {\n _inherits(AbrController, _EventHandler);\n\n function AbrController(hls) {\n _classCallCheck(this, AbrController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_BUFFERED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR));\n\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 return _this;\n }\n\n AbrController.prototype.destroy = function destroy() {\n this.clearTimer();\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n AbrController.prototype.onFragLoading = function onFragLoading(data) {\n var frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, 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 var hls = this.hls;\n var config = hls.config;\n var level = frag.level;\n var isLive = hls.levels[level].details.live;\n\n var ewmaFast = void 0,\n ewmaSlow = void 0;\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 __WEBPACK_IMPORTED_MODULE_5__utils_ewma_bandwidth_estimator__[\"a\" /* default */](hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);\n }\n }\n };\n\n AbrController.prototype._abandonRulesCheck = function _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 var hls = this.hls;\n var video = hls.media;\n var frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n var loader = frag.loader;\n var 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 __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* logger */].warn('frag loader destroy or aborted, disarm abandonRules');\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n var 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 (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {\n var requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(video.playbackRate);\n // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate\n if (requestDelay > 500 * frag.duration / playbackRate) {\n var levels = hls.levels,\n loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),\n // 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 = video.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (__WEBPACK_IMPORTED_MODULE_2__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(video, 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 var fragLevelNextLoadedDelay = void 0,\n nextLoadLevel = void 0;\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 var 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 __WEBPACK_IMPORTED_MODULE_4__utils_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));\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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });\n }\n }\n }\n }\n };\n\n AbrController.prototype.onFragLoaded = function onFragLoaded(data) {\n var 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 var level = this.hls.levels[frag.level];\n var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;\n var 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 var stats = data.stats;\n stats.tparsed = stats.tbuffered = stats.tload;\n this.onFragBuffered(data);\n }\n }\n };\n\n AbrController.prototype.onFragBuffered = function onFragBuffered(data) {\n var stats = data.stats;\n var 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.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 var fragLoadingProcessingMs = stats.tparsed - stats.trequest;\n __WEBPACK_IMPORTED_MODULE_4__utils_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)));\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 AbrController.prototype.onError = function onError(data) {\n // stop timer in case of frag loading error\n switch (data.details) {\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:\n this.clearTimer();\n break;\n default:\n break;\n }\n };\n\n AbrController.prototype.clearTimer = function clearTimer() {\n clearInterval(this.timer);\n this.timer = null;\n };\n\n // return next auto level\n\n\n AbrController.prototype._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {\n for (var i = maxAutoLevel; i >= minAutoLevel; i--) {\n var levelInfo = levels[i],\n levelDetails = levelInfo.details,\n avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,\n live = levelDetails ? levelDetails.live : false,\n adjustedbw = void 0;\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\n var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,\n fetchDuration = bitrate * avgDuration / adjustedbw;\n\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 _createClass(AbrController, [{\n key: 'nextAutoLevel',\n get: function get() {\n var forcedAutoLevel = this._nextAutoLevel;\n var 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\n // compute next level using ABR logic\n var 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\n return nextABRAutoLevel;\n },\n set: function set(nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n }, {\n key: '_nextABRAutoLevel',\n get: function get() {\n var hls = this.hls,\n maxAutoLevel = hls.maxAutoLevel,\n levels = hls.levels,\n config = hls.config,\n minAutoLevel = hls.minAutoLevel;\n var video = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = video ? video.currentTime : 0,\n\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0,\n avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,\n\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n bufferStarvationDelay = (__WEBPACK_IMPORTED_MODULE_2__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(video, 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 var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);\n if (bestLevel >= 0) {\n return bestLevel;\n } else {\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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 var 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 var 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 var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n __WEBPACK_IMPORTED_MODULE_4__utils_logger__[\"b\" /* 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\n return AbrController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AbrController);\n\n/***/ }),\n/* 54 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_ewma__ = __webpack_require__(55);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\n\n\nvar EwmaBandWidthEstimator = function () {\n function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {\n _classCallCheck(this, EwmaBandWidthEstimator);\n\n this.hls = hls;\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new __WEBPACK_IMPORTED_MODULE_0__utils_ewma__[\"a\" /* default */](slow);\n this.fast_ = new __WEBPACK_IMPORTED_MODULE_0__utils_ewma__[\"a\" /* default */](fast);\n }\n\n EwmaBandWidthEstimator.prototype.sample = function sample(durationMs, numBytes) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n var bandwidth = 8000 * numBytes / durationMs,\n\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 EwmaBandWidthEstimator.prototype.canEstimate = function canEstimate() {\n var fast = this.fast_;\n return fast && fast.getTotalWeight() >= this.minWeight_;\n };\n\n EwmaBandWidthEstimator.prototype.getEstimate = function 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 EwmaBandWidthEstimator.prototype.destroy = function destroy() {};\n\n return EwmaBandWidthEstimator;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (EwmaBandWidthEstimator);\n\n/***/ }),\n/* 55 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nvar EWMA = function () {\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n function EWMA(halfLife) {\n _classCallCheck(this, EWMA);\n\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 EWMA.prototype.sample = function 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 EWMA.prototype.getTotalWeight = function getTotalWeight() {\n return this.totalWeight_;\n };\n\n EWMA.prototype.getEstimate = function 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 return EWMA;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (EWMA);\n\n/***/ }),\n/* 56 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_mediasource_helper__ = __webpack_require__(14);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Buffer Controller\n*/\n\n\n\n\n\n\n\nvar MediaSource = Object(__WEBPACK_IMPORTED_MODULE_4__utils_mediasource_helper__[\"a\" /* getMediaSource */])();\n\nvar BufferController = function (_EventHandler) {\n _inherits(BufferController, _EventHandler);\n\n function BufferController(hls) {\n _classCallCheck(this, BufferController);\n\n // the value that we have set mediasource.duration to\n // (the actual duration may be tweaked slighly by the browser)\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_PARSED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_RESET, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_APPENDING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_CODECS, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_EOS, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_FLUSHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_PTS_UPDATED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_UPDATED));\n\n _this._msDuration = null;\n // the value that we want to set mediaSource.duration to\n _this._levelDuration = null;\n // current stream state: true - for live broadcast, false - for VoD content\n _this._live = null;\n // cache the self generated object url to detect hijack of video tag\n _this._objectUrl = 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 return _this;\n }\n\n BufferController.prototype.destroy = function destroy() {\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n BufferController.prototype.onLevelPtsUpdated = function onLevelPtsUpdated(data) {\n var type = data.type;\n var 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') {\n // Chrome audio mp3 track\n var audioBuffer = this.sourceBuffer.audio;\n var 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 var updating = audioBuffer.updating;\n\n try {\n audioBuffer.abort();\n } catch (err) {\n updating = true;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('can not abort audio buffer: ' + err);\n }\n\n if (!updating) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 BufferController.prototype.onManifestParsed = function onManifestParsed(data) {\n var audioExpected = data.audio,\n videoExpected = data.video || data.levels.length && data.altAudio,\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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log(sourceBufferNb + ' sourceBuffer(s) expected');\n }\n this.sourceBufferNb = sourceBufferNb;\n };\n\n BufferController.prototype.onMediaAttaching = function onMediaAttaching(data) {\n var 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 = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n };\n\n BufferController.prototype.onMediaDetaching = function onMediaDetaching() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 window.URL.revokeObjectURL(this._objectUrl);\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_DETACHED);\n };\n\n BufferController.prototype.onMediaSourceOpen = function onMediaSourceOpen() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('media source opened');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHED, { media: this.media });\n var 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 BufferController.prototype.checkPendingTracks = function checkPendingTracks() {\n // if any buffer codecs pending, check if we have enough to create sourceBuffers\n var 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 && (this.sourceBufferNb <= pendingTracksNb || 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 BufferController.prototype.onMediaSourceClose = function onMediaSourceClose() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('media source closed');\n };\n\n BufferController.prototype.onMediaSourceEnded = function onMediaSourceEnded() {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('media source ended');\n };\n\n BufferController.prototype.onSBUpdateEnd = function onSBUpdateEnd() {\n // update timestampOffset\n if (this.audioTimestampOffset) {\n var audioBuffer = this.sourceBuffer.audio;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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\n this.appending = false;\n var parent = this.parent;\n // count nb of pending segments waiting for appending on this sourcebuffer\n var pending = this.segments.reduce(function (counter, segment) {\n return segment.parent === parent ? counter + 1 : counter;\n }, 0);\n\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n var timeRanges = {};\n var sourceBuffer = this.sourceBuffer;\n for (var streamType in sourceBuffer) {\n timeRanges[streamType] = sourceBuffer[streamType].buffered;\n }\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges });\n // don't append in flushing mode\n if (!this._needsFlush) {\n this.doAppending();\n }\n\n this.updateMediaElementDuration();\n };\n\n BufferController.prototype.onSBUpdateError = function onSBUpdateError(event) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* 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 BufferController.prototype.onBufferReset = function 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 this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n };\n\n BufferController.prototype.onBufferCodecs = function 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) {\n this.pendingTracks[trackName] = tracks[trackName];\n }var 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 BufferController.prototype.createSourceBuffers = function createSourceBuffers(tracks) {\n var sourceBuffer = this.sourceBuffer,\n mediaSource = this.mediaSource;\n\n for (var trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n var track = tracks[trackName];\n // use levelCodec as first priority\n var codec = track.levelCodec || track.codec;\n var mimeType = track.container + ';codecs=' + codec;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('creating sourceBuffer(' + mimeType + ')');\n try {\n var 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('error while trying to add sourceBuffer:' + err.message);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });\n }\n }\n }\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_CREATED, { tracks: tracks });\n };\n\n BufferController.prototype.onBufferAppending = function onBufferAppending(data) {\n if (!this._needsFlush) {\n if (!this.segments) {\n this.segments = [data];\n } else {\n this.segments.push(data);\n }\n\n this.doAppending();\n }\n };\n\n BufferController.prototype.onBufferAppendFail = function onBufferAppendFail(data) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false });\n };\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n\n\n BufferController.prototype.onBufferEos = function onBufferEos(data) {\n var sb = this.sourceBuffer;\n var dataType = data.type;\n for (var type in sb) {\n if (!dataType || type === dataType) {\n if (!sb[type].ended) {\n sb[type].ended = true;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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\n\n BufferController.prototype.checkEos = function checkEos() {\n var sb = this.sourceBuffer,\n mediaSource = this.mediaSource;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n for (var type in sb) {\n var sbobj = sb[type];\n if (!sbobj.ended) {\n return;\n }\n\n if (sbobj.updating) {\n this._needsEos = true;\n return;\n }\n }\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n };\n\n BufferController.prototype.onBufferFlushing = function onBufferFlushing(data) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n };\n\n BufferController.prototype.onLevelUpdated = function onLevelUpdated(_ref) {\n var details = _ref.details;\n\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\n };\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n\n\n BufferController.prototype.updateMediaElementDuration = function updateMediaElementDuration() {\n var config = this.hls.config;\n\n var duration = void 0;\n\n if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {\n return;\n }\n\n for (var type in this.sourceBuffer) {\n if (this.sourceBuffer[type].updating === true) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n\n duration = this.media.duration;\n // initialise to the value that the media source is reporting\n if (this._msDuration === null) {\n this._msDuration = this.mediaSource.duration;\n }\n\n if (this._live === true && config.liveDurationInfinity === true) {\n // Override duration to Infinity\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || duration === Infinity || isNaN(duration)) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('Updating Media Source duration to ' + this._levelDuration.toFixed(3));\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n };\n\n BufferController.prototype.doFlush = function 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('error while accessing sourceBuffer.buffered');\n }\n this.appended = appended;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_FLUSHED);\n }\n };\n\n BufferController.prototype.doAppending = function doAppending() {\n var hls = this.hls,\n sourceBuffer = this.sourceBuffer,\n segments = this.segments;\n if (Object.keys(sourceBuffer).length) {\n if (this.media.error) {\n this.segments = [];\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 var segment = segments.shift();\n try {\n var type = segment.type,\n 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('error while trying to append buffer:' + err.message);\n segments.unshift(segment);\n var event = { type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* 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\n event.details = __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');\n segments = [];\n event.fatal = true;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, event);\n } else {\n event.fatal = false;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 = __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].BUFFER_FULL_ERROR;\n event.fatal = false;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, event);\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\n\n BufferController.prototype.flushBuffer = function flushBuffer(startOffset, endOffset, typeIn) {\n var sb = void 0,\n i = void 0,\n bufStart = void 0,\n bufEnd = void 0,\n flushStart = void 0,\n flushEnd = void 0,\n sourceBuffer = this.sourceBuffer;\n if (Object.keys(sourceBuffer).length) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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\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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('cannot flush, sb updating in progress');\n return false;\n }\n }\n } else {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('abort flushing too many retries');\n }\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('buffer flushed');\n }\n // everything flushed !\n return true;\n };\n\n return BufferController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (BufferController);\n\n/***/ }),\n/* 57 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * cap stream level to media size dimension controller\n*/\n\n\n\n\nvar CapLevelController = function (_EventHandler) {\n _inherits(CapLevelController, _EventHandler);\n\n function CapLevelController(hls) {\n _classCallCheck(this, CapLevelController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FPS_DROP_LEVEL_CAPPING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_PARSED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].BUFFER_CODECS));\n\n _this.autoLevelCapping = Number.POSITIVE_INFINITY;\n _this.firstLevel = null;\n _this.levels = [];\n _this.media = null;\n _this.restrictedLevels = [];\n _this.timer = null;\n return _this;\n }\n\n CapLevelController.prototype.destroy = function destroy() {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this._stopCapping();\n }\n };\n\n CapLevelController.prototype.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) {\n // 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 CapLevelController.prototype.onMediaAttaching = function onMediaAttaching(data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n };\n\n CapLevelController.prototype.onManifestParsed = function onManifestParsed(data) {\n var hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && (data.video || data.levels.length && data.altAudio)) {\n // Start capping immediately if the manifest has signaled video codecs\n this._startCapping();\n }\n };\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n\n\n CapLevelController.prototype.onBufferCodecs = function onBufferCodecs(data) {\n var hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this._startCapping();\n }\n };\n\n CapLevelController.prototype.onLevelsUpdated = function onLevelsUpdated(data) {\n this.levels = data.levels;\n };\n\n CapLevelController.prototype.detectPlayerSize = function detectPlayerSize() {\n if (this.media) {\n var levelsLength = this.levels ? this.levels.length : 0;\n if (levelsLength) {\n var 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\n\n CapLevelController.prototype.getMaxLevel = function getMaxLevel(capLevelIndex) {\n var _this2 = this;\n\n if (!this.levels) {\n return -1;\n }\n\n var validLevels = this.levels.filter(function (level, index) {\n return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;\n });\n\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n };\n\n CapLevelController.prototype._startCapping = function _startCapping() {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n };\n\n CapLevelController.prototype._stopCapping = function _stopCapping() {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\n };\n\n CapLevelController.isLevelAllowed = function isLevelAllowed(level) {\n var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n\n return restrictedLevels.indexOf(level) === -1;\n };\n\n CapLevelController.getMaxLevelByMediaSize = function 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 var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {\n if (!nextLevel) {\n return true;\n }\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 var maxLevelIndex = levels.length - 1;\n\n for (var i = 0; i < levels.length; i += 1) {\n var 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 _createClass(CapLevelController, [{\n key: 'mediaWidth',\n get: function get() {\n var width = void 0;\n var 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 key: 'mediaHeight',\n get: function get() {\n var height = void 0;\n var 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 key: 'contentScaleFactor',\n get: function get() {\n var pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch (e) {}\n return pixelRatio;\n }\n }]);\n\n return CapLevelController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (CapLevelController);\n\n/***/ }),\n/* 58 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * FPS Controller\n*/\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\nvar FPSController = function (_EventHandler) {\n _inherits(FPSController, _EventHandler);\n\n function FPSController(hls) {\n _classCallCheck(this, FPSController);\n\n return _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHING));\n }\n\n FPSController.prototype.destroy = function destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.isVideoPlaybackQualityAvailable = false;\n };\n\n FPSController.prototype.onMediaAttaching = function onMediaAttaching(data) {\n var config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n var video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n }\n };\n\n FPSController.prototype.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {\n var currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n var 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 var currentLevel = hls.currentLevel;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 FPSController.prototype.checkFPSInterval = function checkFPSInterval() {\n var video = this.video;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n var 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 return FPSController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (FPSController);\n\n/***/ }),\n/* 59 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n * XHR based logger\n*/\n\n\n\nvar _window = window,\n performance = _window.performance,\n XMLHttpRequest = _window.XMLHttpRequest;\n\nvar XhrLoader = function () {\n function XhrLoader(config) {\n _classCallCheck(this, XhrLoader);\n\n if (config && config.xhrSetup) {\n this.xhrSetup = config.xhrSetup;\n }\n }\n\n XhrLoader.prototype.destroy = function destroy() {\n this.abort();\n this.loader = null;\n };\n\n XhrLoader.prototype.abort = function 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 XhrLoader.prototype.load = function 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 XhrLoader.prototype.loadInternal = function loadInternal() {\n var xhr = void 0,\n context = this.context;\n xhr = this.loader = new XMLHttpRequest();\n\n var stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n var 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\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 XhrLoader.prototype.readystatechange = function 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\n if (readyState === 4) {\n var 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 var data = void 0,\n len = void 0;\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 var 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 __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].error(status + ' while loading ' + context.url);\n this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);\n } else {\n // retry\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* 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 XhrLoader.prototype.loadtimeout = function loadtimeout() {\n __WEBPACK_IMPORTED_MODULE_0__utils_logger__[\"b\" /* logger */].warn('timeout while loading ' + this.context.url);\n this.callbacks.onTimeout(this.stats, this.context, null);\n };\n\n XhrLoader.prototype.loadprogress = function 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\n var 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 return XhrLoader;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (XhrLoader);\n\n/***/ }),\n/* 60 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__task_loop__ = __webpack_require__(8);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors__ = __webpack_require__(2);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n\n\n\n\n\n/**\n * @class AudioTrackController\n * @implements {EventHandler}\n *\n * Handles main manifest and audio-track metadata loaded,\n * owns and exposes the selectable audio-tracks data-models.\n *\n * Exposes internal interface to select available audio-tracks.\n *\n * Handles errors on loading audio-track playlists. Manages fallback mechanism\n * with redundants tracks (group-IDs).\n *\n * Handles level-loading and group-ID switches for video (fallback on video levels),\n * and eventually adapts the audio-track group-ID to match.\n *\n * @fires AUDIO_TRACK_LOADING\n * @fires AUDIO_TRACK_SWITCHING\n * @fires AUDIO_TRACKS_UPDATED\n * @fires ERROR\n *\n */\n\nvar AudioTrackController = function (_TaskLoop) {\n _inherits(AudioTrackController, _TaskLoop);\n\n function AudioTrackController(hls) {\n _classCallCheck(this, AudioTrackController);\n\n /**\n * @private\n * Currently selected index in `tracks`\n * @member {number} trackId\n */\n var _this = _possibleConstructorReturn(this, _TaskLoop.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_PARSED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR));\n\n _this.trackId = -1;\n\n /**\n * @public\n * All tracks available\n * @member {AudioTrack[]}\n */\n _this.tracks = [];\n\n /**\n * @public\n * List of blacklisted audio track IDs (that have caused failure)\n * @member {number[]}\n */\n _this.trackIdBlacklist = Object.create(null);\n\n /**\n * @public\n * The currently running group ID for audio\n * (we grab this on manifest-parsed and new level-loaded)\n * @member {string}\n */\n _this.audioGroupId = null;\n return _this;\n }\n\n /**\n * Reset audio tracks on new manifest loading.\n */\n\n\n AudioTrackController.prototype.onManifestLoading = function onManifestLoading() {\n this.tracks = [];\n this.trackId = -1;\n };\n\n /**\n * Store tracks data from manifest parsed data.\n *\n * Trigger AUDIO_TRACKS_UPDATED event.\n *\n * @param {*} data\n */\n\n\n AudioTrackController.prototype.onManifestParsed = function onManifestParsed(data) {\n var tracks = this.tracks = data.audioTracks || [];\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACKS_UPDATED, { audioTracks: tracks });\n };\n\n /**\n * Store track details of loaded track in our data-model.\n *\n * Set-up metadata update interval task for live-mode streams.\n *\n * @param {} data\n */\n\n\n AudioTrackController.prototype.onAudioTrackLoaded = function onAudioTrackLoaded(data) {\n if (data.id >= this.tracks.length) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('Invalid audio track id:', data.id);\n return;\n }\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('audioTrack ' + data.id + ' loaded');\n\n this.tracks[data.id].details = data.details;\n\n // check if current playlist is a live playlist\n // and if we have already our reload interval setup\n if (data.details.live && !this.hasInterval()) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n var updatePeriodMs = data.details.targetduration * 1000;\n this.setInterval(updatePeriodMs);\n }\n\n if (!data.details.live && this.hasInterval()) {\n // playlist is not live and timer is scheduled: cancel it\n this.clearInterval();\n }\n };\n\n /**\n * Update the internal group ID to any audio-track we may have set manually\n * or because of a failure-handling fallback.\n *\n * Quality-levels should update to that group ID in this case.\n *\n * @param {*} data\n */\n\n\n AudioTrackController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) {\n var audioGroupId = this.tracks[data.id].groupId;\n if (audioGroupId && this.audioGroupId !== audioGroupId) {\n this.audioGroupId = audioGroupId;\n }\n };\n\n /**\n * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)\n * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.\n *\n * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently\n * selected one (based on NAME property).\n *\n * @param {*} data\n */\n\n\n AudioTrackController.prototype.onLevelLoaded = function onLevelLoaded(data) {\n // FIXME: crashes because currentLevel is undefined\n // const levelInfo = this.hls.levels[this.hls.currentLevel];\n\n var levelInfo = this.hls.levels[data.level];\n\n if (!levelInfo.audioGroupIds) {\n return;\n }\n\n var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.audioGroupId !== audioGroupId) {\n this.audioGroupId = audioGroupId;\n this._selectInitialAudioTrack();\n }\n };\n\n /**\n * Handle network errors loading audio track manifests\n * and also pausing on any netwok errors.\n *\n * @param {ErrorEventData} data\n */\n\n\n AudioTrackController.prototype.onError = function onError(data) {\n // Only handle network errors\n if (data.type !== __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].NETWORK_ERROR) {\n return;\n }\n\n // If fatal network error, cancel update task\n if (data.fatal) {\n this.clearInterval();\n }\n\n // If not an audio-track loading error don't handle further\n if (data.details !== __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR) {\n return;\n }\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('Network failure on audio-track id:', data.context.id);\n this._handleLoadError();\n };\n\n /**\n * @type {AudioTrack[]} Audio-track list we own\n */\n\n\n /**\n * @override\n */\n AudioTrackController.prototype.doTick = function doTick() {\n this._updateTrack(this.trackId);\n };\n\n /**\n * Select initial track\n * @private\n */\n\n\n AudioTrackController.prototype._selectInitialAudioTrack = function _selectInitialAudioTrack() {\n var _this2 = this;\n\n var tracks = this.tracks;\n if (!tracks.length) {\n return;\n }\n\n var currentAudioTrack = this.tracks[this.trackId];\n\n var name = null;\n if (currentAudioTrack) {\n name = currentAudioTrack.name;\n }\n\n // Pre-select default tracks if there are any\n var defaultTracks = tracks.filter(function (track) {\n return track.default;\n });\n if (defaultTracks.length) {\n tracks = defaultTracks;\n } else {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('No default audio tracks defined');\n }\n\n var trackFound = false;\n\n var traverseTracks = function traverseTracks() {\n // Select track with right group ID\n tracks.forEach(function (track) {\n if (trackFound) {\n return;\n }\n // We need to match the (pre-)selected group ID\n // and the NAME of the current track.\n if ((!_this2.audioGroupId || track.groupId === _this2.audioGroupId) && (!name || name === track.name)) {\n // If there was a previous track try to stay with the same `NAME`.\n // It should be unique across tracks of same group, and consistent through redundant track groups.\n _this2.audioTrack = track.id;\n trackFound = true;\n }\n });\n };\n\n traverseTracks();\n\n if (!trackFound) {\n name = null;\n traverseTracks();\n }\n\n if (!trackFound) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].error('No track found for running audio group-ID: ' + this.audioGroupId);\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_3__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_3__errors__[\"a\" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR,\n fatal: true\n });\n }\n };\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n * @returns {boolean}\n */\n\n\n AudioTrackController.prototype._needsTrackLoading = function _needsTrackLoading(audioTrack) {\n var details = audioTrack.details;\n\n\n if (!details) {\n return true;\n } else if (details.live) {\n return true;\n }\n };\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n */\n\n\n AudioTrackController.prototype._loadTrackDetailsIfNeeded = function _loadTrackDetailsIfNeeded(audioTrack) {\n if (this._needsTrackLoading(audioTrack)) {\n var url = audioTrack.url,\n id = audioTrack.id;\n // track not retrieved yet, or live playlist we need to (re)load it\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('loading audio-track playlist for id: ' + id);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_LOADING, { url: url, id: id });\n }\n };\n\n /**\n * @private\n * @param {number} newId\n */\n\n\n AudioTrackController.prototype._updateTrack = function _updateTrack(newId) {\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearInterval();\n this.trackId = newId;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('trying to update audio-track ' + newId);\n var audioTrack = this.tracks[newId];\n this._loadTrackDetailsIfNeeded(audioTrack);\n };\n\n /**\n * @private\n */\n\n\n AudioTrackController.prototype._handleLoadError = function _handleLoadError() {\n // First, let's black list current track id\n this.trackIdBlacklist[this.trackId] = true;\n\n // Let's try to fall back on a functional audio-track with the same group ID\n var previousId = this.trackId;\n var _tracks$previousId = this.tracks[previousId],\n name = _tracks$previousId.name,\n language = _tracks$previousId.language,\n groupId = _tracks$previousId.groupId;\n\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('Loading failed on audio track id: ' + previousId + ', group-id: ' + groupId + ', name/language: \"' + name + '\" / \"' + language + '\"');\n\n // Find a non-blacklisted track ID with the same NAME\n // At least a track that is not blacklisted, thus on another group-ID.\n var newId = previousId;\n for (var i = 0; i < this.tracks.length; i++) {\n if (this.trackIdBlacklist[i]) {\n continue;\n }\n var newTrack = this.tracks[i];\n if (newTrack.name === name) {\n newId = i;\n break;\n }\n }\n\n if (newId === previousId) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('No fallback audio-track found for name/language: \"' + name + '\" / \"' + language + '\"');\n return;\n }\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);\n\n this.audioTrack = newId;\n };\n\n _createClass(AudioTrackController, [{\n key: 'audioTracks',\n get: function get() {\n return this.tracks;\n }\n\n /**\n * @type {number} Index into audio-tracks list of currently selected track.\n */\n\n }, {\n key: 'audioTrack',\n get: function get() {\n return this.trackId;\n }\n\n /**\n * Select current track by index\n */\n ,\n set: function set(newId) {\n // noop on same audio track id as already set\n if (this.trackId === newId && this.tracks[this.trackId].details) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].debug('Same id as current audio-track passed, and track details available -> no-op');\n return;\n }\n\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].warn('Invalid id passed to audio-track controller');\n return;\n }\n\n var audioTrack = this.tracks[newId];\n\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('Now switching to audio-track index ' + newId);\n\n // stopping live reloading timer if any\n this.clearInterval();\n this.trackId = newId;\n\n var url = audioTrack.url,\n type = audioTrack.type,\n id = audioTrack.id;\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHING, { id: id, type: type, url: url });\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n }]);\n\n return AudioTrackController;\n}(__WEBPACK_IMPORTED_MODULE_1__task_loop__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AudioTrackController);\n\n/***/ }),\n/* 61 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__ = __webpack_require__(6);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__ = __webpack_require__(11);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__demux_demuxer__ = __webpack_require__(20);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__level_helper__ = __webpack_require__(15);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_time_ranges__ = __webpack_require__(24);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_discontinuities__ = __webpack_require__(25);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__task_loop__ = __webpack_require__(8);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__fragment_tracker__ = __webpack_require__(10);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__loader_fragment__ = __webpack_require__(9);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Audio Stream Controller\n*/\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\n\nvar 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\nvar AudioStreamController = function (_TaskLoop) {\n _inherits(AudioStreamController, _TaskLoop);\n\n function AudioStreamController(hls, fragmentTracker) {\n _classCallCheck(this, AudioStreamController);\n\n var _this = _possibleConstructorReturn(this, _TaskLoop.call(this, hls, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MEDIA_ATTACHED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACKS_UPDATED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHING, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].KEY_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSING_INIT_SEGMENT, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSING_DATA, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_PARSED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_RESET, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_CREATED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_APPENDED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_FLUSHED, __WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].INIT_PTS_FOUND));\n\n _this.fragmentTracker = fragmentTracker;\n _this.config = hls.config;\n _this.audioCodecSwap = false;\n _this._state = State.STOPPED;\n _this.initPTS = [];\n _this.waitingFragment = null;\n _this.videoTrackCC = null;\n return _this;\n }\n\n AudioStreamController.prototype.onHandlerDestroying = function onHandlerDestroying() {\n this.stopLoad();\n _TaskLoop.prototype.onHandlerDestroying.call(this);\n };\n\n AudioStreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n _TaskLoop.prototype.onHandlerDestroyed.call(this);\n };\n\n // Signal that video PTS was found\n\n\n AudioStreamController.prototype.onInitPtsFound = function onInitPtsFound(data) {\n var demuxerId = data.id,\n cc = data.frag.cc,\n 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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 AudioStreamController.prototype.startLoad = function startLoad(startPosition) {\n if (this.tracks) {\n var lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(100);\n this.fragLoadError = 0;\n if (lastCurrentTime > 0 && startPosition === -1) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 AudioStreamController.prototype.stopLoad = function stopLoad() {\n var frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\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 AudioStreamController.prototype.doTick = function doTick() {\n var pos = void 0,\n track = void 0,\n trackDetails = void 0,\n hls = this.hls,\n 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 var tracks = this.tracks;\n // audio tracks not received => exit loop\n if (!tracks) {\n break;\n }\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 && (this.startFragRequested || !config.startFragPrefetch)) {\n break;\n }\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 var media = this.mediaBuffer ? this.mediaBuffer : this.media,\n videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,\n bufferInfo = __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(media, pos, config.maxBufferHole),\n mainBufferInfo = __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].bufferInfo(videoBuffer, pos, config.maxBufferHole),\n bufferLen = bufferInfo.len,\n bufferEnd = bufferInfo.end,\n fragPrevious = this.fragPrevious,\n\n // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)\n // whichever is smaller.\n // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)\n maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),\n maxBufLen = Math.max(maxConfigBuffer, 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 // check if we need to finalize media stream\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 if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN && !bufferInfo.nextStart) {\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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 var fragments = trackDetails.fragments,\n fragLen = fragments.length,\n start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n frag = void 0;\n\n // When switching audio track, reload audio as close as possible to currentTime\n if (audioSwitch) {\n if (trackDetails.live && !trackDetails.PTSKnown) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 } // eslint-disable-line brace-style\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 = Object(__WEBPACK_IMPORTED_MODULE_8__utils_discontinuities__[\"b\" /* 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 var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 var foundFrag = void 0;\n var maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;\n var fragmentWithinToleranceTest = function 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 var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = __WEBPACK_IMPORTED_MODULE_0__utils_binary_search__[\"a\" /* default */].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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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.encrypted) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId);\n this.state = State.KEY_LOADING;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].KEY_LOADING, { frag: frag });\n } else {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('Loading ' + frag.sn + ', cc: ' + frag.cc + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));\n // only load if fragment is not loaded or if in audio switch\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n if (audioSwitch || this.fragmentTracker.getState(frag) === __WEBPACK_IMPORTED_MODULE_10__fragment_tracker__[\"a\" /* FragmentState */].NOT_LOADED) {\n this.fragCurrent = frag;\n this.startFragRequested = true;\n if (!isNaN(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_LOADING, { frag: frag });\n this.state = State.FRAG_LOADING;\n }\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\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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 var 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 var waitingFrag = this.waitingFragment;\n if (waitingFrag) {\n var waitingFragCC = waitingFrag.frag.cc;\n if (videoTrackCC !== waitingFragCC) {\n track = this.tracks[this.trackId];\n if (track.details && track.details.live) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 AudioStreamController.prototype.onMediaAttached = function 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 var config = this.config;\n if (this.tracks && config.autoStartLoad) {\n this.startLoad(config.startPosition);\n }\n };\n\n AudioStreamController.prototype.onMediaDetaching = function onMediaDetaching() {\n var media = this.media;\n if (media && media.ended) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\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 AudioStreamController.prototype.onMediaSeeking = function 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\n // tick to speed up processing\n this.tick();\n };\n\n AudioStreamController.prototype.onMediaEnded = function onMediaEnded() {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n };\n\n AudioStreamController.prototype.onAudioTracksUpdated = function onAudioTracksUpdated(data) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('audio tracks updated');\n this.tracks = data.audioTracks;\n };\n\n AudioStreamController.prototype.onAudioTrackSwitching = function 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 this.setInterval(100);\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 }\n this.tick();\n };\n\n AudioStreamController.prototype.onAudioTrackLoaded = function 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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_4__level_helper__[\"b\" /* mergeDetails */](curDetails, newDetails);\n sliding = newDetails.fragments[0].start;\n // TODO\n // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('live audio playlist sliding:' + sliding.toFixed(3));\n } else {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('live audio playlist - outdated PTS, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 var startTimeOffset = newDetails.startTimeOffset;\n if (!isNaN(startTimeOffset)) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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\n // trigger handler right now\n this.tick();\n };\n\n AudioStreamController.prototype.onKeyLoaded = function onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n };\n\n AudioStreamController.prototype.onFragLoaded = function onFragLoaded(data) {\n var fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 __WEBPACK_IMPORTED_MODULE_2__demux_demuxer__[\"a\" /* default */](this.hls, 'audio');\n }\n\n // Check if we have video initPTS\n // If not we need to wait for it\n var initPTS = this.initPTS[cc];\n var initSegmentData = details.initSegment ? details.initSegment.data : [];\n if (details.initSegment || initPTS !== undefined) {\n this.pendingBuffering = true;\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 var accurateTimeOffset = false; // details.PTSKnown || !details.live;\n this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);\n } else {\n __WEBPACK_IMPORTED_MODULE_7__utils_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);\n this.waitingFragment = data;\n this.state = State.WAITING_INIT_PTS;\n }\n }\n }\n this.fragLoadError = 0;\n };\n\n AudioStreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) {\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {\n var tracks = data.tracks,\n track = void 0;\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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_CODECS, tracks);\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('audio track:audio,container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');\n var initSegment = track.initSegment;\n if (initSegment) {\n var 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_APPENDING, appendObj);\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n };\n\n AudioStreamController.prototype.onFragParsingData = function onFragParsingData(data) {\n var _this2 = this;\n\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {\n var 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 fragCurrent.addElementaryStream(__WEBPACK_IMPORTED_MODULE_11__loader_fragment__[\"a\" /* default */].ElementaryStreamTypes.AUDIO);\n\n __WEBPACK_IMPORTED_MODULE_7__utils_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);\n __WEBPACK_IMPORTED_MODULE_4__level_helper__[\"c\" /* updateFragPTSDTS */](track.details, fragCurrent, data.startPTS, data.endPTS);\n\n var audioSwitch = this.audioSwitch,\n media = this.media,\n 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 var currentTime = media.currentTime;\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('switching audio track : currentTime:' + currentTime);\n if (currentTime >= data.startPTS) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('switching audio track : flushing all audio');\n this.state = State.BUFFER_FLUSHING;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId });\n }\n }\n\n var pendingData = this.pendingData;\n\n if (!pendingData) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].warn('Apparently attempt to enqueue media payload without codec initialization data upfront');\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].ERROR, { type: __WEBPACK_IMPORTED_MODULE_6__errors__[\"b\" /* ErrorTypes */].MEDIA_ERROR, details: null, fatal: true });\n return;\n }\n\n if (!this.audioSwitch) {\n [data.data1, data.data2].forEach(function (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(function (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 (_this2.state === State.PARSING) {\n // arm pending Buffering flag before appending a segment\n _this2.pendingBuffering = true;\n _this2.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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 AudioStreamController.prototype.onFragParsed = function onFragParsed(data) {\n var fragCurrent = this.fragCurrent;\n var fragNew = data.frag;\n if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {\n this.stats.tparsed = performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n };\n\n AudioStreamController.prototype.onBufferReset = function onBufferReset() {\n // reset reference to sourcebuffers\n this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n };\n\n AudioStreamController.prototype.onBufferCreated = function onBufferCreated(data) {\n var 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 AudioStreamController.prototype.onBufferAppended = function onBufferAppended(data) {\n if (data.parent === 'audio') {\n var 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 AudioStreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n var frag = this.fragCurrent,\n stats = this.stats,\n hls = this.hls;\n if (frag) {\n this.fragPrevious = frag;\n stats.tbuffered = performance.now();\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });\n var media = this.mediaBuffer ? this.mediaBuffer : this.media;\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('audio buffered : ' + __WEBPACK_IMPORTED_MODULE_5__utils_time_ranges__[\"a\" /* default */].toString(media.buffered));\n if (this.audioSwitch && this.appended) {\n this.audioSwitch = false;\n hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].AUDIO_TRACK_SWITCHED, { id: this.trackId });\n }\n this.state = State.IDLE;\n }\n this.tick();\n }\n };\n\n AudioStreamController.prototype.onError = function onError(data) {\n var frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n return;\n }\n\n switch (data.details) {\n case __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:\n var _frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (_frag && _frag.type !== 'audio') {\n break;\n }\n\n if (!data.fatal) {\n var loadError = this.fragLoadError;\n if (loadError) {\n loadError++;\n } else {\n loadError = 1;\n }\n\n var config = this.config;\n if (loadError <= config.fragLoadingMaxRetry) {\n this.fragLoadError = loadError;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* 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 __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT:\n case __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* ErrorDetails */].KEY_LOAD_ERROR:\n case __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].warn('AudioStreamController: ' + data.details + ' while loading frag, now switching to ' + this.state + ' state ...');\n }\n break;\n case __WEBPACK_IMPORTED_MODULE_6__errors__[\"a\" /* ErrorDetails */].BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {\n var media = this.mediaBuffer,\n currentTime = this.media.currentTime,\n mediaBuffered = media && __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].isBuffered(media, currentTime) && __WEBPACK_IMPORTED_MODULE_1__utils_buffer_helper__[\"a\" /* BufferHelper */].isBuffered(media, currentTime + 0.5);\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n var _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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].warn('AudioStreamController: reduce max buffer length to ' + _config.maxMaxBufferLength + 's');\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 __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].warn('AudioStreamController: 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(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n }\n }\n break;\n default:\n break;\n }\n };\n\n AudioStreamController.prototype.onBufferFlushed = function onBufferFlushed() {\n var _this3 = this;\n\n var pendingData = this.pendingData;\n if (pendingData && pendingData.length) {\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('AudioStreamController: appending pending audio data after buffer flushed');\n pendingData.forEach(function (appendObj) {\n _this3.hls.trigger(__WEBPACK_IMPORTED_MODULE_3__events__[\"a\" /* default */].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\n _createClass(AudioStreamController, [{\n key: 'state',\n set: function set(nextState) {\n if (this.state !== nextState) {\n var previousState = this.state;\n this._state = nextState;\n __WEBPACK_IMPORTED_MODULE_7__utils_logger__[\"b\" /* logger */].log('audio stream:' + previousState + '->' + nextState);\n }\n },\n get: function get() {\n return this._state;\n }\n }]);\n\n return AudioStreamController;\n}(__WEBPACK_IMPORTED_MODULE_9__task_loop__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (AudioStreamController);\n\n/***/ }),\n/* 62 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony export (immutable) */ __webpack_exports__[\"newCue\"] = newCue;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__vttparser__ = __webpack_require__(27);\n\n\nfunction newCue(track, startTime, endTime, captionScreen) {\n var row = void 0;\n var cue = void 0;\n var indenting = void 0;\n var indent = void 0;\n var text = void 0;\n var VTTCue = window.VTTCue || window.TextTrackCue;\n\n for (var r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty()) {\n for (var c = 0; c < row.chars.length; c++) {\n if (row.chars[c].uchar.match(/\\s/) && indenting) {\n indent++;\n } else {\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 endTime += 0.0001;\n }\n\n cue = new VTTCue(startTime, endTime, Object(__WEBPACK_IMPORTED_MODULE_0__vttparser__[\"b\" /* fixLineBreaks */])(text.trim()));\n\n if (indent >= 16) {\n indent--;\n } else {\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 cue.line = r + 1;\n } else {\n cue.line = r > 7 ? r - 2 : r + 1;\n }\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/* 63 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* harmony default export */ __webpack_exports__[\"a\"] = ((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\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\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\n return (/MSIE\\s8\\.0/.test(navigator.userAgent)\n );\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 get() {\n return _id;\n },\n set: function set(value) {\n _id = '' + value;\n }\n }));\n\n Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {\n get: function get() {\n return _pauseOnExit;\n },\n set: function set(value) {\n _pauseOnExit = !!value;\n }\n }));\n\n Object.defineProperty(cue, 'startTime', extend({}, baseObj, {\n get: function get() {\n return _startTime;\n },\n set: function set(value) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n\n _startTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'endTime', extend({}, baseObj, {\n get: function get() {\n return _endTime;\n },\n set: function set(value) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n\n _endTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'text', extend({}, baseObj, {\n get: function get() {\n return _text;\n },\n set: function set(value) {\n _text = '' + value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'region', extend({}, baseObj, {\n get: function get() {\n return _region;\n },\n set: function set(value) {\n _region = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'vertical', extend({}, baseObj, {\n get: function get() {\n return _vertical;\n },\n set: function set(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\n _vertical = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {\n get: function get() {\n return _snapToLines;\n },\n set: function set(value) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'line', extend({}, baseObj, {\n get: function get() {\n return _line;\n },\n set: function set(value) {\n if (typeof value !== 'number' && value !== autoKeyword) {\n throw new SyntaxError('An invalid number or illegal string was specified.');\n }\n\n _line = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {\n get: function get() {\n return _lineAlign;\n },\n set: function set(value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _lineAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'position', extend({}, baseObj, {\n get: function get() {\n return _position;\n },\n set: function set(value) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n\n _position = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {\n get: function get() {\n return _positionAlign;\n },\n set: function set(value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _positionAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'size', extend({}, baseObj, {\n get: function get() {\n return _size;\n },\n set: function set(value) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n\n _size = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'align', extend({}, baseObj, {\n get: function get() {\n return _align;\n },\n set: function set(value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\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/* 64 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_cea_608_parser__ = __webpack_require__(65);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_output_filter__ = __webpack_require__(66);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_webvtt_parser__ = __webpack_require__(67);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_texttrack_utils__ = __webpack_require__(26);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Timeline Controller\n*/\n\n\n\n\n\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\nvar TimelineController = function (_EventHandler) {\n _inherits(TimelineController, _EventHandler);\n\n function TimelineController(hls) {\n _classCallCheck(this, TimelineController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_PARSING_USERDATA, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_DECRYPTED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].LEVEL_SWITCHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 _this.captionsTracks = {};\n\n _this.captionsProperties = {\n textTrack1: {\n label: _this.config.captionsTextTrack1Label,\n languageCode: _this.config.captionsTextTrack1LanguageCode\n },\n textTrack2: {\n label: _this.config.captionsTextTrack2Label,\n languageCode: _this.config.captionsTextTrack2LanguageCode\n }\n };\n\n if (_this.config.enableCEA708Captions) {\n var channel1 = new __WEBPACK_IMPORTED_MODULE_3__utils_output_filter__[\"a\" /* default */](_this, 'textTrack1');\n var channel2 = new __WEBPACK_IMPORTED_MODULE_3__utils_output_filter__[\"a\" /* default */](_this, 'textTrack2');\n\n _this.cea608Parser = new __WEBPACK_IMPORTED_MODULE_2__utils_cea_608_parser__[\"a\" /* default */](0, channel1, channel2);\n }\n return _this;\n }\n\n TimelineController.prototype.addCues = function addCues(trackName, startTime, endTime, screen) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n var ranges = this.cueRanges;\n var merged = false;\n for (var i = ranges.length; i--;) {\n var cueRange = ranges[i];\n var 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\n this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);\n };\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n\n\n TimelineController.prototype.onInitPtsFound = function onInitPtsFound(data) {\n var _this2 = this;\n\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(function (frag) {\n _this2.onFragLoaded(frag);\n });\n this.unparsedVttFrags = [];\n }\n };\n\n TimelineController.prototype.getExistingTrack = function getExistingTrack(trackName) {\n var media = this.media;\n\n if (media) {\n for (var i = 0; i < media.textTracks.length; i++) {\n var textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n };\n\n TimelineController.prototype.createCaptionsTrack = function createCaptionsTrack(trackName) {\n var _captionsProperties$t = this.captionsProperties[trackName],\n label = _captionsProperties$t.label,\n languageCode = _captionsProperties$t.languageCode;\n\n var captionsTracks = this.captionsTracks;\n if (!captionsTracks[trackName]) {\n // Enable reuse of existing text track.\n var existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n var textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n Object(__WEBPACK_IMPORTED_MODULE_6__utils_texttrack_utils__[\"a\" /* clearCurrentCues */])(captionsTracks[trackName]);\n Object(__WEBPACK_IMPORTED_MODULE_6__utils_texttrack_utils__[\"b\" /* sendAddTrackEvent */])(captionsTracks[trackName], this.media);\n }\n }\n };\n\n TimelineController.prototype.createTextTrack = function createTextTrack(kind, label, lang) {\n var media = this.media;\n if (media) {\n return media.addTextTrack(kind, label, lang);\n }\n };\n\n TimelineController.prototype.destroy = function destroy() {\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n TimelineController.prototype.onMediaAttaching = function onMediaAttaching(data) {\n this.media = data.media;\n this._cleanTracks();\n };\n\n TimelineController.prototype.onMediaDetaching = function onMediaDetaching() {\n var captionsTracks = this.captionsTracks;\n\n Object.keys(captionsTracks).forEach(function (trackName) {\n Object(__WEBPACK_IMPORTED_MODULE_6__utils_texttrack_utils__[\"a\" /* clearCurrentCues */])(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n };\n\n TimelineController.prototype.onManifestLoading = function onManifestLoading() {\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 TimelineController.prototype._cleanTracks = function _cleanTracks() {\n // clear outdated subtitles\n var media = this.media;\n if (media) {\n var textTracks = media.textTracks;\n if (textTracks) {\n for (var i = 0; i < textTracks.length; i++) {\n Object(__WEBPACK_IMPORTED_MODULE_6__utils_texttrack_utils__[\"a\" /* clearCurrentCues */])(textTracks[i]);\n }\n }\n }\n };\n\n TimelineController.prototype.onManifestLoaded = function onManifestLoaded(data) {\n var _this3 = this;\n\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 var inUseTracks = this.media ? this.media.textTracks : [];\n\n this.tracks.forEach(function (track, index) {\n var textTrack = void 0;\n if (index < inUseTracks.length) {\n var 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 = _this3.createTextTrack('subtitles', track.name, track.lang);\n }\n\n if (track.default) {\n textTrack.mode = _this3.hls.subtitleDisplay ? 'showing' : 'hidden';\n } else {\n textTrack.mode = 'disabled';\n }\n\n _this3.textTracks.push(textTrack);\n });\n }\n };\n\n TimelineController.prototype.onLevelSwitching = function onLevelSwitching() {\n this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';\n };\n\n TimelineController.prototype.onFragLoaded = function onFragLoaded(data) {\n var 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 var cea608Parser = this.cea608Parser;\n if (cea608Parser) {\n cea608Parser.reset();\n }\n }\n this.lastSn = sn;\n } // eslint-disable-line brace-style\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 } else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n }\n }\n };\n\n TimelineController.prototype._parseVTTs = function _parseVTTs(frag, payload) {\n var 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 var textTracks = this.textTracks,\n hls = this.hls;\n\n // Parse the WebVTT file contents.\n __WEBPACK_IMPORTED_MODULE_4__utils_webvtt_parser__[\"a\" /* default */].parse(payload, this.initPTS, vttCCs, frag.cc, function (cues) {\n var currentTrack = textTracks[frag.trackId];\n // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n if (currentTrack.mode === 'disabled') {\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n return;\n }\n // Add cues and trigger event with success true.\n cues.forEach(function (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 var 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(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });\n }, function (e) {\n // Something went wrong while parsing. Trigger event with success false.\n __WEBPACK_IMPORTED_MODULE_5__utils_logger__[\"b\" /* logger */].log('Failed to parse VTT cue: ' + e);\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n });\n };\n\n TimelineController.prototype.onFragDecrypted = function 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 TimelineController.prototype.onFragParsingUserdata = function 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 TimelineController.prototype.extractCea608Data = function extractCea608Data(byteArray) {\n var count = byteArray[0] & 31;\n var position = 2;\n var tmpByte = void 0,\n ccbyte1 = void 0,\n ccbyte2 = void 0,\n ccValid = void 0,\n ccType = void 0;\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) {\n // || ccType === 1\n actualCCBytes.push(ccbyte1);\n actualCCBytes.push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n };\n\n return TimelineController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (TimelineController);\n\n/***/ }),\n/* 65 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\n/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nvar specialCea608CharsCodes = {\n 0x2a: 0xe1, // lowercase a, acute accent\n 0x5c: 0xe9, // lowercase e, acute accent\n 0x5e: 0xed, // lowercase i, acute accent\n 0x5f: 0xf3, // lowercase o, acute accent\n 0x60: 0xfa, // lowercase u, acute accent\n 0x7b: 0xe7, // lowercase c with cedilla\n 0x7c: 0xf7, // division symbol\n 0x7d: 0xd1, // uppercase N tilde\n 0x7e: 0xf1, // lowercase n tilde\n 0x7f: 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80: 0xae, // Registered symbol (R)\n 0x81: 0xb0, // degree sign\n 0x82: 0xbd, // 1/2 symbol\n 0x83: 0xbf, // Inverted (open) question mark\n 0x84: 0x2122, // Trademark symbol (TM)\n 0x85: 0xa2, // Cents symbol\n 0x86: 0xa3, // Pounds sterling\n 0x87: 0x266a, // Music 8'th note\n 0x88: 0xe0, // lowercase a, grave accent\n 0x89: 0x20, // transparent space (regular)\n 0x8a: 0xe8, // lowercase e, grave accent\n 0x8b: 0xe2, // lowercase a, circumflex accent\n 0x8c: 0xea, // lowercase e, circumflex accent\n 0x8d: 0xee, // lowercase i, circumflex accent\n 0x8e: 0xf4, // lowercase o, circumflex accent\n 0x8f: 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90: 0xc1, // capital letter A with acute\n 0x91: 0xc9, // capital letter E with acute\n 0x92: 0xd3, // capital letter O with acute\n 0x93: 0xda, // capital letter U with acute\n 0x94: 0xdc, // capital letter U with diaresis\n 0x95: 0xfc, // lowercase letter U with diaeresis\n 0x96: 0x2018, // opening single quote\n 0x97: 0xa1, // inverted exclamation mark\n 0x98: 0x2a, // asterisk\n 0x99: 0x2019, // closing single quote\n 0x9a: 0x2501, // box drawings heavy horizontal\n 0x9b: 0xa9, // copyright sign\n 0x9c: 0x2120, // Service mark\n 0x9d: 0x2022, // (round) bullet\n 0x9e: 0x201c, // Left double quotation mark\n 0x9f: 0x201d, // Right double quotation mark\n 0xa0: 0xc0, // uppercase A, grave accent\n 0xa1: 0xc2, // uppercase A, circumflex\n 0xa2: 0xc7, // uppercase C with cedilla\n 0xa3: 0xc8, // uppercase E, grave accent\n 0xa4: 0xca, // uppercase E, circumflex\n 0xa5: 0xcb, // capital letter E with diaresis\n 0xa6: 0xeb, // lowercase letter e with diaresis\n 0xa7: 0xce, // uppercase I, circumflex\n 0xa8: 0xcf, // uppercase I, with diaresis\n 0xa9: 0xef, // lowercase i, with diaresis\n 0xaa: 0xd4, // uppercase O, circumflex\n 0xab: 0xd9, // uppercase U, grave accent\n 0xac: 0xf9, // lowercase u, grave accent\n 0xad: 0xdb, // uppercase U, circumflex\n 0xae: 0xab, // left-pointing double angle quotation mark\n 0xaf: 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0: 0xc3, // Uppercase A, tilde\n 0xb1: 0xe3, // Lowercase a, tilde\n 0xb2: 0xcd, // Uppercase I, acute accent\n 0xb3: 0xcc, // Uppercase I, grave accent\n 0xb4: 0xec, // Lowercase i, grave accent\n 0xb5: 0xd2, // Uppercase O, grave accent\n 0xb6: 0xf2, // Lowercase o, grave accent\n 0xb7: 0xd5, // Uppercase O, tilde\n 0xb8: 0xf5, // Lowercase o, tilde\n 0xb9: 0x7b, // Open curly brace\n 0xba: 0x7d, // Closing curly brace\n 0xbb: 0x5c, // Backslash\n 0xbc: 0x5e, // Caret\n 0xbd: 0x5f, // Underscore\n 0xbe: 0x7c, // Pipe (vertical line)\n 0xbf: 0x223c, // Tilde operator\n 0xc0: 0xc4, // Uppercase A, umlaut\n 0xc1: 0xe4, // Lowercase A, umlaut\n 0xc2: 0xd6, // Uppercase O, umlaut\n 0xc3: 0xf6, // Lowercase o, umlaut\n 0xc4: 0xdf, // Esszett (sharp S)\n 0xc5: 0xa5, // Yen symbol\n 0xc6: 0xa4, // Generic currency sign\n 0xc7: 0x2503, // Box drawings heavy vertical\n 0xc8: 0xc5, // Uppercase A, ring\n 0xc9: 0xe5, // Lowercase A, ring\n 0xca: 0xd8, // Uppercase O, stroke\n 0xcb: 0xf8, // Lowercase o, strok\n 0xcc: 0x250f, // Box drawings heavy down and right\n 0xcd: 0x2513, // Box drawings heavy down and left\n 0xce: 0x2517, // Box drawings heavy up and right\n 0xcf: 0x251b // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nvar getCharForByte = function getCharForByte(byte) {\n var charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\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 setTime(newTime) {\n this.time = newTime;\n },\n log: function log(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 numArrayToHexArray(numArray) {\n var hexArray = [];\n for (var j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\nvar PenState = function () {\n function PenState(foreground, underline, italics, background, flash) {\n _classCallCheck(this, PenState);\n\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 PenState.prototype.reset = function reset() {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n };\n\n PenState.prototype.setStyles = function 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 PenState.prototype.isDefault = function isDefault() {\n return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;\n };\n\n PenState.prototype.equals = function equals(other) {\n return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;\n };\n\n PenState.prototype.copy = function 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 PenState.prototype.toString = function toString() {\n return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;\n };\n\n return PenState;\n}();\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\n\n\nvar StyledUnicodeChar = function () {\n function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {\n _classCallCheck(this, StyledUnicodeChar);\n\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(foreground, underline, italics, background, flash);\n }\n\n StyledUnicodeChar.prototype.reset = function reset() {\n this.uchar = ' ';\n this.penState.reset();\n };\n\n StyledUnicodeChar.prototype.setChar = function setChar(uchar, newPenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n };\n\n StyledUnicodeChar.prototype.setPenState = function setPenState(newPenState) {\n this.penState.copy(newPenState);\n };\n\n StyledUnicodeChar.prototype.equals = function equals(other) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n };\n\n StyledUnicodeChar.prototype.copy = function copy(newChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n };\n\n StyledUnicodeChar.prototype.isEmpty = function isEmpty() {\n return this.uchar === ' ' && this.penState.isDefault();\n };\n\n return StyledUnicodeChar;\n}();\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\n\n\nvar Row = function () {\n function Row() {\n _classCallCheck(this, Row);\n\n this.chars = [];\n for (var i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n Row.prototype.equals = function 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 Row.prototype.copy = function copy(other) {\n for (var i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n };\n\n Row.prototype.isEmpty = function 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\n\n Row.prototype.setCursor = function setCursor(absPos) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\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\n\n Row.prototype.moveCursor = function 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\n\n Row.prototype.backSpace = function backSpace() {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n };\n\n Row.prototype.insertChar = function insertChar(byte) {\n if (byte >= 0x90) {\n // 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) + ' (' + 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 Row.prototype.clearFromPos = function clearFromPos(startPos) {\n var i = void 0;\n for (i = startPos; i < NR_COLS; i++) {\n this.chars[i].reset();\n }\n };\n\n Row.prototype.clear = function clear() {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n };\n\n Row.prototype.clearToEndOfRow = function clearToEndOfRow() {\n this.clearFromPos(this.pos);\n };\n\n Row.prototype.getTextString = function 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\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n };\n\n Row.prototype.setPenStyles = function setPenStyles(styles) {\n this.currPenState.setStyles(styles);\n var currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n };\n\n return Row;\n}();\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n*/\n\n\nvar CaptionScreen = function () {\n function CaptionScreen() {\n _classCallCheck(this, CaptionScreen);\n\n this.rows = [];\n for (var i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row());\n } // 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 CaptionScreen.prototype.reset = function reset() {\n for (var i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n };\n\n CaptionScreen.prototype.equals = function 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 CaptionScreen.prototype.copy = function copy(other) {\n for (var i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n };\n\n CaptionScreen.prototype.isEmpty = function 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 CaptionScreen.prototype.backSpace = function backSpace() {\n var row = this.rows[this.currRow];\n row.backSpace();\n };\n\n CaptionScreen.prototype.clearToEndOfRow = function 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\n\n CaptionScreen.prototype.insertChar = function insertChar(char) {\n var row = this.rows[this.currRow];\n row.insertChar(char);\n };\n\n CaptionScreen.prototype.setPen = function setPen(styles) {\n var row = this.rows[this.currRow];\n row.setPenStyles(styles);\n };\n\n CaptionScreen.prototype.moveCursor = function moveCursor(relPos) {\n var row = this.rows[this.currRow];\n row.moveCursor(relPos);\n };\n\n CaptionScreen.prototype.setCursor = function setCursor(absPos) {\n logger.log('INFO', 'setCursor: ' + absPos);\n var row = this.rows[this.currRow];\n row.setCursor(absPos);\n };\n\n CaptionScreen.prototype.setPAC = function 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 (var i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n // topRowIndex - the start of rows to copy (inclusive index)\n var topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n var lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n if (prevLineTime && prevLineTime < logger.time) {\n for (var _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\n\n CaptionScreen.prototype.setBkgData = function setBkgData(bkgData) {\n logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); // Space\n };\n\n CaptionScreen.prototype.setRollUpRows = function setRollUpRows(nrRows) {\n this.nrRollUpRows = nrRows;\n };\n\n CaptionScreen.prototype.rollUp = function 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\n\n CaptionScreen.prototype.getDisplayText = function 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 CaptionScreen.prototype.getTextAndFormat = function getTextAndFormat() {\n return this.rows;\n };\n\n return CaptionScreen;\n}();\n\n// var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\nvar Cea608Channel = function () {\n function Cea608Channel(channelNumber, outputFilter) {\n _classCallCheck(this, Cea608Channel);\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 Cea608Channel.prototype.reset = function 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 Cea608Channel.prototype.getHandler = function getHandler() {\n return this.outputFilter;\n };\n\n Cea608Channel.prototype.setHandler = function setHandler(newHandler) {\n this.outputFilter = newHandler;\n };\n\n Cea608Channel.prototype.setPAC = function setPAC(pacData) {\n this.writeScreen.setPAC(pacData);\n };\n\n Cea608Channel.prototype.setBkgData = function setBkgData(bkgData) {\n this.writeScreen.setBkgData(bkgData);\n };\n\n Cea608Channel.prototype.setMode = function setMode(newMode) {\n if (newMode === this.mode) {\n return;\n }\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 Cea608Channel.prototype.insertChars = function insertChars(chars) {\n for (var i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\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 Cea608Channel.prototype.ccRCL = function ccRCL() {\n // 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 Cea608Channel.prototype.ccBS = function ccBS() {\n // BackSpace\n logger.log('INFO', 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n };\n\n Cea608Channel.prototype.ccAOF = function ccAOF() {// Reserved (formerly Alarm Off)\n\n };\n\n Cea608Channel.prototype.ccAON = function ccAON() {// Reserved (formerly Alarm On)\n\n };\n\n Cea608Channel.prototype.ccDER = function ccDER() {\n // 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 Cea608Channel.prototype.ccRU = function ccRU(nrRows) {\n // 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 Cea608Channel.prototype.ccFON = function ccFON() {\n // Flash On\n logger.log('INFO', 'FON - Flash On');\n this.writeScreen.setPen({ flash: true });\n };\n\n Cea608Channel.prototype.ccRDC = function ccRDC() {\n // Resume Direct Captioning (switch mode to PaintOn)\n logger.log('INFO', 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n };\n\n Cea608Channel.prototype.ccTR = function ccTR() {\n // Text Restart in text mode (not supported, however)\n logger.log('INFO', 'TR');\n this.setMode('MODE_TEXT');\n };\n\n Cea608Channel.prototype.ccRTD = function ccRTD() {\n // Resume Text Display in Text mode (not supported, however)\n logger.log('INFO', 'RTD');\n this.setMode('MODE_TEXT');\n };\n\n Cea608Channel.prototype.ccEDM = function ccEDM() {\n // Erase Displayed Memory\n logger.log('INFO', 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n };\n\n Cea608Channel.prototype.ccCR = function ccCR() {\n // Carriage Return\n logger.log('CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n };\n\n Cea608Channel.prototype.ccENM = function ccENM() {\n // Erase Non-Displayed Memory\n logger.log('INFO', 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n };\n\n Cea608Channel.prototype.ccEOC = function ccEOC() {\n // 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 Cea608Channel.prototype.ccTO = function ccTO(nrCols) {\n // Tab Offset 1,2, or 3 columns\n logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n };\n\n Cea608Channel.prototype.ccMIDROW = function ccMIDROW(secondByte) {\n // 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 Cea608Channel.prototype.outputDataUpdate = function outputDataUpdate() {\n var dispatch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n\n var t = logger.time;\n if (t === null) {\n return;\n }\n\n if (this.outputFilter) {\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {\n // 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 Cea608Channel.prototype.cueSplitAtTime = function 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\n this.cueStartTime = t;\n }\n }\n };\n\n return Cea608Channel;\n}();\n\nvar Cea608Parser = function () {\n function Cea608Parser(field, out1, out2) {\n _classCallCheck(this, Cea608Parser);\n\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 Cea608Parser.prototype.getHandler = function getHandler(index) {\n return this.channels[index].getHandler();\n };\n\n Cea608Parser.prototype.setHandler = function 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\n\n Cea608Parser.prototype.addData = function addData(t, byteList) {\n var cmdFound = void 0,\n a = void 0,\n b = void 0,\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\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\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]) + ' 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\n\n Cea608Parser.prototype.parseCmd = function parseCmd(a, b) {\n var chNr = null;\n\n var cond1 = (a === 0x14 || a === 0x1C) && b >= 0x20 && b <= 0x2F;\n var cond2 = (a === 0x17 || a === 0x1F) && b >= 0x21 && 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;\n } // (a === 0x1C || a=== 0x1f)\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 {\n // 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\n\n Cea608Parser.prototype.parseMidrow = function parseMidrow(a, b) {\n var chNr = null;\n\n if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\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\n\n Cea608Parser.prototype.parsePAC = function parsePAC(a, b) {\n var chNr = null;\n var row = null;\n\n var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1F) && b >= 0x40 && b <= 0x7F;\n var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && 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 (b >= 0x40 && b <= 0x5F) {\n row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];\n } else {\n // 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\n\n Cea608Parser.prototype.interpretPAC = function 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\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\n\n Cea608Parser.prototype.parseChars = function parseChars(a, b) {\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 (charCode1 >= 0x11 && 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\n logger.log('INFO', 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n charCodes = [oneCode];\n } else if (a >= 0x20 && 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\n\n Cea608Parser.prototype.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {\n var bkgData = void 0,\n index = void 0,\n chNr = void 0,\n channel = void 0;\n\n var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;\n var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;\n if (!(case1 || case2)) {\n return false;\n }\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\n\n Cea608Parser.prototype.reset = function 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\n\n Cea608Parser.prototype.cueSplitAtTime = function 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 return Cea608Parser;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (Cea608Parser);\n\n/***/ }),\n/* 66 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar OutputFilter = function () {\n function OutputFilter(timelineController, trackName) {\n _classCallCheck(this, OutputFilter);\n\n this.timelineController = timelineController;\n this.trackName = trackName;\n this.startTime = null;\n this.endTime = null;\n this.screen = null;\n }\n\n OutputFilter.prototype.dispatchCue = function dispatchCue() {\n if (this.startTime === null) {\n return;\n }\n\n this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen);\n this.startTime = null;\n };\n\n OutputFilter.prototype.newCue = function newCue(startTime, endTime, screen) {\n if (this.startTime === null || this.startTime > startTime) {\n this.startTime = startTime;\n }\n\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\n };\n\n return OutputFilter;\n}();\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (OutputFilter);\n\n/***/ }),\n/* 67 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__vttparser__ = __webpack_require__(27);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__demux_id3__ = __webpack_require__(7);\n\n\n\n// String.prototype.startsWith is not supported in IE11\nvar startsWith = function startsWith(inputString, searchString, position) {\n return inputString.substr(position || 0, searchString.length) === searchString;\n};\n\nvar cueString2millis = function cueString2millis(timeString) {\n var ts = parseInt(timeString.substr(-3));\n var secs = parseInt(timeString.substr(-6, 2));\n var mins = parseInt(timeString.substr(-9, 2));\n var 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\nvar hash = function hash(text) {\n var hash = 5381;\n var i = text.length;\n while (i) {\n hash = hash * 33 ^ text.charCodeAt(--i);\n }\n\n return (hash >>> 0).toString();\n};\n\nvar calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {\n var currCC = vttCCs[cc];\n var 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\nvar WebVTTParser = {\n parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n var re = /\\r\\n|\\n\\r|\\n|\\r/g;\n // Uint8Array.prototype.reduce is not implemented in IE11\n var vttLines = Object(__WEBPACK_IMPORTED_MODULE_1__demux_id3__[\"b\" /* utf8ArrayToStr */])(new Uint8Array(vttByteArray)).trim().replace(re, '\\n').split('\\n');\n\n var cueTime = '00:00.000';\n var mpegTs = 0;\n var localTime = 0;\n var presentationTime = 0;\n var cues = [];\n var parsingError = void 0;\n var inHeader = true;\n // let VTTCue = VTTCue || window.TextTrackCue;\n\n // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.\n var parser = new __WEBPACK_IMPORTED_MODULE_0__vttparser__[\"a\" /* default */]();\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 var currCC = vttCCs[cc];\n var 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(function (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(function (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 } catch (e) {\n parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line + '\\n');\n });\n\n parser.flush();\n }\n};\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (WebVTTParser);\n\n/***/ }),\n/* 68 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * subtitle track controller\n*/\n\n\n\n\n\nfunction filterSubtitleTracks(textTrackList) {\n var tracks = [];\n for (var i = 0; i < textTrackList.length; i++) {\n if (textTrackList[i].kind === 'subtitles') {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nvar SubtitleTrackController = function (_EventHandler) {\n _inherits(SubtitleTrackController, _EventHandler);\n\n function SubtitleTrackController(hls) {\n _classCallCheck(this, SubtitleTrackController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_DETACHING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADING, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MANIFEST_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_LOADED));\n\n _this.tracks = [];\n _this.trackId = -1;\n _this.media = null;\n\n /**\n * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering\n */\n _this.subtitleDisplay = true;\n return _this;\n }\n\n SubtitleTrackController.prototype._onTextTracksChanged = function _onTextTracksChanged() {\n // Media is undefined when switching streams via loadSource()\n if (!this.media) {\n return;\n }\n\n var trackId = -1;\n var tracks = filterSubtitleTracks(this.media.textTracks);\n for (var id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n this.subtitleTrack = trackId;\n };\n\n SubtitleTrackController.prototype.destroy = function destroy() {\n __WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */].prototype.destroy.call(this);\n };\n\n // Listen for subtitle track change, then extract the current track ID.\n\n\n SubtitleTrackController.prototype.onMediaAttached = function onMediaAttached(data) {\n var _this2 = this;\n\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n if (this.queuedDefaultTrack) {\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(function () {\n _this2.trackChangeListener();\n }, 500);\n } else {\n this.media.textTracks.addEventListener('change', this.trackChangeListener);\n }\n };\n\n SubtitleTrackController.prototype.onMediaDetaching = function onMediaDetaching() {\n if (!this.media) {\n return;\n }\n\n if (this.useTextTrackPolling) {\n clearInterval(this.subtitlePollingInterval);\n } else {\n this.media.textTracks.removeEventListener('change', this.trackChangeListener);\n }\n\n this.media = null;\n };\n\n // Reset subtitle tracks on manifest loading\n\n\n SubtitleTrackController.prototype.onManifestLoading = function onManifestLoading() {\n this.tracks = [];\n this.trackId = -1;\n };\n\n // Fired whenever a new manifest is loaded.\n\n\n SubtitleTrackController.prototype.onManifestLoaded = function onManifestLoaded(data) {\n var _this3 = this;\n\n var tracks = data.subtitles || [];\n this.tracks = tracks;\n this.trackId = -1;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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(function (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 (_this3.media) {\n _this3.subtitleTrack = track.id;\n } else {\n _this3.queuedDefaultTrack = track.id;\n }\n }\n });\n };\n\n // Trigger subtitle track playlist reload.\n\n\n SubtitleTrackController.prototype.onTick = function onTick() {\n var trackId = this.trackId;\n var subtitleTrack = this.tracks[trackId];\n if (!subtitleTrack) {\n return;\n }\n\n var details = subtitleTrack.details;\n // check if we need to load playlist for this subtitle Track\n if (!details || details.live) {\n // track not retrieved yet, or live playlist we need to (re)load it\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('(re)loading playlist for subtitle track ' + trackId);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: trackId });\n }\n };\n\n SubtitleTrackController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(data) {\n var _this4 = this;\n\n if (data.id < this.tracks.length) {\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* 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(function () {\n _this4.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 this._stopTimer();\n }\n }\n };\n\n /** get alternate subtitle tracks list from playlist **/\n\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n * @param newId - The id of the subtitle track to activate.\n */\n SubtitleTrackController.prototype.setSubtitleTrackInternal = function setSubtitleTrackInternal(newId) {\n var hls = this.hls,\n tracks = this.tracks;\n\n if (typeof newId !== 'number' || newId < -1 || newId >= tracks.length) {\n return;\n }\n\n this._stopTimer();\n this.trackId = newId;\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('switching to subtitle track ' + newId);\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_SWITCH, { id: newId });\n if (newId === -1) {\n return;\n }\n\n // check if we need to load playlist for this subtitle Track\n var subtitleTrack = tracks[newId];\n var details = subtitleTrack.details;\n if (!details || details.live) {\n // track not retrieved yet, or live playlist we need to (re)load it\n __WEBPACK_IMPORTED_MODULE_2__utils_logger__[\"b\" /* logger */].log('(re)loading playlist for subtitle track ' + newId);\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId });\n }\n };\n\n SubtitleTrackController.prototype._stopTimer = function _stopTimer() {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n };\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n * @param newId - The id of the next track to enable\n * @private\n */\n\n\n SubtitleTrackController.prototype._toggleTrackModes = function _toggleTrackModes(newId) {\n var media = this.media,\n subtitleDisplay = this.subtitleDisplay,\n trackId = this.trackId;\n\n if (!media) {\n return;\n }\n\n var textTracks = filterSubtitleTracks(media.textTracks);\n if (newId === -1) {\n [].slice.call(textTracks).forEach(function (track) {\n track.mode = 'disabled';\n });\n } else {\n var oldTrack = textTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n var nextTrack = textTracks[newId];\n if (nextTrack) {\n nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';\n }\n };\n\n _createClass(SubtitleTrackController, [{\n key: 'subtitleTracks',\n get: function get() {\n return this.tracks;\n }\n\n /** get index of the selected subtitle track (index in subtitle track lists) **/\n\n }, {\n key: 'subtitleTrack',\n get: function get() {\n return this.trackId;\n }\n\n /** select a subtitle track, based on its index in subtitle track lists**/\n ,\n set: function set(subtitleTrackId) {\n if (this.trackId !== subtitleTrackId) {\n this._toggleTrackModes(subtitleTrackId);\n this.setSubtitleTrackInternal(subtitleTrackId);\n }\n }\n }]);\n\n return SubtitleTrackController;\n}(__WEBPACK_IMPORTED_MODULE_1__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (SubtitleTrackController);\n\n/***/ }),\n/* 69 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_logger__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__crypt_decrypter__ = __webpack_require__(13);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__task_loop__ = __webpack_require__(8);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/*\n * Subtitle Stream Controller\n*/\n\n\n\n\n\n\nvar _window = window,\n performance = _window.performance;\n\n\nvar State = {\n STOPPED: 'STOPPED',\n IDLE: 'IDLE',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING'\n};\n\nvar SubtitleStreamController = function (_TaskLoop) {\n _inherits(SubtitleStreamController, _TaskLoop);\n\n function SubtitleStreamController(hls) {\n _classCallCheck(this, SubtitleStreamController);\n\n var _this = _possibleConstructorReturn(this, _TaskLoop.call(this, hls, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].MEDIA_ATTACHED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].ERROR, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].KEY_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACKS_UPDATED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_SWITCH, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_TRACK_LOADED, __WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].SUBTITLE_FRAG_PROCESSED));\n\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.decrypter = new __WEBPACK_IMPORTED_MODULE_2__crypt_decrypter__[\"a\" /* default */](hls.observer, hls.config);\n return _this;\n }\n\n SubtitleStreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {\n this.state = State.STOPPED;\n };\n\n // Remove all queued items and create a new, empty queue for each track.\n\n\n SubtitleStreamController.prototype.clearVttFragQueues = function clearVttFragQueues() {\n var _this2 = this;\n\n this.vttFragQueues = {};\n this.tracks.forEach(function (track) {\n _this2.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\n\n SubtitleStreamController.prototype.nextFrag = function nextFrag() {\n if (this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) {\n var frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift();\n this.fragCurrent = frag;\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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\n\n SubtitleStreamController.prototype.onSubtitleFragProcessed = function onSubtitleFragProcessed(data) {\n if (data.success) {\n this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn);\n }\n\n this.currentlyProcessing = null;\n this.state = State.IDLE;\n this.nextFrag();\n };\n\n SubtitleStreamController.prototype.onMediaAttached = function onMediaAttached() {\n this.state = State.IDLE;\n };\n\n // If something goes wrong, procede to next frag, if we were processing one.\n\n\n SubtitleStreamController.prototype.onError = function onError(data) {\n var frag = data.frag;\n // don't handle frag error not related to subtitle fragment\n if (frag && frag.type !== 'subtitle') {\n return;\n }\n\n if (this.currentlyProcessing) {\n this.currentlyProcessing = null;\n this.nextFrag();\n }\n };\n\n SubtitleStreamController.prototype.doTick = function doTick() {\n var _this3 = this;\n\n switch (this.state) {\n case State.IDLE:\n var tracks = this.tracks;\n var trackId = this.currentTrackId;\n\n var processedFragSNs = this.vttFragSNsProcessed[trackId],\n fragQueue = this.vttFragQueues[trackId],\n currentFragSN = this.currentlyProcessing ? this.currentlyProcessing.sn : -1;\n\n var alreadyProcessed = function alreadyProcessed(frag) {\n return processedFragSNs.indexOf(frag.sn) > -1;\n };\n\n var alreadyInQueue = function alreadyInQueue(frag) {\n return fragQueue.some(function (fragInQueue) {\n return fragInQueue.sn === frag.sn;\n });\n };\n\n // exit if tracks don't exist\n if (!tracks) {\n break;\n }\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(function (frag) {\n if (!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) {\n // Load key if subtitles are encrypted\n if (frag.encrypted) {\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('Loading key for ' + frag.sn);\n _this3.state = State.KEY_LOADING;\n _this3.hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].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 _this3.nextFrag();\n }\n }\n });\n }\n };\n\n // Got all new subtitle tracks.\n\n\n SubtitleStreamController.prototype.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(data) {\n var _this4 = this;\n\n __WEBPACK_IMPORTED_MODULE_1__utils_logger__[\"b\" /* logger */].log('subtitle tracks updated');\n this.tracks = data.subtitleTracks;\n this.clearVttFragQueues();\n this.vttFragSNsProcessed = {};\n this.tracks.forEach(function (track) {\n _this4.vttFragSNsProcessed[track.id] = [];\n });\n };\n\n SubtitleStreamController.prototype.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(data) {\n this.currentTrackId = data.id;\n if (!this.tracks || this.currentTrackId === -1) {\n return;\n }\n\n // Check if track was already loaded and if so make sure we finish\n // downloading its frags, if not all have been downloaded yet\n var currentTrack = this.tracks[this.currentTrackId];\n if (currentTrack && currentTrack.details) {\n this.tick();\n }\n };\n\n // Got a new set of subtitle fragments.\n\n\n SubtitleStreamController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded() {\n this.tick();\n };\n\n SubtitleStreamController.prototype.onKeyLoaded = function onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n };\n\n SubtitleStreamController.prototype.onFragLoaded = function onFragLoaded(data) {\n var fragCurrent = this.fragCurrent,\n decryptData = data.frag.decryptdata;\n var fragLoaded = data.frag,\n hls = this.hls;\n if (this.state === State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && 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 = void 0;\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 = void 0;\n try {\n endTime = performance.now();\n } catch (error) {\n endTime = Date.now();\n }\n hls.trigger(__WEBPACK_IMPORTED_MODULE_0__events__[\"a\" /* default */].FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });\n });\n }\n }\n };\n\n return SubtitleStreamController;\n}(__WEBPACK_IMPORTED_MODULE_3__task_loop__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (SubtitleStreamController);\n\n/***/ }),\n/* 70 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__event_handler__ = __webpack_require__(3);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__errors__ = __webpack_require__(2);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_logger__ = __webpack_require__(0);\nvar _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; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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; }\n\nfunction _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; }\n\n/**\n * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n *\n * DRM support for Hls.js\n */\n\n\n\n\n\n\n\nvar _window = window,\n XMLHttpRequest = _window.XMLHttpRequest;\n\n\nvar MAX_LICENSE_REQUEST_FAILURES = 3;\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nvar KeySystems = {\n WIDEVINE: 'com.widevine.alpha',\n PLAYREADY: 'com.microsoft.playready'\n};\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @param {object} drmSystemOptions Optional parameters/requirements for the key-system\n * @returns {Array<MediaSystemConfiguration>} An array of supported configurations\n */\n\nvar createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {\n /* jshint ignore:line */\n var baseConfig = {\n // initDataTypes: ['keyids', 'mp4'],\n // label: \"\",\n // persistentState: \"not-allowed\", // or \"required\" ?\n // distinctiveIdentifier: \"not-allowed\", // or \"required\" ?\n // sessionTypes: ['temporary'],\n videoCapabilities: [\n // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n ]\n };\n\n videoCodecs.forEach(function (codec) {\n baseConfig.videoCapabilities.push({\n contentType: 'video/mp4; codecs=\"' + codec + '\"'\n });\n });\n\n return [baseConfig];\n};\n\n/**\n * The idea here is to handle key-system (and their respective platforms) specific configuration differences\n * in order to work with the local requestMediaKeySystemAccess method.\n *\n * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`\n */\nvar getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs) {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);\n default:\n throw Error('Unknown key-system: ' + keySystem);\n }\n};\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\n\nvar EMEController = function (_EventHandler) {\n _inherits(EMEController, _EventHandler);\n\n /**\n * @constructs\n * @param {Hls} hls Our Hls.js instance\n */\n function EMEController(hls) {\n _classCallCheck(this, EMEController);\n\n var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, __WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].MEDIA_ATTACHED, __WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].MANIFEST_PARSED));\n\n _this._widevineLicenseUrl = hls.config.widevineLicenseUrl;\n _this._licenseXhrSetup = hls.config.licenseXhrSetup;\n _this._emeEnabled = hls.config.emeEnabled;\n\n _this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;\n\n _this._mediaKeysList = [];\n _this._media = null;\n\n _this._hasSetMediaKeys = false;\n _this._isMediaEncrypted = false;\n\n _this._requestLicenseFailureCount = 0;\n return _this;\n }\n\n /**\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @returns {string} License server URL for key-system (if any configured, otherwise causes error)\n */\n\n\n EMEController.prototype.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {\n var url = void 0;\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n url = this._widevineLicenseUrl;\n break;\n default:\n url = null;\n break;\n }\n\n if (!url) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('No license server URL configured for key-system \"' + keySystem + '\"');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].KEY_SYSTEM_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n\n return url;\n };\n\n /**\n * Requests access object and adds it to our list upon success\n * @private\n * @param {string} keySystem System ID (see `KeySystems`)\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n */\n\n\n EMEController.prototype._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {\n var _this2 = this;\n\n // TODO: add other DRM \"options\"\n\n var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);\n\n if (!mediaKeySystemConfigs) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);\n return;\n }\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Requesting encrypted media key-system access');\n\n // expecting interface like window.navigator.requestMediaKeySystemAccess\n this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs).then(function (mediaKeySystemAccess) {\n _this2._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);\n }).catch(function (err) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Failed to obtain key-system \"' + keySystem + '\" access:', err);\n });\n };\n\n /**\n * Handles obtaining access to a key-system\n *\n * @param {string} keySystem\n * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess\n */\n EMEController.prototype._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {\n var _this3 = this;\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Access for key-system \"' + keySystem + '\" obtained');\n\n var mediaKeysListItem = {\n mediaKeys: null,\n mediaKeysSession: null,\n mediaKeysSessionInitialized: false,\n mediaKeySystemAccess: mediaKeySystemAccess,\n mediaKeySystemDomain: keySystem\n };\n\n this._mediaKeysList.push(mediaKeysListItem);\n\n mediaKeySystemAccess.createMediaKeys().then(function (mediaKeys) {\n mediaKeysListItem.mediaKeys = mediaKeys;\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Media-keys created for key-system \"' + keySystem + '\"');\n\n _this3._onMediaKeysCreated();\n }).catch(function (err) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Failed to create media-keys:', err);\n });\n };\n\n /**\n * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this\n * for all existing keys where no session exists yet.\n */\n\n\n EMEController.prototype._onMediaKeysCreated = function _onMediaKeysCreated() {\n var _this4 = this;\n\n // check for all key-list items if a session exists, otherwise, create one\n this._mediaKeysList.forEach(function (mediaKeysListItem) {\n if (!mediaKeysListItem.mediaKeysSession) {\n mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();\n _this4._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);\n }\n });\n };\n\n /**\n *\n * @param {*} keySession\n */\n\n\n EMEController.prototype._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {\n var _this5 = this;\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('New key-system session ' + keySession.sessionId);\n\n keySession.addEventListener('message', function (event) {\n _this5._onKeySessionMessage(keySession, event.message);\n }, false);\n };\n\n EMEController.prototype._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Got EME message event, creating license request');\n\n this._requestLicense(message, function (data) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Received license data, updating key-session');\n keySession.update(data);\n });\n };\n\n EMEController.prototype._onMediaEncrypted = function _onMediaEncrypted(initDataType, initData) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Media is encrypted using \"' + initDataType + '\" init data type');\n\n this._isMediaEncrypted = true;\n this._mediaEncryptionInitDataType = initDataType;\n this._mediaEncryptionInitData = initData;\n\n this._attemptSetMediaKeys();\n this._generateRequestWithPreferredKeySession();\n };\n\n EMEController.prototype._attemptSetMediaKeys = function _attemptSetMediaKeys() {\n if (!this._hasSetMediaKeys) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n var keysListItem = this._mediaKeysList[0];\n if (!keysListItem || !keysListItem.mediaKeys) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].KEY_SYSTEM_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_SYSTEM_NO_KEYS,\n fatal: true\n });\n return;\n }\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Setting keys for encrypted media');\n\n this._media.setMediaKeys(keysListItem.mediaKeys);\n this._hasSetMediaKeys = true;\n }\n };\n\n EMEController.prototype._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession() {\n var _this6 = this;\n\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n var keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Fatal: Media is encrypted but not any key-system access has been obtained yet');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].KEY_SYSTEM_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n if (keysListItem.mediaKeysSessionInitialized) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].warn('Key-Session already initialized but requested again');\n return;\n }\n\n var keySession = keysListItem.mediaKeysSession;\n if (!keySession) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Fatal: Media is encrypted but no key-session existing');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].KEY_SYSTEM_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_SYSTEM_NO_SESSION,\n fatal: true\n });\n }\n\n var initDataType = this._mediaEncryptionInitDataType;\n var initData = this._mediaEncryptionInitData;\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Generating key-session request for \"' + initDataType + '\" init data type');\n\n keysListItem.mediaKeysSessionInitialized = true;\n\n keySession.generateRequest(initDataType, initData).then(function () {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].debug('Key-session generation succeeded');\n }).catch(function (err) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Error generating key-session request:', err);\n _this6.hls.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].KEY_SYSTEM_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_SYSTEM_NO_SESSION,\n fatal: false\n });\n });\n };\n\n /**\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n * @returns {XMLHttpRequest} Unsent (but opened state) XHR object\n */\n\n\n EMEController.prototype._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {\n var xhr = new XMLHttpRequest();\n var licenseXhrSetup = this._licenseXhrSetup;\n\n try {\n if (licenseXhrSetup) {\n try {\n licenseXhrSetup(xhr, url);\n } catch (e) {\n // let's try to open before running setup\n xhr.open('POST', url, true);\n licenseXhrSetup(xhr, url);\n }\n }\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Error setting up key-system license XHR', e);\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].KEY_SYSTEM_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n return;\n }\n\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);\n return xhr;\n };\n\n /**\n * @param {XMLHttpRequest} xhr\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n *\n */\n\n\n EMEController.prototype._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {\n switch (xhr.readyState) {\n case 4:\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('License request succeeded');\n callback(xhr.response);\n } else {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('License Request XHR failed (' + url + '). Status: ' + xhr.status + ' (' + xhr.statusText + ')');\n\n this._requestLicenseFailureCount++;\n if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {\n var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].warn('Retrying license request, ' + attemptsLeft + ' attempts left');\n this._requestLicense(keyMessage, callback);\n return;\n }\n\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].KEY_SYSTEM_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n break;\n }\n };\n\n /**\n * @param {object} keysListItem\n * @param {ArrayBuffer} keyMessage\n * @returns {ArrayBuffer} Challenge data posted to license server\n */\n\n\n EMEController.prototype._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {\n var challenge = void 0;\n\n if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('PlayReady is not supported (yet)');\n\n // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js\n /*\n if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');\n if (keyMessageXml.getElementsByTagName('Challenge')[0]) {\n challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);\n } else {\n throw 'Cannot find <Challenge> in key message';\n }\n var headerNames = keyMessageXml.getElementsByTagName('name');\n var headerValues = keyMessageXml.getElementsByTagName('value');\n if (headerNames.length !== headerValues.length) {\n throw 'Mismatched header <name>/<value> pair in key message';\n }\n for (var i = 0; i < headerNames.length; i++) {\n xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);\n }\n }\n */\n } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {\n // For Widevine CDMs, the challenge is the keyMessage.\n challenge = keyMessage;\n } else {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);\n }\n\n return challenge;\n };\n\n EMEController.prototype._requestLicense = function _requestLicense(keyMessage, callback) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Requesting content license for key-system');\n\n var keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].error('Fatal error: Media is encrypted but no key-system access has been obtained yet');\n this.hls.trigger(__WEBPACK_IMPORTED_MODULE_1__events__[\"a\" /* default */].ERROR, {\n type: __WEBPACK_IMPORTED_MODULE_2__errors__[\"b\" /* ErrorTypes */].KEY_SYSTEM_ERROR,\n details: __WEBPACK_IMPORTED_MODULE_2__errors__[\"a\" /* ErrorDetails */].KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n var url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);\n var xhr = this._createLicenseXhr(url, keyMessage, callback);\n\n __WEBPACK_IMPORTED_MODULE_3__utils_logger__[\"b\" /* logger */].log('Sending license request to URL: ' + url);\n\n xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));\n };\n\n EMEController.prototype.onMediaAttached = function onMediaAttached(data) {\n var _this7 = this;\n\n if (!this._emeEnabled) {\n return;\n }\n\n var media = data.media;\n\n // keep reference of media\n this._media = media;\n\n // FIXME: also handle detaching media !\n\n media.addEventListener('encrypted', function (e) {\n _this7._onMediaEncrypted(e.initDataType, e.initData);\n });\n };\n\n EMEController.prototype.onManifestParsed = function onManifestParsed(data) {\n if (!this._emeEnabled) {\n return;\n }\n\n var audioCodecs = data.levels.map(function (level) {\n return level.audioCodec;\n });\n var videoCodecs = data.levels.map(function (level) {\n return level.videoCodec;\n });\n\n this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);\n };\n\n _createClass(EMEController, [{\n key: 'requestMediaKeySystemAccess',\n get: function get() {\n if (!this._requestMediaKeySystemAccess) {\n throw new Error('No requestMediaKeySystemAccess function configured');\n }\n\n return this._requestMediaKeySystemAccess;\n }\n }]);\n\n return EMEController;\n}(__WEBPACK_IMPORTED_MODULE_0__event_handler__[\"a\" /* default */]);\n\n/* harmony default export */ __webpack_exports__[\"a\"] = (EMEController);\n\n/***/ }),\n/* 71 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return requestMediaKeySystemAccess; });\nvar requestMediaKeySystemAccess = function () {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {\n return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);\n } else {\n return null;\n }\n}();\n\n\n\n/***/ }),\n/* 72 */\n/***/ (function(module, exports) {\n\n/*! http://mths.be/endswith v0.2.0 by @mathias */\nif (!String.prototype.endsWith) {\n\t(function() {\n\t\t'use strict'; // needed to support `apply`/`call` with `undefined`/`null`\n\t\tvar defineProperty = (function() {\n\t\t\t// IE 8 only supports `Object.defineProperty` on DOM elements\n\t\t\ttry {\n\t\t\t\tvar object = {};\n\t\t\t\tvar $defineProperty = Object.defineProperty;\n\t\t\t\tvar result = $defineProperty(object, object, object) && $defineProperty;\n\t\t\t} catch(error) {}\n\t\t\treturn result;\n\t\t}());\n\t\tvar toString = {}.toString;\n\t\tvar endsWith = function(search) {\n\t\t\tif (this == null) {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar string = String(this);\n\t\t\tif (search && toString.call(search) == '[object RegExp]') {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar stringLength = string.length;\n\t\t\tvar searchString = String(search);\n\t\t\tvar searchLength = searchString.length;\n\t\t\tvar pos = stringLength;\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tvar position = arguments[1];\n\t\t\t\tif (position !== undefined) {\n\t\t\t\t\t// `ToInteger`\n\t\t\t\t\tpos = position ? Number(position) : 0;\n\t\t\t\t\tif (pos != pos) { // better `isNaN`\n\t\t\t\t\t\tpos = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar end = Math.min(Math.max(pos, 0), stringLength);\n\t\t\tvar start = end - searchLength;\n\t\t\tif (start < 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar index = -1;\n\t\t\twhile (++index < searchLength) {\n\t\t\t\tif (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\tif (defineProperty) {\n\t\t\tdefineProperty(String.prototype, 'endsWith', {\n\t\t\t\t'value': endsWith,\n\t\t\t\t'configurable': true,\n\t\t\t\t'writable': true\n\t\t\t});\n\t\t} else {\n\t\t\tString.prototype.endsWith = endsWith;\n\t\t}\n\t}());\n}\n\n\n/***/ })\n/******/ ])[\"default\"];\n});\n\n\n// WEBPACK FOOTER //\n// hls.min.js"," \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 = 28);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 8b3896ec37aa881fcca0","import { getSelfScope } from './get-self-scope';\n\nfunction noop () {}\n\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nlet exportedLogger = fakeLogger;\n\n// 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\nconst global = getSelfScope();\n\nfunction consolePrintFn (type) {\n const func = global.console[type];\n if (func) {\n return function (...args) {\n if (args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n\n func.apply(global.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 } else {\n exportedLogger = fakeLogger;\n }\n};\n\nexport var logger = exportedLogger;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/logger.js","/**\n * @readonly\n * @enum {string}\n */\nconst HlsEvents = {\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 }\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 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\nexport default HlsEvents;\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 // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR: 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nexport const ErrorDetails = {\n KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',\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 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*\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\nconst FORBIDDEN_EVENT_NAMES = new Set([\n 'hlsEventGeneric',\n 'hlsHandlerDestroying',\n 'hlsHandlerDestroyed'\n]);\n\nclass EventHandler {\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.onHandlerDestroying();\n this.unregisterListeners();\n this.onHandlerDestroyed();\n }\n\n onHandlerDestroying () {}\n onHandlerDestroyed () {}\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 (FORBIDDEN_EVENT_NAMES.has(event)) {\n throw new Error('Forbidden event-name: ' + event);\n }\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 let eventToFunction = function (event, data) {\n let 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\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n logger.error(`An internal error happened while handling event ${event}. Error message: \"${err.message}\". Here is a stacktrace:`, err);\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","export function getSelfScope () {\n // see https://stackoverflow.com/a/11237259/589493\n if (typeof window === 'undefined') {\n /* eslint-disable-next-line no-undef */\n return self;\n } else {\n return window;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/get-self-scope.js","// 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 = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\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 (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 = 5\n// module chunks = 0","let 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 let minIndex = 0;\n let maxIndex = list.length - 1;\n let currentIndex = null;\n let currentElement = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n\n let comparisonResult = comparisonFunction(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\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 * ID3 parser\n */\nclass 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\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;\n } // 2^32 / 90\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, true);\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, exitOnNull = false) {\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 (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\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","import EventHandler from './event-handler';\n\n/**\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\n\nexport default class TaskLoop extends EventHandler {\n constructor (hls, ...events) {\n super(hls, ...events);\n\n this._tickInterval = null;\n this._tickTimer = null;\n this._tickCallCount = 0;\n this._boundTick = this.tick.bind(this);\n }\n\n /**\n * @override\n */\n onHandlerDestroying () {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n /**\n * @returns {boolean}\n */\n hasInterval () {\n return !!this._tickInterval;\n }\n\n /**\n * @returns {boolean}\n */\n hasNextTick () {\n return !!this._tickTimer;\n }\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n */\n setInterval (millis) {\n if (!this._tickInterval) {\n this._tickInterval = setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n */\n clearInterval () {\n if (this._tickInterval) {\n clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n clearNextTick () {\n if (this._tickTimer) {\n clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n tick () {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.clearNextTick();\n this._tickTimer = setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n doTick () {}\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/task-loop.js","\nimport URLToolkit from 'url-toolkit';\n\nimport LevelKey from './level-key';\n\nexport default class Fragment {\n constructor () {\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n this.tagList = [];\n\n // Holds the types of data this fragment supports\n this._elementaryStreams = {\n [Fragment.ElementaryStreamTypes.AUDIO]: false,\n [Fragment.ElementaryStreamTypes.VIDEO]: false\n };\n }\n\n /**\n * `type` property for this._elementaryStreams\n *\n * @enum\n */\n static get ElementaryStreamTypes () {\n return {\n AUDIO: 'audio',\n VIDEO: 'video'\n };\n }\n\n get url () {\n if (!this._url && this.relurl) {\n this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\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\n return this._programDateTime;\n }\n\n get byteRange () {\n if (!this._byteRange && !this.rawByteRange) {\n return [];\n }\n\n if (this._byteRange) {\n return this._byteRange;\n }\n\n let 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 || 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n return byteRange;\n }\n\n /**\n * @type {number}\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\n return this._decryptdata;\n }\n\n get encrypted () {\n return !!((this.decryptdata && this.decryptdata.uri !== null) && (this.decryptdata.key === null));\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n addElementaryStream (type) {\n this._elementaryStreams[type] = true;\n }\n\n /**\n * @param {ElementaryStreamType} type\n */\n hasElementaryStream (type) {\n return this._elementaryStreams[type] === true;\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 let uint8View = new Uint8Array(16);\n\n for (let 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 let 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\n\n\n// WEBPACK FOOTER //\n// ./src/loader/fragment.js","import EventHandler from '../event-handler';\nimport Event from '../events';\n\nexport const FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nexport class FragmentTracker extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.BUFFER_APPENDED,\n Event.FRAG_BUFFERED,\n Event.FRAG_LOADED\n );\n\n this.bufferPadding = 0.2;\n\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n\n this.config = hls.config;\n }\n\n destroy () {\n this.fragments = null;\n this.timeRanges = null;\n this.config = null;\n EventHandler.prototype.destroy.call(this);\n super.destroy();\n }\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n getBufferedFrag (position, levelType) {\n const fragments = this.fragments;\n const bufferedFrags = Object.keys(fragments).filter(key => {\n const fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n const frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n const bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n detectEvictedFragments (elementaryStream, timeRange) {\n let fragmentTimes, time;\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (fragmentEntity.buffered === true) {\n const esData = fragmentEntity.range[elementaryStream];\n if (esData) {\n fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n time = fragmentTimes[i];\n\n if (this.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n break;\n }\n }\n }\n }\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n detectPartialFragments (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n if (fragment.hasElementaryStream(elementaryStream) === true) {\n let timeRange = this.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n }\n\n getBufferedTimes (startPTS, endPTS, timeRange) {\n let fragmentTimes = [];\n let startTime, endTime;\n let fragmentPartial = false;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n }\n\n getFragmentKey (fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n }\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n getPartialFragment (time) {\n let timePadding, startTime, endTime;\n let bestFragment = null;\n let bestOverlap = 0;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (this.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - this.bufferPadding;\n endTime = fragmentEntity.body.endPTS + this.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n getState (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n let state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n }\n\n isPartial (fragmentEntity) {\n return fragmentEntity.buffered === true &&\n ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||\n (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));\n }\n\n isTimeBuffered (startPTS, endPTS, timeRange) {\n let startTime, endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n /**\n * Fires when a fragment loading is completed\n */\n onFragLoaded (e) {\n let fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!isNaN(fragment.sn) && !fragment.bitrateTest) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n this.fragments[fragKey] = fragmentEntity;\n }\n }\n\n /**\n * Fires when the buffer is updated\n */\n onBufferAppended (e) {\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n let timeRange = this.timeRanges[elementaryStream];\n this.detectEvictedFragments(elementaryStream, timeRange);\n });\n }\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n onFragBuffered (e) {\n this.detectPartialFragments(e.frag);\n }\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n hasFragment (fragment) {\n const fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n }\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n removeFragment (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n }\n\n /**\n * Remove all fragments from fragment tracker.\n */\n removeAllFragments () {\n this.fragments = Object.create(null);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fragment-tracker.js","/**\n * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n * @param {HTMLMediaElement|SourceBuffer} media\n * @param {number} position\n * @returns {boolean}\n */\n static isBuffered (media, position) {\n try {\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 } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo (media, pos, maxHoleDuration) {\n try {\n if (media) {\n let 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\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo (buffered, pos, maxHoleDuration) {\n let 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 let 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 let buf2len = buffered2.length;\n if (buf2len) {\n let 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 let start = buffered2[i].start,\n end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/buffer-helper.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 = 12\n// module chunks = 0","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\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nclass Decrypter {\n constructor (observer, config, { removePKCS7Padding = true } = {}) {\n this.logEnabled = true;\n this.observer = observer;\n this.config = config;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = global.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {}\n }\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\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));\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 } 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","/**\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/utils/mediasource-helper.js","/**\n * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\nimport { logger } from '../utils/logger';\n\nexport function addGroupId (level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nexport function updatePTS (fragments, fromIdx, toIdx) {\n let 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\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\n let 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\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 let 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 // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\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 let 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 let 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/controller/level-helper.js","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport M3U8Parser from './m3u8-parser';\n\nconst { performance } = window;\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\nconst ContextType = {\n MANIFEST: 'manifest',\n LEVEL: 'level',\n AUDIO_TRACK: 'audioTrack',\n SUBTITLE_TRACK: 'subtitleTrack'\n};\n\n/**\n * @enum {string}\n */\nconst LevelType = {\n MAIN: 'main',\n AUDIO: 'audio',\n SUBTITLE: 'subtitle'\n};\n\n/**\n * @constructor\n */\nclass PlaylistLoader extends EventHandler {\n /**\n * @constructs\n * @param {Hls} hls\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\n this.loaders = {};\n }\n\n static get ContextType () {\n return ContextType;\n }\n\n static get LevelType () {\n return LevelType;\n }\n\n /**\n * @param {ContextType} type\n * @returns {boolean}\n */\n static canHaveQualityLevels (type) {\n return (type !== ContextType.AUDIO_TRACK &&\n type !== ContextType.SUBTITLE_TRACK);\n }\n\n /**\n * Map context.type to LevelType\n * @param {{type: ContextType}} context\n * @returns {LevelType}\n */\n static mapContextToLevelType (context) {\n const { type } = context;\n\n switch (type) {\n case ContextType.AUDIO_TRACK:\n return LevelType.AUDIO;\n case ContextType.SUBTITLE_TRACK:\n return LevelType.SUBTITLE;\n default:\n return LevelType.MAIN;\n }\n }\n\n static getResponseUrl (response, context) {\n let url = response.url;\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 return url;\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {object} context\n * @returns {XHRLoader} or other compatible configured overload\n */\n createInternalLoader (context) {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n\n const loader = new InternalLoader(config);\n\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n getInternalLoader (context) {\n return this.loaders[context.type];\n }\n\n resetInternalLoader (contextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n destroyInternalLoaders () {\n for (let contextType in this.loaders) {\n let loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n }\n\n destroy () {\n this.destroyInternalLoaders();\n\n super.destroy();\n }\n\n onManifestLoading (data) {\n this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });\n }\n\n onLevelLoading (data) {\n this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });\n }\n\n onAudioTrackLoading (data) {\n this.load(data.url, { type: ContextType.AUDIO_TRACK, level: 0, id: data.id });\n }\n\n onSubtitleTrackLoading (data) {\n this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: 0, id: data.id });\n }\n\n load (url, context) {\n const config = this.hls.config;\n\n logger.debug(`Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) { // same URL can't overlap\n logger.trace('playlist request ongoing');\n return false;\n } else {\n logger.warn(`aborting previous loader for type: ${context.type}`);\n loader.abort();\n }\n }\n\n let maxRetry,\n timeout,\n retryDelay,\n maxRetryDelay;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case ContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case ContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n context.url = url;\n context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)\n\n const loaderConfig = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay\n };\n\n const loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n logger.debug(`Calling internal loader delegate for URL: ${url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n }\n\n loadsuccess (response, stats, context, networkDetails = null) {\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n\n const string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n }\n\n loaderror (response, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails);\n }\n\n loadtimeout (stats, context, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, true);\n }\n\n _handleMasterPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n const string = response.data;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levels = M3U8Parser.parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n\n const audioGroups = levels.map(level => ({\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n }));\n\n let audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n let subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n\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\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // 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({\n type: 'main',\n name: 'main'\n });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n url,\n stats,\n networkDetails\n });\n }\n\n _handleTrackOrLevelPlaylist (response, stats, context, networkDetails) {\n const hls = this.hls;\n\n const { id, level, type } = context;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n const levelUrlId = isNaN(id) ? 0 : id;\n const levelId = isNaN(level) ? levelUrlId : level; // level -> id -> 0\n const levelType = PlaylistLoader.mapContextToLevelType(context);\n\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n levelDetails.tload = stats.tload;\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === ContextType.MANIFEST) {\n const singleLevel = {\n url,\n details: levelDetails\n };\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n const sidxUrl = levelDetails.initSegment.url;\n this.load(sidxUrl, {\n isSidxRequest: true,\n type,\n level,\n levelDetails,\n id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n }\n\n _handleSidxRequest (response, context) {\n const sidxInfo = MP4Demuxer.parseSegmentIndex(new Uint8Array(response.data));\n sidxInfo.references.forEach((segmentRef, index) => {\n const segRefInfo = segmentRef.info;\n const frag = context.levelDetails.fragments[index];\n\n if (frag.byteRange.length === 0) {\n frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);\n }\n });\n\n context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';\n }\n\n _handleManifestParsingError (response, context, reason, networkDetails) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason,\n networkDetails\n });\n }\n\n _handleNetworkError (context, networkDetails, timeout = false) {\n logger.info(`A network error occured while loading a ${context.type}-type playlist`);\n\n let details;\n let fatal;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case ContextType.MANIFEST:\n details = (timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR);\n fatal = true;\n break;\n case ContextType.LEVEL:\n details = (timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR);\n fatal = false;\n break;\n case ContextType.AUDIO_TRACK:\n details = (timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR);\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: loader.url,\n loader,\n context,\n networkDetails\n });\n }\n\n _handlePlaylistLoaded (response, stats, context, networkDetails) {\n const { type, level, id, levelDetails } = context;\n\n if (!levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n const canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(Event.LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats,\n networkDetails\n });\n } else {\n switch (type) {\n case ContextType.AUDIO_TRACK:\n this.hls.trigger(Event.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n case ContextType.SUBTITLE_TRACK:\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n }\n }\n }\n}\n\nexport default PlaylistLoader;\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/playlist-loader.js","/**\n * MP4 demuxer\n */\nimport { logger } from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4Demuxer {\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\n if (videoCodec == null) {\n videoCodec = 'avc1.42e01e';\n }\n\n const 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\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 });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\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 static bin2str (buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint16 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 8 |\n buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\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 // Find the data for a box specified by its path\n static findBox (data, path) {\n let 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 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 static parseSegmentIndex (initSegment) {\n const moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n const moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n let index = 0;\n let sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n let references;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n const version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n const timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.end + firstOffset;\n\n const referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7FFFFFFF;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n const subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n moovEndOffset\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 let result = [];\n let 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 * 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 */\n static getStartDTS (initData, fragment) {\n let 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 let 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 let 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 static 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 let id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n let 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 let version = tfdt.data[tfdt.start];\n let 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, false);\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\nexport default MP4Demuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/mp4demuxer.js","import URLToolkit from 'url-toolkit';\n\nexport default class LevelKey {\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\n return this._uri;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/level-key.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 window.MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/codecs.js","import EventEmitter from 'events';\nimport work from 'webworkify-webpack';\n\nimport Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst MediaSource = getMediaSource();\n\nclass Demuxer {\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 let 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) {\n 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 };\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 global.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\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\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 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 global.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\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// WEBPACK FOOTER //\n// ./src/demux/demuxer.js","/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\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\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst performance = global;\n\nclass DemuxerInline {\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 let 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\n let localthis = this;\n // performance.now() not available on WebWorker, at least on Safari Desktop\n let 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 let 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 let demuxer = this.demuxer;\n if (!demuxer ||\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n // so let's check that current demuxer is still valid\n ((discontinuity || trackSwitch) && !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: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer }\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\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 * ADTS parser helper\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\nexport function getAudioConfig (observer, data, offset, audioCodec) {\n let 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\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\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 let 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 let headerLength, frameLength, stamp;\n let 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 let frameDuration = getFrameDuration(track.samplerate);\n let header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n let stamp = header.stamp;\n let headerLength = header.headerLength;\n let frameLength = header.frameLength;\n\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n let 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// WEBPACK FOOTER //\n// ./src/demux/adts.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 SamplesCoefficients: [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]\n ],\n\n BytesInSlot: [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\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 let header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n let frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;\n let stamp = pts + frameIndex * frameDuration;\n let 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 let headerB = (data[offset + 1] >> 3) & 3;\n let headerC = (data[offset + 1] >> 1) & 3;\n let headerE = (data[offset + 2] >> 4) & 15;\n let headerF = (data[offset + 2] >> 2) & 3;\n let headerG = (data[offset + 2] >> 1) & 1;\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n let columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n let bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n let columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n let sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n let channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n let sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n let bytesInSlot = MpegAudio.BytesInSlot[headerC];\n let samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n let frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\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\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\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 * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r) {\n let log = '', len = r.length;\n for (let i = 0; i < len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n\n return log;\n }\n};\n\nexport default TimeRanges;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/time-ranges.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 && lastLevel.details.fragments && lastLevel.details.fragments.length) {\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","\nexport function sendAddTrackEvent (track, videoEl) {\n let event = null;\n try {\n event = new window.Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n event.track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function clearCurrentCues (track) {\n if (track && track.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/texttrack-utils.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\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\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// Try to parse input as a time stamp.\nfunction parseTimeStamp (input) {\n function computeSeconds (h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;\n }\n\n let 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\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 (let 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 let 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 let groups = groupDelim ? input.split(groupDelim) : [input];\n for (let i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n\n let kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n let k = kv[0];\n let v = kv[1];\n callback(k, v);\n }\n}\n\nlet 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.\nlet 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 let oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp () {\n let ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\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 let 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 (let 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\n settings.alt(k, vals0, ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\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\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 let 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 let 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 let 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 let buffer = self.buffer;\n let pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n ++pos;\n }\n\n let line = buffer.substr(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n\n if (buffer[pos] === '\\n') {\n ++pos;\n }\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 let 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 let 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 let 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\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\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\n self.cue = null;\n self.state = 'ID';\n continue;\n }\n if (self.cue.text) {\n self.cue.text += '\\n';\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\n continue;\n }\n }\n } catch (e) {\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\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 let 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\n return this;\n }\n};\n\nexport { fixLineBreaks };\n\nexport default VTTParser;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/vttparser.js","import URLToolkit from 'url-toolkit';\n\nimport {\n ErrorTypes,\n ErrorDetails\n} from './errors';\n\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { hlsDefaultConfig } from './config';\n\nimport HlsEvents from './events';\nimport EventEmitter from 'events';\n\n// polyfill for IE11\nrequire('string.prototype.endswith');\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\nexport default class Hls {\n /**\n * @type {string}\n */\n static get version () {\n return __VERSION__;\n }\n\n /**\n * @type {boolean}\n */\n static isSupported () {\n return isSupported();\n }\n\n /**\n * @type {HlsEvents}\n */\n static get Events () {\n return HlsEvents;\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n static get ErrorTypes () {\n return ErrorTypes;\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n static get ErrorDetails () {\n return ErrorDetails;\n }\n\n /**\n * @type {HlsConfig}\n */\n static get DefaultConfig () {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n static set DefaultConfig (defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n constructor (config = {}) {\n let 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 (let 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 let 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.once = observer.once.bind(observer);\n this.trigger = observer.trigger.bind(observer);\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n const abrController = this.abrController = new config.abrController(this);\n\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\n /**\n * @member {LevelController} levelController\n */\n const levelController = this.levelController = new LevelController(this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n\n /**\n * @member {StreamController} streamController\n */\n const streamController = this.streamController = new StreamController(this, fragmentTracker);\n\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n const coreComponents = [\n playListLoader,\n fragmentLoader,\n keyLoader,\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker\n ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n const audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n const subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n coreComponents.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n const emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\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\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n destroy () {\n logger.log('destroy');\n this.trigger(HlsEvents.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {\n component.destroy();\n });\n this.url = null;\n this.observer.removeAllListeners();\n this._autoLevelCapping = -1;\n }\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n attachMedia (media) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(HlsEvents.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach from the media\n */\n detachMedia () {\n logger.log('detachMedia');\n this.trigger(HlsEvents.MEDIA_DETACHING);\n this.media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\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(HlsEvents.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n startLoad (startPosition = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach(controller => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad () {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec () {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError () {\n logger.log('recoverMediaError');\n let media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n }\n\n /**\n * @type {QualityLevel[]}\n */\n get levels () {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel () {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @type {number} -1 for automatic level selection\n */\n set currentLevel (newLevel) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n get nextLevel () {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n set nextLevel (newLevel) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n get loadLevel () {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n set loadLevel (newLevel) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n get nextLoadLevel () {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n set nextLoadLevel (level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n get firstLevel () {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n set firstLevel (newLevel) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\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\n * (determined from download of first segment)\n * @type {number}\n */\n get startLevel () {\n return this.levelController.startLevel;\n }\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\n * (determined from download of first segment)\n * @type {number} newLevel\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\n hls.levelController.startLevel = newLevel;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n get autoLevelCapping () {\n return this._autoLevelCapping;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n set autoLevelCapping (newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n get autoLevelEnabled () {\n return (this.levelController.manualLevel === -1);\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n get manualLevel () {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\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 /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\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\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\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 /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * 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,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n set nextAutoLevel (nextLevel) {\n const hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n get audioTracks () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n get audioTrack () {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n set audioTrack (audioTrackId) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n get liveSyncPosition () {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n get subtitleTracks () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n get subtitleTrack () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type{number}\n */\n set subtitleTrack (subtitleTrackId) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n get subtitleDisplay () {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\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","\nimport URLToolkit from 'url-toolkit';\n\nimport Fragment from './fragment';\nimport LevelKey from './level-key';\n\nimport AttrList from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport { isCodecType } from '../utils/codecs';\n\n/**\n * M3U8 parser\n * @module\n */\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\nconst MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nexport default class M3U8Parser {\n static 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\n static convertAVC1ToAVCOTI (codec) {\n let 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 static resolve (url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static 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 const attrs = level.attrs = new AttrList(result[1]);\n level.url = M3U8Parser.resolve(result[2], baseurl);\n\n const 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 = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n }\n return levels;\n }\n\n static 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 = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n media.lang = attrs.LANGUAGE;\n if (!media.name) {\n media.name = media.lang;\n }\n\n if (audioGroups.length) {\n const groupCodec = M3U8Parser.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 static parseLevelPlaylist (string, baseurl, id, type, levelUrlId) {\n let 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 || 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.urlId = levelUrlId;\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 if (level.programDateTime) {\n if (prevFrag) {\n if (frag.rawProgramDateTime) { // PDT discontinuity found\n frag.pdt = Date.parse(frag.rawProgramDateTime);\n } else { // Contiguous fragment\n frag.pdt = prevFrag.pdt + (prevFrag.duration * 1000);\n }\n } else { // First fragment\n frag.pdt = Date.parse(level.programDateTime);\n }\n frag.endPdt = frag.pdt + (frag.duration * 1000);\n }\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', 'SAMPLE-AES-CENC'].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\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\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every((frag) => MP4_REGEX_SUFFIX.test(frag.relurl))) {\n logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new Fragment();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n return level;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/loader/m3u8-parser.js","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n constructor (attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (let 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\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\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\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\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList (input) {\n let match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let 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\n attrs[match[1]] = value;\n }\n return attrs;\n }\n}\n\nexport default AttrList;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/attr-list.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 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\n super.destroy();\n }\n\n onFragLoading (data) {\n const frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n let loader = loaders[type];\n if (loader) {\n logger.warn(`abort previous fragment loader for type: ${type}`);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader =\n config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n let start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (!isNaN(start) && !isNaN(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\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\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\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 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\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\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","/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment from '../loader/fragment';\nimport PlaylistLoader from '../loader/playlist-loader';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { alignDiscontinuities } from '../utils/discontinuities';\nimport TaskLoop from '../task-loop';\nimport { calculateNextPDT, findFragmentByPDT, findFragmentBySN, fragmentWithinToleranceTest } from './fragment-finders';\n\nexport const 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 TaskLoop {\n constructor (hls, fragmentTracker) {\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.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.stallReported = false;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n super.onHandlerDestroyed();\n }\n\n startLoad (startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n this.setInterval(100);\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 let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.clearInterval();\n this.state = State.STOPPED;\n this.forceStartLoad = false;\n }\n\n doTick () {\n switch (this.state) {\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\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log('mediaController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle () {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n // if 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\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\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 (!levelDetails || (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\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 } 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\n if (frag) {\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);\n this._loadKey(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 this._loadFragment(frag);\n }\n }\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\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 if (!levelDetails.programDateTime) { // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\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 } else { // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPDT(fragments, fragPrevious.endPdt + 1);\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 const fragBySN = () => findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n let frag;\n let foundFrag;\n\n if (bufferEnd < end) {\n if (!levelDetails.programDateTime) { // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);\n } else {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n foundFrag = findFragmentByPDT(fragments, calculateNextPDT(start, bufferEnd, levelDetails));\n if (!foundFrag || fragmentWithinToleranceTest(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) {\n // Fall back to SN order if finding by PDT returns a frag which won't fit within the stream\n // fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise\n logger.warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN');\n foundFrag = fragBySN();\n }\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 } 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 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 _loadKey (frag) {\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\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\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n this.hls.trigger(Event.FRAG_LOADING, { 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(this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\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 this.fragmentTracker.getBufferedFrag(position, PlaylistLoader.LevelType.MAIN);\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 let 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 > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\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 let 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\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 let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\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 const 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 /**\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 nextLevelSwitch () {\n const 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 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 let 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 let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\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\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached (data) {\n let 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 let 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 backtracked flag\n let levels = this.levels;\n if (levels) {\n levels.forEach(level => {\n if (level.details) {\n level.details.fragments.forEach(fragment => {\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\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\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\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\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\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 onManifestLoading () {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed (data) {\n let 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\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\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 let 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\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 let 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 const stats = data.stats;\n const currentLevel = this.levels[fragCurrent.level];\n const 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 = window.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 = window.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\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\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\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let 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\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n let 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 let 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 let 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 if (data.hasAudio === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(Fragment.ElementaryStreamTypes.VIDEO);\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', frag.sn);\n } else {\n logger.warn('missing video frame(s), backtracking fragment', frag.sn);\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 this.fragmentTracker.removeFragment(frag);\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', frag.sn);\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 let 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 // 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 = window.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 let 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 let 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 onBufferCreated (data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for (let 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 this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = window.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\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 logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = window.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.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 return true;\n }\n return false;\n }\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n _checkBuffer () {\n const { config, media } = this;\n const stallDebounceInterval = 1000;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n const currentTime = media.currentTime;\n const mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n const buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n const expectedPlaying = !((media.paused && media.readyState > 1) || // not playing when media is paused and sufficiently buffered\n media.ended || // not playing when media is ended\n media.buffered.length === 0); // not playing if nothing buffered\n const tnow = window.performance.now();\n\n if (currentTime !== this.lastCurrentTime) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(tnow - this.stalled)}ms`);\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n } else if (expectedPlaying) {\n // The playhead isn't moving but it should be\n // Allow some slack time to for small stalls to resolve themselves\n const stalledDuration = tnow - this.stalled;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);\n if (!this.stalled) {\n this.stalled = tnow;\n return;\n } else if (stalledDuration >= stallDebounceInterval) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n this._tryFixBufferStall(bufferInfo, stalledDuration);\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 if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n this.fragmentTracker.detectEvictedFragments(Fragment.ElementaryStreamTypes.VIDEO, media.buffered);\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 /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDuration - The amount of time Hls.js has been stalling for.\n * @private\n */\n _tryFixBufferStall (bufferInfo, stalledDuration) {\n const { config, media } = this;\n const currentTime = media.currentTime;\n const jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end\n\n const partial = this.fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n this._trySkipBufferHole(partial);\n }\n\n if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n _reportStall (bufferLen) {\n const { hls, media, stallReported } = this;\n if (!stallReported) {\n // Report stalled error once\n this.stallReported = true;\n logger.warn(`Playback stalling at @${media.currentTime} due to low buffer`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n _trySkipBufferHole (partial) {\n const { hls, media } = this;\n const currentTime = media.currentTime;\n let lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (let i = 0; i < media.buffered.length; i++) {\n let startTime = media.buffered.start(i);\n if (currentTime >= lastEndTime && currentTime < startTime) {\n media.currentTime = Math.max(startTime, media.currentTime + 0.1);\n logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${media.currentTime}`);\n this.stalled = null;\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${media.currentTime}`,\n frag: partial\n });\n return;\n }\n lastEndTime = media.buffered.end(i);\n }\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n _tryNudgeBuffer () {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n const nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\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, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, raise fatal error`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n _seekToStartPos () {\n const { media } = this;\n const currentTime = media.currentTime;\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 const startPosition = media.seeking ? currentTime : this.startPosition;\n // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered\n if (currentTime !== startPosition) {\n // if startPosition not buffered, let's seek to buffered.start(0)\n logger.log(`target start position not buffered, seek to buffered.start(0) ${startPosition} from current time ${currentTime} `);\n media.currentTime = startPosition;\n }\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// WEBPACK FOOTER //\n// ./src/controller/stream-controller.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\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\((\\/\\\\*.*?\\\\*\\/)?\\s?.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_modules__\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\\n'\n })\n\n src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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 = 34\n// module chunks = 0","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","// PKCS7\nexport function removePadding (buffer) {\n const outputBytes = buffer.byteLength;\n const paddingBytes = outputBytes && (new DataView(buffer)).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return buffer.slice(0, outputBytes - paddingBytes);\n } else {\n return buffer;\n }\n}\n\nclass 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\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, removePKCS7Padding) {\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 let 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 removePKCS7Padding ? removePadding(outputInt32.buffer) : 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","/**\n * AAC demuxer\n */\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport ID3 from '../demux/id3';\n\nclass AACDemuxer {\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\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 let 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\nexport default AACDemuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/aacdemuxer.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\nimport * as ADTS from './adts';\nimport MpegAudio from './mpegaudio';\nimport Event from '../events';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\n// import Hex from '../utils/hex';\nimport { logger } from '../utils/logger';\nimport { 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: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nclass TSDemuxer {\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\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 let start, len = data.length, stt, pid, atf, offset, pes,\n unknownPIDs = false;\n this.contiguous = contiguous;\n let 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)) && pes.pts !== undefined) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n parseID3PES(pes);\n }\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\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\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\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\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)) && pes.pts !== undefined) {\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)) && pes.pts !== undefined) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\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\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)) && pes.pts !== undefined) {\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 let 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\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\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\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 let 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\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 let 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\n if (debug) {\n avcSample.debug += 'NDR ';\n }\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\n if (debug) {\n avcSample.debug += 'IDR ';\n }\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\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 endOfCaptions = true;\n\n let countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n let providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n let userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n let userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n let firstByte = expGolombDecoder.readUByte();\n let secondByte = expGolombDecoder.readUByte();\n\n let totalCCs = 31 & firstByte;\n let 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 } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\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\n if (!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n let 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 let codecarray = unit.data.subarray(1, 4);\n let codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\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\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\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\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 let len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\n } else {\n for (let 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 } 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 let i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n let 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 let 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 let 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 let 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 let 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 let 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 let 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 let 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\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES (pes) {\n let data = pes.data;\n let length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let 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 * 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 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 let\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\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 let 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 let\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\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\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 let leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\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 let clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG () {\n let 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 this.readBits(1) === 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 let\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 let\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 let chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // 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 let 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();\n } // offset_for_ref_frame[ i ]\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);\n } // 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\nimport Decrypter from '../crypt/decrypter';\n\nclass SampleAesDecrypter {\n constructor (observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config, { removePKCS7Padding: false });\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\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\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\nexport default SampleAesDecrypter;\n\n\n\n// WEBPACK FOOTER //\n// ./src/demux/sample-aes.js","/**\n * MP3 demuxer\n */\nimport ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport MpegAudio from './mpegaudio';\n\nclass MP3Demuxer {\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 let 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 timestamp = ID3.getTimeStamp(id3Data);\n let pts = timestamp ? 90 * timestamp : timeOffset * 90000;\n let offset = id3Data.length;\n let length = data.length;\n let frameIndex = 0, stamp = 0;\n let 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 let 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 * fMP4 remuxer\n*/\n\nimport AAC from './aac-helper';\nimport MP4 from './mp4-generator';\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\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\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 // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED);\n }\n\n generateIS (audioTrack, videoTrack, timeOffset) {\n let 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\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 let 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 if (nbSamples === 0) {\n return;\n }\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 || (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\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\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 maxBufferHole.\n // 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 gapTolerance = Math.floor(maxBufferHole * 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 should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\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 // 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 hasAudio: false,\n hasVideo: true,\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 let 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 // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter(function (sample) {\n return sample.pts >= 0;\n });\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = timeOffset * inputTimeScale;\n }\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 if (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 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 } // eslint-disable-line brace-style\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 let 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 (let 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 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\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\n firstPTS = 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 let lastSampleDuration = 0;\n let 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\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 hasAudio: true,\n hasVideo: false,\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 (let i = 0; i < nbSamples; i++) {\n let 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 let 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 (let 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 let length = track.samples.length, sample;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if (length) {\n for (let 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 let offset;\n if (reference === undefined) {\n return value;\n }\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\n return value;\n }\n}\n\nexport default MP4Remuxer;\n\n\n\n// WEBPACK FOOTER //\n// ./src/remux/mp4-remuxer.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\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/remux/aac-helper.js","/**\n * Generate MP4 Box\n*/\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 let 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 let 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 let 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 let 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 let 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 let majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n let avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n let 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 let\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\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 let\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 let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\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 let\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 let\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 let 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\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\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\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n let 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\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 let 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 let 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 let 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\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 let 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 let 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 let 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 let 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\n let 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 * 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 let observer = this.observer;\n let streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\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","/* 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\nimport DemuxerInline from '../demux/demuxer-inline';\nimport Event from '../events';\nimport { enableLogs } from '../utils/logger';\nimport EventEmitter from 'events';\n\nlet DemuxerWorker = function (self) {\n // observer setup\n let 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 let forwardMessage = function (ev, data) {\n self.postMessage({ event: ev, data: data });\n };\n\n self.addEventListener('message', function (ev) {\n let 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// WEBPACK FOOTER //\n// ./src/demux/demuxer-worker.js","import BinarySearch from '../utils/binary-search';\n\n/**\n * Calculates the PDT of the next load position.\n * bufferEnd in this function is usually the position of the playhead.\n * @param {number} [start = 0] - The PTS of the first fragment within the level\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level\n * @returns {number} nextPdt - The computed PDT\n */\nexport function calculateNextPDT (start = 0, bufferEnd = 0, levelDetails) {\n let pdt = 0;\n if (levelDetails.programDateTime) {\n const parsedDateInt = Date.parse(levelDetails.programDateTime);\n if (!isNaN(parsedDateInt)) {\n pdt = (bufferEnd * 1000) + parsedDateInt - (1000 * start);\n }\n }\n return pdt;\n}\n\n/**\n * Finds the first fragment whose endPDT value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @returns {*|null} fragment - The best matching fragment\n */\nexport function findFragmentByPDT (fragments, PDTValue = null) {\n if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) {\n return null;\n }\n\n // if less than start\n let firstSegment = fragments[0];\n\n if (PDTValue < firstSegment.pdt) {\n return null;\n }\n\n let lastSegment = fragments[fragments.length - 1];\n\n if (PDTValue >= lastSegment.endPdt) {\n return null;\n }\n\n for (let seg = 0; seg < fragments.length; ++seg) {\n let frag = fragments[seg];\n if (PDTValue < frag.endPdt) {\n return frag;\n }\n }\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} [end = 0] - The computed end time of the stream\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nexport function findFragmentBySN (fragPrevious, fragments, bufferEnd = 0, end = 0, maxFragLookUpTolerance = 0) {\n let foundFrag;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n }\n }\n return foundFrag;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest (bufferEnd = 0, maxFragLookUpTolerance = 0, 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 } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/fragment-finders.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';\nimport { addGroupId } from './level-helper';\n\nconst { performance } = window;\n\nexport default class LevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.FRAG_LOADED,\n Event.ERROR);\n\n this.canload = false;\n this.currentLevelIndex = null;\n this.manualLevelIndex = -1;\n this.timer = null;\n }\n\n onHandlerDestroying () {\n this.clearTimer();\n this.manualLevelIndex = -1;\n }\n\n clearTimer () {\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 !== null) {\n this.loadLevel();\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 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (level.attrs && level.attrs.AUDIO) {\n addGroupId(levelFromSet || level, 'audio', level.attrs.AUDIO);\n }\n\n if (level.attrs && level.attrs.SUBTITLES) {\n addGroupId(levelFromSet || level, 'text', level.attrs.SUBTITLES);\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\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 > 0) {\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, {\n levels,\n audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: audioTracks.length > 0 && videoCodecFound\n });\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.currentLevelIndex;\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.currentLevelIndex !== newLevel || !levels[newLevel].details) {\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.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this.currentLevelIndex = newLevel;\n const levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n const level = levels[newLevel];\n const levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n let 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, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n }\n\n get manualLevel () {\n return this.manualLevelIndex;\n }\n\n set manualLevel (newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel () {\n return this._firstLevel;\n }\n\n set firstLevel (newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel () {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel (newLevel) {\n this._startLevel = newLevel;\n }\n\n onError (data) {\n if (data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n let levelError = false, fragmentError = false;\n let levelIndex;\n\n // try to recover not fatal errors\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 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 levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {\n let { config } = this.hls;\n let { details: errorDetails } = errorEvent;\n let level = this._levels[levelIndex];\n let redundantLevels, delay, nextLevel;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(() => this.loadLevel(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`level controller, cannot recover from ${errorDetails} error`);\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;\n logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n logger.warn(`level controller, ${errorDetails}: reload a fragment`);\n this.currentLevelIndex = null;\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.currentLevelIndex) {\n return;\n }\n\n const 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) {\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 const targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration);\n let reloadInterval = targetdurationMs,\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 half of target duration\n reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval));\n logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);\n this.timer = setTimeout(() => this.loadLevel(), reloadInterval);\n } else {\n this.clearTimer();\n }\n }\n\n onAudioTrackSwitched (data) {\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n const urlId = currentLevel.audioGroupIds.findIndex((groupId) => groupId === audioGroupId);\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n loadLevel () {\n logger.debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n const levelObject = this._levels[this.currentLevelIndex];\n\n if (typeof levelObject === 'object' &&\n levelObject.url.length > 0) {\n const level = this.currentLevelIndex;\n const id = levelObject.urlId;\n const url = levelObject.url[id];\n\n logger.log(`Attempt loading level index ${level} with URL-id ${id}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });\n }\n }\n }\n\n get nextLoadLevel () {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel (nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n}\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';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\n\nclass ID3TrackController extends EventHandler {\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\n }\n }\n\n onMediaDetaching () {\n clearCurrentCues(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n getID3Track (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n let textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\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.getID3Track(this.media.textTracks);\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","import { getMediaSource } from './utils/mediasource-helper';\n\nexport function 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\n\n// WEBPACK FOOTER //\n// ./src/is-supported.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';\nimport EMEController from './controller/eme-controller';\n\nimport { requestMediaKeySystemAccess } from './utils/mediakeys-helper';\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\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 liveDurationInfinity: false, // used by buffer-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 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, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\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 emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n requestMediaKeySystemAccessFunc:\n requestMediaKeySystemAccess // used by eme-controller\n};\n\nif (__USE_SUBTITLES__) {\n hlsDefaultConfig.subtitleStreamController = SubtitleStreamController;\n hlsDefaultConfig.subtitleTrackController = SubtitleTrackController;\n hlsDefaultConfig.timelineController = TimelineController;\n hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller\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 (__USE_ALT_AUDIO__) {\n hlsDefaultConfig.audioStreamController = AudioStreamController;\n hlsDefaultConfig.audioTrackController = AudioTrackController;\n}\n\nif (__USE_EME_DRM__) {\n hlsDefaultConfig.emeController = EMEController;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/config.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 '../utils/buffer-helper';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\n\nconst { performance } = window;\n\nclass AbrController extends EventHandler {\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 const frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, 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 const hls = this.hls;\n const config = hls.config;\n const level = frag.level;\n const isLive = hls.levels[level].details.live;\n\n let ewmaFast, ewmaSlow;\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 }\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 const hls = this.hls;\n const video = hls.media;\n const frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n const loader = frag.loader;\n const 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 // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\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 (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {\n let requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(video.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 = video.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (BufferHelper.bufferInfo(video, 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 const 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 const stats = data.stats;\n const 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.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\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\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel () {\n let hls = this.hls, maxAutoLevel = hls.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = hls.minAutoLevel;\n const video = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = (video ? video.currentTime : 0),\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.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(video, 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\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// WEBPACK FOOTER //\n// ./src/controller/abr-controller.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\nclass EwmaBandWidthEstimator {\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 let 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 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// WEBPACK FOOTER //\n// ./src/utils/ewma-bandwidth-estimator.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 // 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 let 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 let 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 * 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 '../utils/mediasource-helper';\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\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 // current stream state: true - for live broadcast, false - for VoD content\n this._live = null;\n // cache the self generated object url to detect hijack of video tag\n this._objectUrl = 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.altAudio),\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 let 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 = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n }\n\n onMediaDetaching () {\n logger.log('media source detaching');\n let 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 window.URL.revokeObjectURL(this._objectUrl);\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n logger.warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = 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 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\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\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n let timeRanges = {};\n const sourceBuffer = this.sourceBuffer;\n for (let streamType in sourceBuffer) {\n timeRanges[streamType] = sourceBuffer[streamType].buffered;\n }\n\n this.hls.trigger(Event.BUFFER_APPENDED, { parent, pending, timeRanges });\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 let sourceBuffer = this.sourceBuffer;\n for (let type in sourceBuffer) {\n let 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 (let 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 createSourceBuffers (tracks) {\n let 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\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 let 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 let 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\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 onBufferFlushing (data) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n onLevelUpdated ({ details }) {\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n updateMediaElementDuration () {\n let { config } = this.hls;\n let duration;\n\n if (this._levelDuration === null ||\n !this.media ||\n !this.mediaSource ||\n !this.sourceBuffer ||\n this.media.readyState === 0 ||\n this.mediaSource.readyState !== 'open') {\n return;\n }\n\n for (let type in this.sourceBuffer) {\n if (this.sourceBuffer[type].updating === true) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n\n duration = this.media.duration;\n // initialise to the value that the media source is reporting\n if (this._msDuration === null) {\n this._msDuration = this.mediaSource.duration;\n }\n\n if (this._live === true && config.liveDurationInfinity === true) {\n // Override duration to Infinity\n logger.log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if ((this._levelDuration > this._msDuration && this._levelDuration > duration) ||\n (duration === Infinity || isNaN(duration))) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(`Updating Media Source duration to ${this._levelDuration.toFixed(3)}`);\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n }\n\n doFlush () {\n // loop through all buffer ranges to flush\n while (this.flushRange.length) {\n let 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 let appended = 0;\n let sourceBuffer = this.sourceBuffer;\n try {\n for (let 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 let 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 let 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\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 } 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 }\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 let 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 (let 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\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 constructor (hls) {\n super(hls,\n Event.FPS_DROP_LEVEL_CAPPING,\n Event.MEDIA_ATTACHING,\n Event.MANIFEST_PARSED,\n Event.BUFFER_CODECS);\n\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = null;\n this.levels = [];\n this.media = null;\n this.restrictedLevels = [];\n this.timer = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this._stopCapping();\n }\n }\n\n onFpsDropLevelCapping (data) {\n // 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 onMediaAttaching (data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed (data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && (data.video || (data.levels.length && data.altAudio))) {\n // Start capping immediately if the manifest has signaled video codecs\n this._startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs (data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this._startCapping();\n }\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\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 _startCapping () {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n _stopCapping () {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\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\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\nconst { performance } = window;\n\nclass FPSController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy () {\n if (this.timer) {\n clearInterval(this.timer);\n }\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 window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\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// WEBPACK FOOTER //\n// ./src/controller/fps-controller.js","/**\n * XHR based logger\n*/\n\nimport { logger } from '../utils/logger';\n\nconst { performance, XMLHttpRequest } = window;\n\nclass XhrLoader {\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 let 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 let 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\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 let 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\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 let xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\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","import Event from '../events';\nimport TaskLoop from '../task-loop';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\n/**\n * @class AudioTrackController\n * @implements {EventHandler}\n *\n * Handles main manifest and audio-track metadata loaded,\n * owns and exposes the selectable audio-tracks data-models.\n *\n * Exposes internal interface to select available audio-tracks.\n *\n * Handles errors on loading audio-track playlists. Manages fallback mechanism\n * with redundants tracks (group-IDs).\n *\n * Handles level-loading and group-ID switches for video (fallback on video levels),\n * and eventually adapts the audio-track group-ID to match.\n *\n * @fires AUDIO_TRACK_LOADING\n * @fires AUDIO_TRACK_SWITCHING\n * @fires AUDIO_TRACKS_UPDATED\n * @fires ERROR\n *\n */\nclass AudioTrackController extends TaskLoop {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.AUDIO_TRACK_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.LEVEL_LOADED,\n Event.ERROR\n );\n\n /**\n * @private\n * Currently selected index in `tracks`\n * @member {number} trackId\n */\n this.trackId = -1;\n\n /**\n * @public\n * All tracks available\n * @member {AudioTrack[]}\n */\n this.tracks = [];\n\n /**\n * @public\n * List of blacklisted audio track IDs (that have caused failure)\n * @member {number[]}\n */\n this.trackIdBlacklist = Object.create(null);\n\n /**\n * @public\n * The currently running group ID for audio\n * (we grab this on manifest-parsed and new level-loaded)\n * @member {string}\n */\n this.audioGroupId = null;\n }\n\n /**\n * Reset audio tracks on new manifest loading.\n */\n onManifestLoading () {\n this.tracks = [];\n this.trackId = -1;\n }\n\n /**\n * Store tracks data from manifest parsed data.\n *\n * Trigger AUDIO_TRACKS_UPDATED event.\n *\n * @param {*} data\n */\n onManifestParsed (data) {\n const tracks = this.tracks = data.audioTracks || [];\n this.hls.trigger(Event.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });\n }\n\n /**\n * Store track details of loaded track in our data-model.\n *\n * Set-up metadata update interval task for live-mode streams.\n *\n * @param {} data\n */\n onAudioTrackLoaded (data) {\n if (data.id >= this.tracks.length) {\n logger.warn('Invalid audio track id:', data.id);\n return;\n }\n\n logger.log(`audioTrack ${data.id} loaded`);\n\n this.tracks[data.id].details = data.details;\n\n // check if current playlist is a live playlist\n // and if we have already our reload interval setup\n if (data.details.live && !this.hasInterval()) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n const updatePeriodMs = data.details.targetduration * 1000;\n this.setInterval(updatePeriodMs);\n }\n\n if (!data.details.live && this.hasInterval()) {\n // playlist is not live and timer is scheduled: cancel it\n this.clearInterval();\n }\n }\n\n /**\n * Update the internal group ID to any audio-track we may have set manually\n * or because of a failure-handling fallback.\n *\n * Quality-levels should update to that group ID in this case.\n *\n * @param {*} data\n */\n onAudioTrackSwitched (data) {\n const audioGroupId = this.tracks[data.id].groupId;\n if (audioGroupId && (this.audioGroupId !== audioGroupId)) {\n this.audioGroupId = audioGroupId;\n }\n }\n\n /**\n * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)\n * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.\n *\n * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently\n * selected one (based on NAME property).\n *\n * @param {*} data\n */\n onLevelLoaded (data) {\n // FIXME: crashes because currentLevel is undefined\n // const levelInfo = this.hls.levels[this.hls.currentLevel];\n\n const levelInfo = this.hls.levels[data.level];\n\n if (!levelInfo.audioGroupIds) {\n return;\n }\n\n const audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.audioGroupId !== audioGroupId) {\n this.audioGroupId = audioGroupId;\n this._selectInitialAudioTrack();\n }\n }\n\n /**\n * Handle network errors loading audio track manifests\n * and also pausing on any netwok errors.\n *\n * @param {ErrorEventData} data\n */\n onError (data) {\n // Only handle network errors\n if (data.type !== ErrorTypes.NETWORK_ERROR) {\n return;\n }\n\n // If fatal network error, cancel update task\n if (data.fatal) {\n this.clearInterval();\n }\n\n // If not an audio-track loading error don't handle further\n if (data.details !== ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {\n return;\n }\n\n logger.warn('Network failure on audio-track id:', data.context.id);\n this._handleLoadError();\n }\n\n /**\n * @type {AudioTrack[]} Audio-track list we own\n */\n get audioTracks () {\n return this.tracks;\n }\n\n /**\n * @type {number} Index into audio-tracks list of currently selected track.\n */\n get audioTrack () {\n return this.trackId;\n }\n\n /**\n * Select current track by index\n */\n set audioTrack (newId) {\n // noop on same audio track id as already set\n if (this.trackId === newId && this.tracks[this.trackId].details) {\n logger.debug('Same id as current audio-track passed, and track details available -> no-op');\n return;\n }\n\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n logger.warn('Invalid id passed to audio-track controller');\n return;\n }\n\n const audioTrack = this.tracks[newId];\n\n logger.log(`Now switching to audio-track index ${newId}`);\n\n // stopping live reloading timer if any\n this.clearInterval();\n this.trackId = newId;\n\n const { url, type, id } = audioTrack;\n this.hls.trigger(Event.AUDIO_TRACK_SWITCHING, { id, type, url });\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @override\n */\n doTick () {\n this._updateTrack(this.trackId);\n }\n\n /**\n * Select initial track\n * @private\n */\n _selectInitialAudioTrack () {\n let tracks = this.tracks;\n if (!tracks.length) {\n return;\n }\n\n const currentAudioTrack = this.tracks[this.trackId];\n\n let name = null;\n if (currentAudioTrack) {\n name = currentAudioTrack.name;\n }\n\n // Pre-select default tracks if there are any\n const defaultTracks = tracks.filter((track) => track.default);\n if (defaultTracks.length) {\n tracks = defaultTracks;\n } else {\n logger.warn('No default audio tracks defined');\n }\n\n let trackFound = false;\n\n const traverseTracks = () => {\n // Select track with right group ID\n tracks.forEach((track) => {\n if (trackFound) {\n return;\n }\n // We need to match the (pre-)selected group ID\n // and the NAME of the current track.\n if ((!this.audioGroupId || track.groupId === this.audioGroupId) &&\n (!name || name === track.name)) {\n // If there was a previous track try to stay with the same `NAME`.\n // It should be unique across tracks of same group, and consistent through redundant track groups.\n this.audioTrack = track.id;\n trackFound = true;\n }\n });\n };\n\n traverseTracks();\n\n if (!trackFound) {\n name = null;\n traverseTracks();\n }\n\n if (!trackFound) {\n logger.error(`No track found for running audio group-ID: ${this.audioGroupId}`);\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n * @returns {boolean}\n */\n _needsTrackLoading (audioTrack) {\n const { details } = audioTrack;\n\n if (!details) {\n return true;\n } else if (details.live) {\n return true;\n }\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n */\n _loadTrackDetailsIfNeeded (audioTrack) {\n if (this._needsTrackLoading(audioTrack)) {\n const { url, id } = audioTrack;\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`loading audio-track playlist for id: ${id}`);\n this.hls.trigger(Event.AUDIO_TRACK_LOADING, { url, id });\n }\n }\n\n /**\n * @private\n * @param {number} newId\n */\n _updateTrack (newId) {\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearInterval();\n this.trackId = newId;\n logger.log(`trying to update audio-track ${newId}`);\n const audioTrack = this.tracks[newId];\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @private\n */\n _handleLoadError () {\n // First, let's black list current track id\n this.trackIdBlacklist[this.trackId] = true;\n\n // Let's try to fall back on a functional audio-track with the same group ID\n const previousId = this.trackId;\n const { name, language, groupId } = this.tracks[previousId];\n\n logger.warn(`Loading failed on audio track id: ${previousId}, group-id: ${groupId}, name/language: \"${name}\" / \"${language}\"`);\n\n // Find a non-blacklisted track ID with the same NAME\n // At least a track that is not blacklisted, thus on another group-ID.\n let newId = previousId;\n for (let i = 0; i < this.tracks.length; i++) {\n if (this.trackIdBlacklist[i]) {\n continue;\n }\n const newTrack = this.tracks[i];\n if (newTrack.name === name) {\n newId = i;\n break;\n }\n }\n\n if (newId === previousId) {\n logger.warn(`No fallback audio-track found for name/language: \"${name}\" / \"${language}\"`);\n return;\n }\n\n logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);\n\n this.audioTrack = newId;\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 '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { findFragWithCC } from '../utils/discontinuities';\nimport TaskLoop from '../task-loop';\nimport { FragmentState } from './fragment-tracker';\nimport Fragment from '../loader/fragment';\n\nconst { performance } = window;\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 TaskLoop {\n constructor (hls, fragmentTracker) {\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_RESET,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED,\n Event.INIT_PTS_FOUND);\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.initPTS = [];\n this.waitingFragment = null;\n this.videoTrackCC = null;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n super.onHandlerDestroyed();\n }\n\n // Signal that video PTS was found\n onInitPtsFound (data) {\n let 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 let lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(100);\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 let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(frag);\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 doTick () {\n let 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\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\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) or config.maxMaxBufferLength (default: 600s)\n // whichever is smaller.\n // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)\n maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),\n maxBufLen = Math.max(maxConfigBuffer, 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 // check if we need to finalize media stream\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 if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN && !bufferInfo.nextStart) {\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 } // eslint-disable-line brace-style\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 } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\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.encrypted) {\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 // only load if fragment is not loaded or if in audio switch\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) {\n this.fragCurrent = frag;\n this.startFragRequested = true;\n if (!isNaN(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n hls.trigger(Event.FRAG_LOADING, { frag });\n this.state = State.FRAG_LOADING;\n }\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\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 let 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 let 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 // 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\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 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 let 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 this.setInterval(100);\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 }\n this.tick();\n }\n\n onAudioTrackLoaded (data) {\n let 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 let 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\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 let 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 let 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\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 fragCurrent.addElementaryStream(Fragment.ElementaryStreamTypes.AUDIO);\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 let pendingData = this.pendingData;\n\n if (!pendingData) {\n logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');\n hls.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: null, fatal: true });\n return;\n }\n\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 onBufferReset () {\n // reset reference to sourcebuffers\n this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\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\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n const frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n break;\n }\n\n if (!data.fatal) {\n let loadError = this.fragLoadError;\n if (loadError) {\n loadError++;\n } else {\n loadError = 1;\n }\n\n const config = this.config;\n if (loadError <= config.fragLoadingMaxRetry) {\n this.fragLoadError = loadError;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n const 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.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, now switching 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(`AudioStreamController: reduce max buffer length to ${config.maxMaxBufferLength}s`);\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('AudioStreamController: 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('AudioStreamController: appending pending audio data after 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// WEBPACK FOOTER //\n// ./src/controller/audio-stream-controller.js","import { fixLineBreaks } from './vttparser';\n\nexport function newCue (track, startTime, endTime, captionScreen) {\n let row;\n let cue;\n let indenting;\n let indent;\n let text;\n let VTTCue = window.VTTCue || window.TextTrackCue;\n\n for (let r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty()) {\n for (let c = 0; c < row.chars.length; c++) {\n if (row.chars[c].uchar.match(/\\s/) && indenting) {\n indent++;\n } else {\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 endTime += 0.0001;\n }\n\n cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));\n\n if (indent >= 16) {\n indent--;\n } else {\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 cue.line = r + 1;\n } else {\n cue.line = (r > 7 ? r - 2 : r + 1);\n }\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// WEBPACK FOOTER //\n// ./src/utils/cues.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 let autoKeyword = 'auto';\n let directionSetting = {\n '': true,\n lr: true,\n rl: true\n };\n let 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\n let 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\n let align = alignSetting[value.toLowerCase()];\n return align ? value.toLowerCase() : false;\n }\n\n function extend (obj) {\n let i = 1;\n for (; i < arguments.length; i++) {\n let cobj = arguments[i];\n for (let p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue (startTime, endTime, text) {\n let cue = this;\n let isIE8 = (function () {\n if (typeof navigator === 'undefined') {\n return;\n }\n\n return (/MSIE\\s8\\.0/).test(navigator.userAgent);\n })();\n let 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 let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical = '';\n let _snapToLines = true;\n let _line = 'auto';\n let _lineAlign = 'start';\n let _position = 50;\n let _positionAlign = 'middle';\n let _size = 50;\n let _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\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\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 let 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\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\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 let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\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\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 let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\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\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 let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\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 let 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 * 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';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\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 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 this.captionsTracks = {};\n\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode\n }\n };\n\n if (this.config.enableCEA708Captions) {\n let channel1 = new OutputFilter(this, 'textTrack1');\n let channel2 = new OutputFilter(this, 'textTrack2');\n\n this.cea608Parser = new Cea608Parser(0, channel1, channel2);\n }\n }\n\n addCues (trackName, 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\n this.Cues.newCue(this.captionsTracks[trackName], 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 (trackName) {\n const { media } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n let textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n createCaptionsTrack (trackName) {\n const { label, languageCode } = this.captionsProperties[trackName];\n const captionsTracks = this.captionsTracks;\n if (!captionsTracks[trackName]) {\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], this.media);\n }\n }\n }\n\n createTextTrack (kind, label, lang) {\n const media = this.media;\n if (media) {\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 const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach(trackName => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n }\n\n onManifestLoading () {\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 _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\n if (track.default) {\n textTrack.mode = this.hls.subtitleDisplay ? 'showing' : 'hidden';\n } else {\n textTrack.mode = 'disabled';\n }\n\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 let 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 } // eslint-disable-line brace-style\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 let 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 } 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 // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n if (currentTrack.mode === 'disabled') {\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n return;\n }\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 );\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 let 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 (let i = 0; i < data.samples.length; i++) {\n let ccdatas = this.extractCea608Data(data.samples[i].bytes);\n this.cea608Parser.addData(data.samples[i].pts, ccdatas);\n }\n }\n }\n\n extractCea608Data (byteArray) {\n let count = byteArray[0] & 31;\n let position = 2;\n let tmpByte, ccbyte1, ccbyte2, ccValid, ccType;\n let actualCCBytes = [];\n\n for (let 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 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 *\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\nlet 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 */\nlet getCharForByte = function (byte) {\n let charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n\n return String.fromCharCode(charCode);\n};\n\nlet NR_ROWS = 15,\n NR_COLS = 100;\n// Tables to look up row from PAC data\nlet rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };\nlet rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };\nlet rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };\nlet rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };\n\nlet 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 */\nlet 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 let minLevel = this.verboseFilter[severity];\n if (this.verboseLevel >= minLevel) {\n // console.log(this.time + ' [' + severity + '] ' + msg);\n }\n }\n};\n\nlet numArrayToHexArray = function (numArray) {\n let hexArray = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\nclass PenState {\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 let attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (let i = 0; i < attribs.length; i++) {\n let 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 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 (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals (other) {\n let equal = true;\n for (let 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 (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty () {\n let empty = true;\n for (let 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\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 let newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let 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 let 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 let 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 let chars = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n let char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\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 let 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 constructor () {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row());\n } // 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 (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n }\n\n equals (other) {\n let equal = true;\n for (let 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 (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty () {\n let empty = true;\n for (let 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 let row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow () {\n let 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 let row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen (styles) {\n let row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor (relPos) {\n let row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor (absPos) {\n logger.log('INFO', 'setCursor: ' + absPos);\n let row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC (pacData) {\n logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));\n let 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 let 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 let 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 let row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n let indent = pacData.indent;\n let prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n let 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 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 let topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n let 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 let displayText = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n let 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 constructor (channelNumber, outputFilter) {\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\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 (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n\n let 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\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF () { // Reserved (formerly Alarm Off)\n\n }\n\n ccAON () { // Reserved (formerly Alarm On)\n\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 let 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 let styles = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n let colorIndex = Math.floor(secondByte / 2) - 0x10;\n let 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\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\n this.cueStartTime = t;\n }\n }\n }\n}\n\nclass Cea608Parser {\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 let cmdFound, a, b,\n charsFound = false;\n\n this.lastTime = t;\n logger.setTime(t);\n\n for (let 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\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n if (this.currChNr && this.currChNr >= 0) {\n let 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 let chNr = null;\n\n let cond1 = (a === 0x14 || a === 0x1C) && (b >= 0x20 && b <= 0x2F);\n let cond2 = (a === 0x17 || a === 0x1F) && (b >= 0x21 && 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;\n } // (a === 0x1C || a=== 0x1f)\n\n let 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 let chNr = null;\n\n if (((a === 0x11) || (a === 0x19)) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n\n if (chNr !== this.currChNr) {\n logger.log('ERROR', 'Mismatch channel in midrow parsing');\n return false;\n }\n let 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 let chNr = null;\n let row = null;\n\n let case1 = ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1F)) && (b >= 0x40 && b <= 0x7F);\n let case2 = (a === 0x10 || a === 0x18) && (b >= 0x40 && 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 (b >= 0x40 && 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 let pacData = this.interpretPAC(row, b);\n let 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 let pacIndex = byte;\n let 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\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 let 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 (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let 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\n logger.log('INFO', 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = (b === 0) ? [a] : [a, b];\n }\n if (charCodes) {\n let 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 let bkgData,\n index,\n chNr,\n channel;\n\n let case1 = (a === 0x10 || a === 0x18) && (b >= 0x20 && b <= 0x2f);\n let case2 = (a === 0x17 || a === 0x1f) && (b >= 0x2d && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\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 (let 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 (let 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 constructor (timelineController, trackName) {\n this.timelineController = timelineController;\n this.trackName = trackName;\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\n this.timelineController.addCues(this.trackName, 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\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\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\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 } 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 * 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 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 = null;\n\n /**\n * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering\n */\n this.subtitleDisplay = true;\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 === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\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) {\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\n if (this.useTextTrackPolling) {\n clearInterval(this.subtitlePollingInterval);\n } else {\n this.media.textTracks.removeEventListener('change', this.trackChangeListener);\n }\n\n this.media = null;\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 || details.live) {\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 this._stopTimer();\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) {\n this._toggleTrackModes(subtitleTrackId);\n this.setSubtitleTrackInternal(subtitleTrackId);\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n * @param newId - The id of the subtitle track to activate.\n */\n setSubtitleTrackInternal (newId) {\n const { hls, tracks } = this;\n if (typeof newId !== 'number' || newId < -1 || newId >= tracks.length) {\n return;\n }\n\n this._stopTimer();\n this.trackId = newId;\n logger.log(`switching to subtitle track ${newId}`);\n hls.trigger(Event.SUBTITLE_TRACK_SWITCH, { id: newId });\n if (newId === -1) {\n return;\n }\n\n // check if we need to load playlist for this subtitle Track\n const subtitleTrack = tracks[newId];\n const details = subtitleTrack.details;\n if (!details || details.live) {\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 hls.trigger(Event.SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId });\n }\n }\n\n _stopTimer () {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n * @param newId - The id of the next track to enable\n * @private\n */\n _toggleTrackModes (newId) {\n const { media, subtitleDisplay, trackId } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n if (newId === -1) {\n [].slice.call(textTracks).forEach(track => {\n track.mode = 'disabled';\n });\n } else {\n const oldTrack = textTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n const nextTrack = textTracks[newId];\n if (nextTrack) {\n nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';\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 { logger } from '../utils/logger';\nimport Decrypter from '../crypt/decrypter';\nimport TaskLoop from '../task-loop';\n\nconst { performance } = window;\n\nconst State = {\n STOPPED: 'STOPPED',\n IDLE: 'IDLE',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING'\n};\n\nclass SubtitleStreamController extends TaskLoop {\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\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.decrypter = new Decrypter(hls.observer, hls.config);\n }\n\n onHandlerDestroyed () {\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\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\n if (this.currentlyProcessing) {\n this.currentlyProcessing = null;\n this.nextFrag();\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 => {\n return fragInQueue.sn === frag.sn;\n });\n };\n\n // exit if tracks don't exist\n if (!tracks) {\n break;\n }\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.encrypted) {\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 if (!this.tracks || this.currentTrackId === -1) {\n return;\n }\n\n // Check if track was already loaded and if so make sure we finish\n // downloading its frags, if not all have been downloaded yet\n const currentTrack = this.tracks[this.currentTrackId];\n if (currentTrack && currentTrack.details) {\n this.tick();\n }\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 let 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 let 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 let 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 * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n *\n * DRM support for Hls.js\n */\n\nimport EventHandler from '../event-handler';\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\n\nconst { XMLHttpRequest } = window;\n\nconst MAX_LICENSE_REQUEST_FAILURES = 3;\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nconst KeySystems = {\n WIDEVINE: 'com.widevine.alpha',\n PLAYREADY: 'com.microsoft.playready'\n};\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @param {object} drmSystemOptions Optional parameters/requirements for the key-system\n * @returns {Array<MediaSystemConfiguration>} An array of supported configurations\n */\n\nconst createWidevineMediaKeySystemConfigurations = function (audioCodecs, videoCodecs, drmSystemOptions) { /* jshint ignore:line */\n const baseConfig = {\n // initDataTypes: ['keyids', 'mp4'],\n // label: \"\",\n // persistentState: \"not-allowed\", // or \"required\" ?\n // distinctiveIdentifier: \"not-allowed\", // or \"required\" ?\n // sessionTypes: ['temporary'],\n videoCapabilities: [\n // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n ]\n };\n\n videoCodecs.forEach((codec) => {\n baseConfig.videoCapabilities.push({\n contentType: `video/mp4; codecs=\"${codec}\"`\n });\n });\n\n return [\n baseConfig\n ];\n};\n\n/**\n * The idea here is to handle key-system (and their respective platforms) specific configuration differences\n * in order to work with the local requestMediaKeySystemAccess method.\n *\n * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`\n */\nconst getSupportedMediaKeySystemConfigurations = function (keySystem, audioCodecs, videoCodecs) {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);\n default:\n throw Error('Unknown key-system: ' + keySystem);\n }\n};\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\nclass EMEController extends EventHandler {\n /**\n * @constructs\n * @param {Hls} hls Our Hls.js instance\n */\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MANIFEST_PARSED\n );\n\n this._widevineLicenseUrl = hls.config.widevineLicenseUrl;\n this._licenseXhrSetup = hls.config.licenseXhrSetup;\n this._emeEnabled = hls.config.emeEnabled;\n\n this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;\n\n this._mediaKeysList = [];\n this._media = null;\n\n this._hasSetMediaKeys = false;\n this._isMediaEncrypted = false;\n\n this._requestLicenseFailureCount = 0;\n }\n\n /**\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @returns {string} License server URL for key-system (if any configured, otherwise causes error)\n */\n getLicenseServerUrl (keySystem) {\n let url;\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n url = this._widevineLicenseUrl;\n break;\n default:\n url = null;\n break;\n }\n\n if (!url) {\n logger.error(`No license server URL configured for key-system \"${keySystem}\"`);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n\n return url;\n }\n\n /**\n * Requests access object and adds it to our list upon success\n * @private\n * @param {string} keySystem System ID (see `KeySystems`)\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n */\n _attemptKeySystemAccess (keySystem, audioCodecs, videoCodecs) {\n // TODO: add other DRM \"options\"\n\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);\n\n if (!mediaKeySystemConfigs) {\n logger.warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);\n return;\n }\n\n logger.log('Requesting encrypted media key-system access');\n\n // expecting interface like window.navigator.requestMediaKeySystemAccess\n this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs)\n .then((mediaKeySystemAccess) => {\n this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);\n })\n .catch((err) => {\n logger.error(`Failed to obtain key-system \"${keySystem}\" access:`, err);\n });\n }\n\n get requestMediaKeySystemAccess () {\n if (!this._requestMediaKeySystemAccess) {\n throw new Error('No requestMediaKeySystemAccess function configured');\n }\n\n return this._requestMediaKeySystemAccess;\n }\n\n /**\n * Handles obtaining access to a key-system\n *\n * @param {string} keySystem\n * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess\n */\n _onMediaKeySystemAccessObtained (keySystem, mediaKeySystemAccess) {\n logger.log(`Access for key-system \"${keySystem}\" obtained`);\n\n const mediaKeysListItem = {\n mediaKeys: null,\n mediaKeysSession: null,\n mediaKeysSessionInitialized: false,\n mediaKeySystemAccess: mediaKeySystemAccess,\n mediaKeySystemDomain: keySystem\n };\n\n this._mediaKeysList.push(mediaKeysListItem);\n\n mediaKeySystemAccess.createMediaKeys()\n .then((mediaKeys) => {\n mediaKeysListItem.mediaKeys = mediaKeys;\n\n logger.log(`Media-keys created for key-system \"${keySystem}\"`);\n\n this._onMediaKeysCreated();\n })\n .catch((err) => {\n logger.error('Failed to create media-keys:', err);\n });\n }\n\n /**\n * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this\n * for all existing keys where no session exists yet.\n */\n _onMediaKeysCreated () {\n // check for all key-list items if a session exists, otherwise, create one\n this._mediaKeysList.forEach((mediaKeysListItem) => {\n if (!mediaKeysListItem.mediaKeysSession) {\n mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();\n this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);\n }\n });\n }\n\n /**\n *\n * @param {*} keySession\n */\n _onNewMediaKeySession (keySession) {\n logger.log(`New key-system session ${keySession.sessionId}`);\n\n keySession.addEventListener('message', (event) => {\n this._onKeySessionMessage(keySession, event.message);\n }, false);\n }\n\n _onKeySessionMessage (keySession, message) {\n logger.log('Got EME message event, creating license request');\n\n this._requestLicense(message, (data) => {\n logger.log('Received license data, updating key-session');\n keySession.update(data);\n });\n }\n\n _onMediaEncrypted (initDataType, initData) {\n logger.log(`Media is encrypted using \"${initDataType}\" init data type`);\n\n this._isMediaEncrypted = true;\n this._mediaEncryptionInitDataType = initDataType;\n this._mediaEncryptionInitData = initData;\n\n this._attemptSetMediaKeys();\n this._generateRequestWithPreferredKeySession();\n }\n\n _attemptSetMediaKeys () {\n if (!this._hasSetMediaKeys) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem || !keysListItem.mediaKeys) {\n logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n fatal: true\n });\n return;\n }\n\n logger.log('Setting keys for encrypted media');\n\n this._media.setMediaKeys(keysListItem.mediaKeys);\n this._hasSetMediaKeys = true;\n }\n }\n\n _generateRequestWithPreferredKeySession () {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n if (keysListItem.mediaKeysSessionInitialized) {\n logger.warn('Key-Session already initialized but requested again');\n return;\n }\n\n const keySession = keysListItem.mediaKeysSession;\n if (!keySession) {\n logger.error('Fatal: Media is encrypted but no key-session existing');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: true\n });\n }\n\n const initDataType = this._mediaEncryptionInitDataType;\n const initData = this._mediaEncryptionInitData;\n\n logger.log(`Generating key-session request for \"${initDataType}\" init data type`);\n\n keysListItem.mediaKeysSessionInitialized = true;\n\n keySession.generateRequest(initDataType, initData)\n .then(() => {\n logger.debug('Key-session generation succeeded');\n })\n .catch((err) => {\n logger.error('Error generating key-session request:', err);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: false\n });\n });\n }\n\n /**\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n * @returns {XMLHttpRequest} Unsent (but opened state) XHR object\n */\n _createLicenseXhr (url, keyMessage, callback) {\n const xhr = new XMLHttpRequest();\n const licenseXhrSetup = this._licenseXhrSetup;\n\n try {\n if (licenseXhrSetup) {\n try {\n licenseXhrSetup(xhr, url);\n } catch (e) {\n // let's try to open before running setup\n xhr.open('POST', url, true);\n licenseXhrSetup(xhr, url);\n }\n }\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n logger.error('Error setting up key-system license XHR', e);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n return;\n }\n\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange =\n this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);\n return xhr;\n }\n\n /**\n * @param {XMLHttpRequest} xhr\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n *\n */\n _onLicenseRequestReadyStageChange (xhr, url, keyMessage, callback) {\n switch (xhr.readyState) {\n case 4:\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n logger.log('License request succeeded');\n callback(xhr.response);\n } else {\n logger.error(`License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`);\n\n this._requestLicenseFailureCount++;\n if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {\n const attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;\n logger.warn(`Retrying license request, ${attemptsLeft} attempts left`);\n this._requestLicense(keyMessage, callback);\n return;\n }\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n break;\n }\n }\n\n /**\n * @param {object} keysListItem\n * @param {ArrayBuffer} keyMessage\n * @returns {ArrayBuffer} Challenge data posted to license server\n */\n _generateLicenseRequestChallenge (keysListItem, keyMessage) {\n let challenge;\n\n if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {\n logger.error('PlayReady is not supported (yet)');\n\n // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js\n /*\n if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');\n if (keyMessageXml.getElementsByTagName('Challenge')[0]) {\n challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);\n } else {\n throw 'Cannot find <Challenge> in key message';\n }\n var headerNames = keyMessageXml.getElementsByTagName('name');\n var headerValues = keyMessageXml.getElementsByTagName('value');\n if (headerNames.length !== headerValues.length) {\n throw 'Mismatched header <name>/<value> pair in key message';\n }\n for (var i = 0; i < headerNames.length; i++) {\n xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);\n }\n }\n */\n } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {\n // For Widevine CDMs, the challenge is the keyMessage.\n challenge = keyMessage;\n } else {\n logger.error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);\n }\n\n return challenge;\n }\n\n _requestLicense (keyMessage, callback) {\n logger.log('Requesting content license for key-system');\n\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n const url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);\n const xhr = this._createLicenseXhr(url, keyMessage, callback);\n\n logger.log(`Sending license request to URL: ${url}`);\n\n xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));\n }\n\n onMediaAttached (data) {\n if (!this._emeEnabled) {\n return;\n }\n\n const media = data.media;\n\n // keep reference of media\n this._media = media;\n\n // FIXME: also handle detaching media !\n\n media.addEventListener('encrypted', (e) => {\n this._onMediaEncrypted(e.initDataType, e.initData);\n });\n }\n\n onManifestParsed (data) {\n if (!this._emeEnabled) {\n return;\n }\n\n const audioCodecs = data.levels.map((level) => level.audioCodec);\n const videoCodecs = data.levels.map((level) => level.videoCodec);\n\n this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);\n }\n}\n\nexport default EMEController;\n\n\n\n// WEBPACK FOOTER //\n// ./src/controller/eme-controller.js","const requestMediaKeySystemAccess = (function () {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {\n return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);\n } else {\n return null;\n }\n})();\n\nexport {\n requestMediaKeySystemAccess\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/mediakeys-helper.js","/*! http://mths.be/endswith v0.2.0 by @mathias */\nif (!String.prototype.endsWith) {\n\t(function() {\n\t\t'use strict'; // needed to support `apply`/`call` with `undefined`/`null`\n\t\tvar defineProperty = (function() {\n\t\t\t// IE 8 only supports `Object.defineProperty` on DOM elements\n\t\t\ttry {\n\t\t\t\tvar object = {};\n\t\t\t\tvar $defineProperty = Object.defineProperty;\n\t\t\t\tvar result = $defineProperty(object, object, object) && $defineProperty;\n\t\t\t} catch(error) {}\n\t\t\treturn result;\n\t\t}());\n\t\tvar toString = {}.toString;\n\t\tvar endsWith = function(search) {\n\t\t\tif (this == null) {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar string = String(this);\n\t\t\tif (search && toString.call(search) == '[object RegExp]') {\n\t\t\t\tthrow TypeError();\n\t\t\t}\n\t\t\tvar stringLength = string.length;\n\t\t\tvar searchString = String(search);\n\t\t\tvar searchLength = searchString.length;\n\t\t\tvar pos = stringLength;\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tvar position = arguments[1];\n\t\t\t\tif (position !== undefined) {\n\t\t\t\t\t// `ToInteger`\n\t\t\t\t\tpos = position ? Number(position) : 0;\n\t\t\t\t\tif (pos != pos) { // better `isNaN`\n\t\t\t\t\t\tpos = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar end = Math.min(Math.max(pos, 0), stringLength);\n\t\t\tvar start = end - searchLength;\n\t\t\tif (start < 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvar index = -1;\n\t\t\twhile (++index < searchLength) {\n\t\t\t\tif (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\tif (defineProperty) {\n\t\t\tdefineProperty(String.prototype, 'endsWith', {\n\t\t\t\t'value': endsWith,\n\t\t\t\t'configurable': true,\n\t\t\t\t'writable': true\n\t\t\t});\n\t\t} else {\n\t\t\tString.prototype.endsWith = endsWith;\n\t\t}\n\t}());\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./node_modules/string.prototype.endswith/endswith.js\n// module id = 72\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/grails-app/assets/javascripts/streama/directives/streama-video-player-directive.js b/grails-app/assets/javascripts/streama/directives/streama-video-player-directive.js index 39f67981f..806579eb7 100644 --- a/grails-app/assets/javascripts/streama/directives/streama-video-player-directive.js +++ b/grails-app/assets/javascripts/streama/directives/streama-video-player-directive.js @@ -48,6 +48,7 @@ angular.module('streama').directive('streamaVideoPlayer', [ $scope.loading = true; $scope.initialPlay = false; + if (!$scope.options.isExternalLink) { $http.head(videoSrc) .then(function () { @@ -77,10 +78,13 @@ angular.module('streama').directive('streamaVideoPlayer', [ $scope.$on('$stateChangeSuccess', onStateChangeSuccess); $timeout(function () { + var $video = $elem.find('video'); $video.bind("contextmenu", function () { return false; + }); + video = $video[0]; video.oncanplay = oncanplay; video.onwaiting = onwaiting; @@ -88,6 +92,7 @@ angular.module('streama').directive('streamaVideoPlayer', [ video.onerror = onerror; video.ontimeupdate = ontimeupdate; video.addEventListener('ended', onVideoEnded); + $scope.scrubberOptions = generateScrupperOoptions(); $scope.volumeScrubberOptions = generateVolumeScrubberOptions(); $scope.volumeLevel = localStorageService.get('volumeLevel') || 5; @@ -103,6 +108,8 @@ angular.module('streama').directive('streamaVideoPlayer', [ var selectedVideoFile = _.find($scope.options.videoFiles, {label: savedVideoFileLabel}); changeVideoFile(selectedVideoFile); } + + //Autoloads sub#0 if the setting is true on Admin>Settings, and if the subtitle exists (by Norwelian) var sub_auto_load_value = false; apiService.settings.list().then(function(data){ @@ -114,11 +121,18 @@ angular.module('streama').directive('streamaVideoPlayer', [ hideSubtitle(); changeSubtitle($scope.options.subtitles[0]); } + }); $scope.options.subtitleSize = localStorageService.get('subtitleSize') || 'md'; $scope.options.hasCustomSubtitleSize = localStorageService.get('hasCustomSubtitleSize') || false; $scope.options.customSubtitleSize = localStorageService.get('customSubtitleSize') || null; +// HLS Support + if (Hls.isSupported()) { + var hls = new Hls(); + hls.loadSource(videoSrc); + hls.attachMedia(video); + } }); } diff --git a/grails-app/assets/javascripts/vendor.js b/grails-app/assets/javascripts/vendor.js index dd5fc88c2..94782409f 100644 --- a/grails-app/assets/javascripts/vendor.js +++ b/grails-app/assets/javascripts/vendor.js @@ -25,4 +25,4 @@ //= require ui-select/select //= require jquery-mousewheel/jquery.mousewheel //= require owl.carousel/owl.carousel - +//= require hls.js/dist/hls.min diff --git a/grails-app/conf/application.yml b/grails-app/conf/application.yml index 9ed7d2573..92c0c8ec2 100644 --- a/grails-app/conf/application.yml +++ b/grails-app/conf/application.yml @@ -164,7 +164,7 @@ streama: opensubtitleUrl: 'https://rest.opensubtitles.org/search' - uploadtypes: ['video/h264', 'video/mp4', 'video/mpeg', 'video/quicktime', 'video/webm', 'video/x-ms-wm', 'video/x-ms-wmv', + uploadtypes: ['video/h264', 'video/mp4', 'application/vnd.apple.mpegurl', 'video/mpeg', 'video/quicktime', 'video/webm', 'video/x-ms-wm', 'video/x-ms-wmv', 'video/x-msvideo', 'image/bmp', 'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/svg+xml', 'image/x-icon', 'image/x-png', 'application/x-subrip', 'text/plain', 'text/vtt', 'text/plain', 'application/octet-stream', 'video/x-matroska', 'image/vnd.microsoft.icon', 'video/mp2t']