@eluvio/elv-player-js 1.0.62 → 1.0.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/7.bundle.js DELETED
@@ -1,357 +0,0 @@
1
- (window.webpackJsonp=window.webpackJsonp||[]).push([[7],{634:function(e,t,r){"undefined"!=typeof window&&function webpackUniversalModuleDefinition(t,r){e.exports=r()}(0,(function(){return function(e){var t={};function __webpack_require__(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,__webpack_require__),i.l=!0,i.exports}return __webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.d=function(e,t,r){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.t=function(e,t){if(1&t&&(e=__webpack_require__(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(__webpack_require__.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)__webpack_require__.d(r,i,function(t){return e[t]}.bind(null,i));return r},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="/dist/",__webpack_require__(__webpack_require__.s="./src/hls.ts")}({"./node_modules/eventemitter3/index.js":
2
- /*!*********************************************!*\
3
- !*** ./node_modules/eventemitter3/index.js ***!
4
- \*********************************************/
5
- /*! no static exports found */function(e,t,r){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function Events(){}function EE(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function addListener(e,t,r,i,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new EE(r,i||e,a),o=n?n+t:t;return e._events[o]?e._events[o].fn?e._events[o]=[e._events[o],s]:e._events[o].push(s):(e._events[o]=s,e._eventsCount++),e}function clearEvent(e,t){0==--e._eventsCount?e._events=new Events:delete e._events[t]}function EventEmitter(){this._events=new Events,this._eventsCount=0}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(n=!1)),EventEmitter.prototype.eventNames=function eventNames(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},EventEmitter.prototype.listeners=function listeners(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,a=r.length,s=new Array(a);i<a;i++)s[i]=r[i].fn;return s},EventEmitter.prototype.listenerCount=function listenerCount(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},EventEmitter.prototype.emit=function emit(e,t,r,i,a,s){var o=n?n+e:e;if(!this._events[o])return!1;var l,u,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,i),!0;case 5:return d.fn.call(d.context,t,r,i,a),!0;case 6:return d.fn.call(d.context,t,r,i,a,s),!0}for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d.fn.apply(d.context,l)}else{var h,f=d.length;for(u=0;u<f;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),c){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,t);break;case 3:d[u].fn.call(d[u].context,t,r);break;case 4:d[u].fn.call(d[u].context,t,r,i);break;default:if(!l)for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d[u].fn.apply(d[u].context,l)}}return!0},EventEmitter.prototype.on=function on(e,t,r){return addListener(this,e,t,r,!1)},EventEmitter.prototype.once=function once(e,t,r){return addListener(this,e,t,r,!0)},EventEmitter.prototype.removeListener=function removeListener(e,t,r,i){var a=n?n+e:e;if(!this._events[a])return this;if(!t)return clearEvent(this,a),this;var s=this._events[a];if(s.fn)s.fn!==t||i&&!s.once||r&&s.context!==r||clearEvent(this,a);else{for(var o=0,l=[],u=s.length;o<u;o++)(s[o].fn!==t||i&&!s[o].once||r&&s[o].context!==r)&&l.push(s[o]);l.length?this._events[a]=1===l.length?l[0]:l:clearEvent(this,a)}return this},EventEmitter.prototype.removeAllListeners=function removeAllListeners(e){var t;return e?(t=n?n+e:e,this._events[t]&&clearEvent(this,t)):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prefixed=n,EventEmitter.EventEmitter=EventEmitter,e.exports=EventEmitter},"./node_modules/url-toolkit/src/url-toolkit.js":
6
- /*!*****************************************************!*\
7
- !*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
8
- \*****************************************************/
9
- /*! no static exports found */function(e,t,r){var i,n,a,s,o;i=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/,n=/^([^\/?#]*)([^]*)$/,a=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=o.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=o.normalizePath(i.path),o.buildURLFromParts(i)}var a=o.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=o.normalizePath(a.path),o.buildURLFromParts(a)):t;var s=o.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");if(!s.netLoc&&s.path&&"/"!==s.path[0]){var l=n.exec(s.path);s.netLoc=l[1],s.path=l[2]}s.netLoc&&!s.path&&(s.path="/");var u={scheme:s.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(u.netLoc=s.netLoc,"/"!==a.path[0]))if(a.path){var d=s.path,c=d.substring(0,d.lastIndexOf("/")+1)+a.path;u.path=o.normalizePath(c)}else u.path=s.path,a.params||(u.params=s.params,a.query||(u.query=s.query));return null===u.path&&(u.path=r.alwaysNormalize?o.normalizePath(a.path):a.path),o.buildURLFromParts(u)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(a,"");e.length!==(e=e.replace(s,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=o},"./node_modules/webworkify-webpack/index.js":
10
- /*!**************************************************!*\
11
- !*** ./node_modules/webworkify-webpack/index.js ***!
12
- \**************************************************/
13
- /*! no static exports found */function(e,t,r){function webpackBootstrapFunc(e){var t={};function __webpack_require__(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,__webpack_require__),i.l=!0,i.exports}__webpack_require__.m=e,__webpack_require__.c=t,__webpack_require__.i=function(e){return e},__webpack_require__.d=function(e,t,r){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},__webpack_require__.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.n=function(e){var t=e&&e.__esModule?function getDefault(){return e.default}:function getModuleExports(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="/",__webpack_require__.oe=function(e){throw console.error(e),e};var r=__webpack_require__(__webpack_require__.s=ENTRY_MODULE);return r.default||r}var i="\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)";function quoteRegExp(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function getModuleDependencies(e,t,n){var a={};a[n]=[];var s=t.toString(),o=s.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);if(!o)return a;for(var l,u=o[1],d=new RegExp("(\\\\n|\\W)"+quoteRegExp(u)+i,"g");l=d.exec(s);)"dll-reference"!==l[3]&&a[n].push(l[3]);for(d=new RegExp("\\("+quoteRegExp(u)+'\\("(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))"\\)\\)'+i,"g");l=d.exec(s);)e[l[2]]||(a[n].push(l[1]),e[l[2]]=r(l[1]).m),a[l[2]]=a[l[2]]||[],a[l[2]].push(l[4]);for(var c,h=Object.keys(a),f=0;f<h.length;f++)for(var g=0;g<a[h[f]].length;g++)c=a[h[f]][g],isNaN(1*c)||(a[h[f]][g]=1*a[h[f]][g]);return a}function hasValuesInQueues(e){return Object.keys(e).reduce((function(t,r){return t||e[r].length>0}),!1)}e.exports=function(e,t){t=t||{};var i={main:r.m},n=t.all?{main:Object.keys(i.main)}:function getRequiredModules(e,t){for(var r={main:[t]},i={main:[]},n={main:{}};hasValuesInQueues(r);)for(var a=Object.keys(r),s=0;s<a.length;s++){var o=a[s],l=r[o].pop();if(n[o]=n[o]||{},!n[o][l]&&e[o][l]){n[o][l]=!0,i[o]=i[o]||[],i[o].push(l);for(var u=getModuleDependencies(e,e[o][l],o),d=Object.keys(u),c=0;c<d.length;c++)r[d[c]]=r[d[c]]||[],r[d[c]]=r[d[c]].concat(u[d[c]])}}return i}(i,e),a="";Object.keys(n).filter((function(e){return"main"!==e})).forEach((function(e){for(var t=0;n[e][t];)t++;n[e].push(t),i[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",a=a+"var "+e+" = ("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+n[e].map((function(t){return JSON.stringify(t)+": "+i[e][t].toString()})).join(",")+"});\n"})),a=a+"new (("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+n.main.map((function(e){return JSON.stringify(e)+": "+i.main[e].toString()})).join(",")+"}))(self);";var s=new window.Blob([a],{type:"text/javascript"});if(t.bare)return s;var o=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(s),l=new window.Worker(o);return l.objectURL=o,l}},"./src/config.ts":
14
- /*!***********************!*\
15
- !*** ./src/config.ts ***!
16
- \***********************/
17
- /*! exports provided: hlsDefaultConfig, mergeConfig, enableStreamingMode */function(e,t,r){"use strict";r.r(t),r.d(t,"hlsDefaultConfig",(function(){return y})),r.d(t,"mergeConfig",(function(){return mergeConfig})),r.d(t,"enableStreamingMode",(function(){return enableStreamingMode}));var i=r(/*! ./controller/abr-controller */"./src/controller/abr-controller.ts"),n=r(/*! ./controller/audio-stream-controller */"./src/controller/audio-stream-controller.ts"),a=r(/*! ./controller/audio-track-controller */"./src/controller/audio-track-controller.ts"),s=r(/*! ./controller/subtitle-stream-controller */"./src/controller/subtitle-stream-controller.ts"),o=r(/*! ./controller/subtitle-track-controller */"./src/controller/subtitle-track-controller.ts"),l=r(/*! ./controller/buffer-controller */"./src/controller/buffer-controller.ts"),u=r(/*! ./controller/timeline-controller */"./src/controller/timeline-controller.ts"),d=r(/*! ./controller/cap-level-controller */"./src/controller/cap-level-controller.ts"),c=r(/*! ./controller/fps-controller */"./src/controller/fps-controller.ts"),h=r(/*! ./controller/eme-controller */"./src/controller/eme-controller.ts"),f=r(/*! ./utils/xhr-loader */"./src/utils/xhr-loader.ts"),g=r(/*! ./utils/fetch-loader */"./src/utils/fetch-loader.ts"),v=r(/*! ./utils/cues */"./src/utils/cues.ts"),p=r(/*! ./utils/mediakeys-helper */"./src/utils/mediakeys-helper.ts"),m=r(/*! ./utils/logger */"./src/utils/logger.ts");function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e}).apply(this,arguments)}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var y=_objectSpread(_objectSpread({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,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:f.default,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:i.default,bufferController:l.default,capLevelController:d.default,fpsController:c.default,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,drmSystemOptions:{},requestMediaKeySystemAccessFunc:p.requestMediaKeySystemAccess,testBandwidth:!0,progressive:!1,lowLatencyMode:!0},function timelineConfig(){return{cueHandler:v.default,enableCEA708Captions:!0,enableWebVTT:!0,enableIMSC1:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}()),{},{subtitleStreamController:s.SubtitleStreamController,subtitleTrackController:o.default,timelineController:u.TimelineController,audioStreamController:n.default,audioTrackController:a.default,emeController:h.default});function mergeConfig(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');return _extends({},e,t)}function enableStreamingMode(e){var t=e.loader;t!==g.default&&t!==f.default?(m.logger.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):Object(g.fetchSupported)()&&(e.loader=g.default,e.progressive=!0,e.enableSoftwareAES=!0,m.logger.log("[config]: Progressive streaming enabled, using FetchLoader"))}},"./src/controller/abr-controller.ts":
18
- /*!******************************************!*\
19
- !*** ./src/controller/abr-controller.ts ***!
20
- \******************************************/
21
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../utils/ewma-bandwidth-estimator */"./src/utils/ewma-bandwidth-estimator.ts"),a=r(/*! ../events */"./src/events.ts"),s=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),o=r(/*! ../errors */"./src/errors.ts"),l=r(/*! ../types/loader */"./src/types/loader.ts"),u=r(/*! ../utils/logger */"./src/utils/logger.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var d=function(){function AbrController(e){this.hls=void 0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=void 0,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;var t=e.config;this.bwEstimator=new n.default(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}var e=AbrController.prototype;return e.registerListeners=function registerListeners(){var e=this.hls;e.on(a.Events.FRAG_LOADING,this.onFragLoading,this),e.on(a.Events.FRAG_LOADED,this.onFragLoaded,this),e.on(a.Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(a.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(a.Events.ERROR,this.onError,this)},e.unregisterListeners=function unregisterListeners(){var e=this.hls;e.off(a.Events.FRAG_LOADING,this.onFragLoading,this),e.off(a.Events.FRAG_LOADED,this.onFragLoaded,this),e.off(a.Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(a.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(a.Events.ERROR,this.onError,this)},e.destroy=function destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null},e.onFragLoading=function onFragLoading(e,t){var r,i=t.frag;i.type===l.PlaylistLevelType.MAIN&&(this.timer||(this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null,this.timer=self.setInterval(this.onCheck,100)))},e.onLevelLoaded=function onLevelLoaded(e,t){var r=this.hls.config;t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)},e._abandonRulesCheck=function _abandonRulesCheck(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls,n=r.autoLevelEnabled,o=r.config,l=r.media;if(e&&l){var d=t?t.stats:e.stats,c=t?t.duration:e.duration;if(d.aborted)return u.logger.warn("frag loader destroy or aborted, disarm abandonRules"),this.clearTimer(),void(this._nextAutoLevel=-1);if(n&&!l.paused&&l.playbackRate&&l.readyState){var h=performance.now()-d.loading.start,f=Math.abs(l.playbackRate);if(!(h<=500*c/f)){var g=r.levels,v=r.minAutoLevel,p=g[e.level],m=d.total||Math.max(d.loaded,Math.round(c*p.maxBitrate/8)),y=Math.max(1,d.bwEstimate?d.bwEstimate/8:1e3*d.loaded/h),E=(m-d.loaded)/y,T=l.currentTime,S=(s.BufferHelper.bufferInfo(l,T,o.maxBufferHole).end-T)/f;if(!(S>=2*c/f||E<=S)){var b,L=Number.POSITIVE_INFINITY;for(b=e.level-1;b>v;b--){if((L=c*g[b].maxBitrate/(6.4*y))<S)break}if(!(L>=E)){var A=this.bwEstimator.getEstimate();u.logger.warn("Fragment "+e.sn+(t?" part "+t.index:"")+" of level "+e.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+b+"\n Current BW estimate: "+(Object(i.isFiniteNumber)(A)?(A/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+E.toFixed(3)+" s\n Estimated load time for the next fragment: "+L.toFixed(3)+" s\n Time to underbuffer: "+S.toFixed(3)+" s"),r.nextLoadLevel=b,this.bwEstimator.sample(h,d.loaded),this.clearTimer(),e.loader&&(this.fragCurrent=this.partCurrent=null,e.loader.abort()),r.trigger(a.Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:d})}}}}}},e.onFragLoaded=function onFragLoaded(e,t){var r=t.frag,n=t.part;if(r.type===l.PlaylistLevelType.MAIN&&Object(i.isFiniteNumber)(r.sn)){var s=n?n.stats:r.stats,o=n?n.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var u=this.hls.levels[r.level],d=(u.loaded?u.loaded.bytes:0)+s.loaded,c=(u.loaded?u.loaded.duration:0)+o;u.loaded={bytes:d,duration:c},u.realBitrate=Math.round(8*d/c)}if(r.bitrateTest){var h={stats:s,frag:r,part:n,id:r.type};this.onFragBuffered(a.Events.FRAG_BUFFERED,h),r.bitrateTest=!1}}},e.onFragBuffered=function onFragBuffered(e,t){var r=t.frag,i=t.part,n=i?i.stats:r.stats;if(!n.aborted&&r.type===l.PlaylistLevelType.MAIN&&"initSegment"!==r.sn){var a=n.parsing.end-n.loading.start;this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}},e.onError=function onError(e,t){switch(t.details){case o.ErrorDetails.FRAG_LOAD_ERROR:case o.ErrorDetails.FRAG_LOAD_TIMEOUT:this.clearTimer()}},e.clearTimer=function clearTimer(){self.clearInterval(this.timer),this.timer=void 0},e.getNextABRAutoLevel=function getNextABRAutoLevel(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls,i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,o=r.media,l=t?t.duration:e?e.duration:0,d=o?o.currentTime:0,c=o&&0!==o.playbackRate?Math.abs(o.playbackRate):1,h=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,f=(s.BufferHelper.bufferInfo(o,d,n.maxBufferHole).end-d)/c,g=this.findBestLevel(h,a,i,f,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(g>=0)return g;u.logger.trace((f?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var v=l?Math.min(l,n.maxStarvationDelay):n.maxStarvationDelay,p=n.abrBandWidthFactor,m=n.abrBandWidthUpFactor;if(!f){var y=this.bitrateTestDelay;if(y)v=(l?Math.min(l,n.maxLoadingDelay):n.maxLoadingDelay)-y,u.logger.trace("bitrate test took "+Math.round(1e3*y)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*v)+" ms"),p=m=1}return g=this.findBestLevel(h,a,i,f+v,p,m),Math.max(g,0)},e.findBestLevel=function findBestLevel(e,t,r,i,n,a){for(var s,o=this.fragCurrent,l=this.partCurrent,d=this.lastLoadedFragLevel,c=this.hls.levels,h=c[d],f=!(null==h||null===(s=h.details)||void 0===s||!s.live),g=null==h?void 0:h.codecSet,v=l?l.duration:o?o.duration:0,p=r;p>=t;p--){var m=c[p];if(m&&(!g||m.codecSet===g)){var y=m.details,E=(l?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||v,T=void 0;T=p<=d?n*e:a*e;var S=c[p].maxBitrate,b=S*E/T;if(u.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+p+"/"+Math.round(T)+"/"+S+"/"+E+"/"+i+"/"+b),T>S&&(!b||f&&!this.bitrateTestDelay||b<i))return p}}return-1},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(AbrController,[{key:"nextAutoLevel",get:function get(){var e=this._nextAutoLevel,t=this.bwEstimator;if(!(-1===e||t&&t.canEstimate()))return e;var r=this.getNextABRAutoLevel();return-1!==e&&(r=Math.min(e,r)),r},set:function set(e){this._nextAutoLevel=e}}]),AbrController}();t.default=d},"./src/controller/audio-stream-controller.ts":
22
- /*!***************************************************!*\
23
- !*** ./src/controller/audio-stream-controller.ts ***!
24
- \***************************************************/
25
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./base-stream-controller */"./src/controller/base-stream-controller.ts"),a=r(/*! ../events */"./src/events.ts"),s=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),o=r(/*! ./fragment-tracker */"./src/controller/fragment-tracker.ts"),l=r(/*! ../types/level */"./src/types/level.ts"),u=r(/*! ../types/loader */"./src/types/loader.ts"),d=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),c=r(/*! ../demux/chunk-cache */"./src/demux/chunk-cache.ts"),h=r(/*! ../demux/transmuxer-interface */"./src/demux/transmuxer-interface.ts"),f=r(/*! ../types/transmuxer */"./src/types/transmuxer.ts"),g=r(/*! ./fragment-finders */"./src/controller/fragment-finders.ts"),v=r(/*! ../utils/discontinuities */"./src/utils/discontinuities.ts"),p=r(/*! ../errors */"./src/errors.ts"),m=r(/*! ../utils/logger */"./src/utils/logger.ts");function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e}).apply(this,arguments)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var y=function(e){function AudioStreamController(t,r){var i;return(i=e.call(this,t,r,"[audio-stream-controller]")||this).videoBuffer=null,i.videoTrackCC=-1,i.waitingVideoCC=-1,i.audioSwitch=!1,i.trackId=-1,i.waitingData=null,i.mainDetails=null,i.bufferFlushed=!1,i._registerListeners(),i}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(AudioStreamController,e);var t=AudioStreamController.prototype;return t.onHandlerDestroying=function onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null},t._registerListeners=function _registerListeners(){var e=this.hls;e.on(a.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(a.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(a.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(a.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(a.Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(a.Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(a.Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(a.Events.ERROR,this.onError,this),e.on(a.Events.BUFFER_RESET,this.onBufferReset,this),e.on(a.Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(a.Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(a.Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(a.Events.FRAG_BUFFERED,this.onFragBuffered,this)},t._unregisterListeners=function _unregisterListeners(){var e=this.hls;e.off(a.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(a.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(a.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(a.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(a.Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(a.Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(a.Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(a.Events.ERROR,this.onError,this),e.off(a.Events.BUFFER_RESET,this.onBufferReset,this),e.off(a.Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(a.Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(a.Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(a.Events.FRAG_BUFFERED,this.onFragBuffered,this)},t.onInitPtsFound=function onInitPtsFound(e,t){var r=t.frag,i=t.id,a=t.initPTS;if("main"===i){var s=r.cc;this.initPTS[r.cc]=a,this.log("InitPTS for cc: "+s+" found from main: "+a),this.videoTrackCC=s,this.state===n.State.WAITING_INIT_PTS&&this.tick()}},t.startLoad=function startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=n.State.STOPPED);var t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),this.fragLoadError=0,t>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=n.State.IDLE):(this.loadedmetadata=!1,this.state=n.State.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()},t.doTick=function doTick(){switch(this.state){case n.State.IDLE:this.doTickIdle();break;case n.State.WAITING_TRACK:var t,r=this.levels,i=this.trackId,a=null==r?void 0:null===(t=r[i])||void 0===t?void 0:t.details;if(a){if(this.waitForCdnTuneIn(a))break;this.state=n.State.WAITING_INIT_PTS}break;case n.State.FRAG_LOADING_WAITING_RETRY:var o,l=performance.now(),u=this.retryDate;(!u||l>=u||null!==(o=this.media)&&void 0!==o&&o.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.state=n.State.IDLE);break;case n.State.WAITING_INIT_PTS:var d=this.waitingData;if(d){var c=d.frag,h=d.part,f=d.cache,v=d.complete;if(void 0!==this.initPTS[c.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=n.State.FRAG_LOADING;var p={frag:c,part:h,payload:f.flush(),networkDetails:null};this._handleFragmentLoadProgress(p),v&&e.prototype._handleFragmentLoadComplete.call(this,p)}else if(this.videoTrackCC!==this.waitingVideoCC)m.logger.log("Waiting fragment cc ("+c.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var y=this.getLoadPosition(),E=s.BufferHelper.bufferInfo(this.mediaBuffer,y,this.config.maxBufferHole);Object(g.fragmentWithinToleranceTest)(E.end,this.config.maxFragLookUpTolerance,c)<0&&(m.logger.log("Waiting fragment cc ("+c.cc+") @ "+c.start+" cancelled because another fragment at "+E.end+" is needed"),this.clearWaitingFragment())}}else this.state=n.State.IDLE}this.onTickEnd()},t.clearWaitingFragment=function clearWaitingFragment(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=n.State.IDLE)},t.onTickEnd=function onTickEnd(){var e=this.media;if(e&&e.readyState){var t=(this.mediaBuffer?this.mediaBuffer:e).buffered;!this.loadedmetadata&&t.length&&(this.loadedmetadata=!0),this.lastCurrentTime=e.currentTime}},t.doTickIdle=function doTickIdle(){var e,t,r=this.hls,i=this.levels,s=this.media,o=this.trackId,l=r.config;if(i&&i[o]&&(s||!this.startFragRequested&&l.startFragPrefetch)){var c=i[o].details;if(!c||c.live&&this.levelLastLoaded!==o||this.waitForCdnTuneIn(c))this.state=n.State.WAITING_TRACK;else{this.bufferFlushed&&(this.bufferFlushed=!1,this.afterBufferFlushed(this.mediaBuffer?this.mediaBuffer:this.media,d.ElementaryStreamTypes.AUDIO,u.PlaylistLevelType.AUDIO));var h=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,u.PlaylistLevelType.AUDIO);if(null!==h){var f=h.len,g=this.getMaxBufferLength(),v=this.audioSwitch;if(!(f>=g)||v){if(!v&&this._streamEnded(h,c))return r.trigger(a.Events.BUFFER_EOS,{type:"audio"}),void(this.state=n.State.ENDED);var p=c.fragments[0].start,m=h.end;if(v){var y=this.getLoadPosition();m=y,c.PTSKnown&&y<p&&(h.end>p||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=p+.05)}var E=this.getNextFragment(m,c);E?"identity"!==(null===(e=E.decryptdata)||void 0===e?void 0:e.keyFormat)||null!==(t=E.decryptdata)&&void 0!==t&&t.key?this.loadFragment(E,c,m):this.loadKey(E,c):this.bufferFlushed=!0}}}}},t.getMaxBufferLength=function getMaxBufferLength(){var t=e.prototype.getMaxBufferLength.call(this),r=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,u.PlaylistLevelType.MAIN);return null===r?t:Math.max(t,r.len)},t.onMediaDetaching=function onMediaDetaching(){this.videoBuffer=null,e.prototype.onMediaDetaching.call(this)},t.onAudioTracksUpdated=function onAudioTracksUpdated(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(e){return new l.Level(e)}))},t.onAudioTrackSwitching=function onAudioTrackSwitching(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;null!=i&&i.loader&&i.loader.abort(),this.fragCurrent=null,this.clearWaitingFragment(),r?this.setInterval(100):this.resetTransmuxer(),r?(this.audioSwitch=!0,this.state=n.State.IDLE):this.state=n.State.STOPPED,this.tick()},t.onManifestLoading=function onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1},t.onLevelLoaded=function onLevelLoaded(e,t){this.mainDetails=t.details},t.onAudioTrackLoaded=function onAudioTrackLoaded(e,t){var r,i=this.levels,a=t.details,s=t.id;if(i){this.log("Track "+s+" loaded ["+a.startSN+","+a.endSN+"],duration:"+a.totalduration);var o=i[s],l=0;if(a.live||null!==(r=o.details)&&void 0!==r&&r.live){var u=this.mainDetails;if(a.fragments[0]||(a.deltaUpdateFailed=!0),a.deltaUpdateFailed||!u)return;!o.details&&a.hasProgramDateTime&&u.hasProgramDateTime?(Object(v.alignPDT)(a,u),l=a.fragments[0].start):l=this.alignPlaylists(a,o.details)}o.details=a,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&a.live||this.setStartPosition(o.details,l),this.state!==n.State.WAITING_TRACK||this.waitForCdnTuneIn(a)||(this.state=n.State.IDLE),this.tick()}else this.warn("Audio tracks were reset while loading level "+s)},t._handleFragmentLoadProgress=function _handleFragmentLoadProgress(e){var t,r=e.frag,i=e.part,a=e.payload,s=this.config,o=this.trackId,l=this.levels;if(l){var d=l[o];console.assert(d,"Audio track is defined on fragment load progress");var g=d.details;console.assert(g,"Audio track details are defined on fragment load progress");var v=s.defaultAudioCodec||d.audioCodec||"mp4a.40.2",p=this.transmuxer;p||(p=this.transmuxer=new h.default(this.hls,u.PlaylistLevelType.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var y=this.initPTS[r.cc],E=null===(t=r.initSegment)||void 0===t?void 0:t.data;if(void 0!==y){var T=i?i.index:-1,S=-1!==T,b=new f.ChunkMetadata(r.level,r.sn,r.stats.chunkCount,a.byteLength,T,S);p.push(a,E,v,"",r,i,g.totalduration,!1,b,y)}else{m.logger.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+g.startSN+" ,"+g.endSN+"],track "+o),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new c.default,complete:!1}).cache.push(new Uint8Array(a)),this.waitingVideoCC=this.videoTrackCC,this.state=n.State.WAITING_INIT_PTS}}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},t._handleFragmentLoadComplete=function _handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},t.onBufferReset=function onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},t.onBufferCreated=function onBufferCreated(e,t){var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer)},t.onFragBuffered=function onFragBuffered(e,t){var r=t.frag,i=t.part;r.type===u.PlaylistLevelType.AUDIO&&(this.fragContextChanged(r)?this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+this.audioSwitch):("initSegment"!==r.sn&&(this.fragPrevious=r,this.audioSwitch&&(this.audioSwitch=!1,this.hls.trigger(a.Events.AUDIO_TRACK_SWITCHED,{id:this.trackId}))),this.fragBufferedComplete(r,i)))},t.onError=function onError(t,r){switch(r.details){case p.ErrorDetails.FRAG_LOAD_ERROR:case p.ErrorDetails.FRAG_LOAD_TIMEOUT:case p.ErrorDetails.KEY_LOAD_ERROR:case p.ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(u.PlaylistLevelType.AUDIO,r);break;case p.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case p.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:this.state!==n.State.ERROR&&this.state!==n.State.STOPPED&&(this.state=r.fatal?n.State.ERROR:n.State.IDLE,this.warn(r.details+" while loading frag, switching to "+this.state+" state"));break;case p.ErrorDetails.BUFFER_FULL_ERROR:if("audio"===r.parent&&(this.state===n.State.PARSING||this.state===n.State.PARSED)){var i=!0,a=this.getFwdBufferInfo(this.mediaBuffer,u.PlaylistLevelType.AUDIO);a&&a.len>.5&&(i=!this.reduceMaxBufferLength(a.len)),i&&(this.warn("Buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.resetLoadingState()}}},t.onBufferFlushed=function onBufferFlushed(e,t){t.type===d.ElementaryStreamTypes.AUDIO&&(this.bufferFlushed=!0)},t._handleTransmuxComplete=function _handleTransmuxComplete(e){var t,r="audio",i=this.hls,s=e.remuxResult,o=e.chunkMeta,l=this.getCurrentContext(o);if(!l)return this.warn("The loading context changed while buffering fragment "+o.sn+" of level "+o.level+". This chunk will not be buffered."),void this.resetLiveStartWhenNotLoaded(o.level);var u=l.frag,c=l.part,h=s.audio,f=s.text,g=s.id3,v=s.initSegment;if(!this.fragContextChanged(u)){if(this.state=n.State.PARSING,this.audioSwitch&&h&&this.completeAudioSwitch(),null!=v&&v.tracks&&(this._bufferInitSegment(v.tracks,u,o),i.trigger(a.Events.FRAG_PARSING_INIT_SEGMENT,{frag:u,id:r,tracks:v.tracks})),h){var p=h.startPTS,m=h.endPTS,y=h.startDTS,E=h.endDTS;c&&(c.elementaryStreams[d.ElementaryStreamTypes.AUDIO]={startPTS:p,endPTS:m,startDTS:y,endDTS:E}),u.setElementaryStreamInfo(d.ElementaryStreamTypes.AUDIO,p,m,y,E),this.bufferFragmentData(h,u,c,o)}if(null!=g&&null!==(t=g.samples)&&void 0!==t&&t.length){var T=_extends({frag:u,id:r},g);i.trigger(a.Events.FRAG_PARSING_METADATA,T)}if(f){var S=_extends({frag:u,id:r},f);i.trigger(a.Events.FRAG_PARSING_USERDATA,S)}}},t._bufferInitSegment=function _bufferInitSegment(e,t,r){if(this.state===n.State.PARSING){e.video&&delete e.video;var i=e.audio;if(i){i.levelCodec=i.codec,i.id="audio",this.log("Init audio buffer, container:"+i.container+", codecs[parsed]=["+i.codec+"]"),this.hls.trigger(a.Events.BUFFER_CODECS,e);var s=i.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:t,part:null,chunkMeta:r,parent:t.type,data:s};this.hls.trigger(a.Events.BUFFER_APPENDING,o)}this.tick()}}},t.loadFragment=function loadFragment(t,r,a){var s=this.fragmentTracker.getState(t);this.fragCurrent=t,(this.audioSwitch||s===o.FragmentState.NOT_LOADED||s===o.FragmentState.PARTIAL)&&("initSegment"===t.sn?this._loadInitSegment(t):r.live&&!Object(i.isFiniteNumber)(this.initPTS[t.cc])?(this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=n.State.WAITING_INIT_PTS):(this.startFragRequested=!0,e.prototype.loadFragment.call(this,t,r,a)))},t.completeAudioSwitch=function completeAudioSwitch(){var t=this.hls,r=this.media,i=this.trackId;r&&(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.audioSwitch=!1,t.trigger(a.Events.AUDIO_TRACK_SWITCHED,{id:i})},AudioStreamController}(n.default);t.default=y},"./src/controller/audio-track-controller.ts":
26
- /*!**************************************************!*\
27
- !*** ./src/controller/audio-track-controller.ts ***!
28
- \**************************************************/
29
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../errors */"./src/errors.ts"),a=r(/*! ./base-playlist-controller */"./src/controller/base-playlist-controller.ts"),s=r(/*! ../types/loader */"./src/types/loader.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var o=function(e){function AudioTrackController(t){var r;return(r=e.call(this,t,"[audio-track-controller]")||this).tracks=[],r.groupId=null,r.tracksInGroup=[],r.trackId=-1,r.trackName="",r.selectDefaultTrack=!0,r.registerListeners(),r}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(AudioTrackController,e);var t=AudioTrackController.prototype;return t.registerListeners=function registerListeners(){var e=this.hls;e.on(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(i.Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(i.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(i.Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(i.Events.ERROR,this.onError,this)},t.unregisterListeners=function unregisterListeners(){var e=this.hls;e.off(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(i.Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(i.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(i.Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(i.Events.ERROR,this.onError,this)},t.destroy=function destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,e.prototype.destroy.call(this)},t.onManifestLoading=function onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.trackName="",this.selectDefaultTrack=!0},t.onManifestParsed=function onManifestParsed(e,t){this.tracks=t.audioTracks||[]},t.onAudioTrackLoaded=function onAudioTrackLoaded(e,t){var r=t.id,i=t.details,n=this.tracksInGroup[r];if(n){var a=n.details;n.details=t.details,this.log("audioTrack "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&(this.retryCount=0,this.playlistLoaded(r,t,a))}else this.warn("Invalid audio track id "+r)},t.onLevelLoading=function onLevelLoading(e,t){this.switchLevel(t.level)},t.onLevelSwitching=function onLevelSwitching(e,t){this.switchLevel(t.level)},t.switchLevel=function switchLevel(e){var t=this.hls.levels[e];if(null!=t&&t.audioGroupIds){var r=t.audioGroupIds[t.urlId];if(this.groupId!==r){this.groupId=r;var n=this.tracks.filter((function(e){return!r||e.groupId===r}));this.selectDefaultTrack&&!n.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),this.tracksInGroup=n;var a={audioTracks:n};this.log("Updating audio tracks, "+n.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(i.Events.AUDIO_TRACKS_UPDATED,a),this.selectInitialTrack()}}},t.onError=function onError(t,r){e.prototype.onError.call(this,t,r),!r.fatal&&r.context&&r.context.type===s.PlaylistContextType.AUDIO_TRACK&&r.context.id===this.trackId&&r.context.groupId===this.groupId&&this.retryLoadingOrFail(r)},t.setAudioTrack=function setAudioTrack(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid id passed to audio-track controller");else{this.clearTimer();var r=t[this.trackId];this.log("Now switching to audio-track index "+e);var n=t[e],a=n.id,s=n.groupId,o=void 0===s?"":s,l=n.name,u=n.type,d=n.url;if(this.trackId=e,this.trackName=l,this.selectDefaultTrack=!1,this.hls.trigger(i.Events.AUDIO_TRACK_SWITCHING,{id:a,groupId:o,name:l,type:u,url:d}),!n.details||n.details.live){var c=this.switchParams(n.url,null==r?void 0:r.details);this.loadPlaylist(c)}}},t.selectInitialTrack=function selectInitialTrack(){var e=this.tracksInGroup;console.assert(e.length,"Initial audio track should be selected when tracks are known");var t=this.trackName,r=this.findTrackId(t)||this.findTrackId();-1!==r?this.setAudioTrack(r):(this.warn("No track found for running audio group-ID: "+this.groupId),this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))},t.findTrackId=function findTrackId(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||e===i.name))return i.id}return-1},t.loadPlaylist=function loadPlaylist(e){var t=this.tracksInGroup[this.trackId];if(this.shouldLoadTrack(t)){var r=t.id,n=t.groupId,a=t.url;if(e)try{a=e.addDirectives(a)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}this.log("loading audio-track playlist for id: "+r),this.clearTimer(),this.hls.trigger(i.Events.AUDIO_TRACK_LOADING,{url:a,id:r,groupId:n,deliveryDirectives:e||null})}},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(AudioTrackController,[{key:"audioTracks",get:function get(){return this.tracksInGroup}},{key:"audioTrack",get:function get(){return this.trackId},set:function set(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}}]),AudioTrackController}(a.default);t.default=o},"./src/controller/base-playlist-controller.ts":
30
- /*!****************************************************!*\
31
- !*** ./src/controller/base-playlist-controller.ts ***!
32
- \****************************************************/
33
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return l}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../types/level */"./src/types/level.ts"),a=r(/*! ./level-helper */"./src/controller/level-helper.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ../errors */"./src/errors.ts"),l=function(){function BasePlaylistController(e,t){this.hls=void 0,this.timer=-1,this.canLoad=!1,this.retryCount=0,this.log=void 0,this.warn=void 0,this.log=s.logger.log.bind(s.logger,t+":"),this.warn=s.logger.warn.bind(s.logger,t+":"),this.hls=e}var e=BasePlaylistController.prototype;return e.destroy=function destroy(){this.clearTimer(),this.hls=this.log=this.warn=null},e.onError=function onError(e,t){t.fatal&&t.type===o.ErrorTypes.NETWORK_ERROR&&this.clearTimer()},e.clearTimer=function clearTimer(){clearTimeout(this.timer),this.timer=-1},e.startLoad=function startLoad(){this.canLoad=!0,this.retryCount=0,this.loadPlaylist()},e.stopLoad=function stopLoad(){this.canLoad=!1,this.clearTimer()},e.switchParams=function switchParams(e,t){var r=null==t?void 0:t.renditionReports;if(r)for(var a=0;a<r.length;a++){var s=r[a],o=""+s.URI;if(o===e.substr(-o.length)){var l=parseInt(s["LAST-MSN"]),u=parseInt(s["LAST-PART"]);if(t&&this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);void 0!==u&&d>t.partTarget&&(u+=1)}if(Object(i.isFiniteNumber)(l))return new n.HlsUrlParameters(l,Object(i.isFiniteNumber)(u)?u:void 0,n.HlsSkip.No)}}},e.loadPlaylist=function loadPlaylist(e){},e.shouldLoadTrack=function shouldLoadTrack(e){return this.canLoad&&e&&!!e.url&&(!e.details||e.details.live)},e.playlistLoaded=function playlistLoaded(e,t,r){var i=this,n=t.details,s=t.stats,o=s.loading.end?Math.max(0,self.performance.now()-s.loading.end):0;if(n.advancedDateTime=Date.now()-o,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log("live playlist "+e+" "+(n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:"MISSED")),r&&n.fragments.length>0&&Object(a.mergeDetails)(r,n),!this.canLoad||!n.live)return;var l,u=void 0,d=void 0;if(n.canBlockReload&&n.endSN&&n.advanced){var c=this.hls.config.lowLatencyMode,h=n.lastPartSn,f=n.endSN,g=n.lastPartIndex,v=h===f;-1!==g?(u=v?f+1:h,d=v?c?0:g:g+1):u=f+1;var p=n.age,m=p+n.ageHeader,y=Math.min(m-n.partTarget,1.5*n.targetduration);if(y>0){if(r&&y>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+y+" with playlist age: "+n.age),y=0;else{var E=Math.floor(y/n.targetduration);if(u+=E,void 0!==d)d+=Math.round(y%n.targetduration/n.partTarget);this.log("CDN Tune-in age: "+n.ageHeader+"s last advanced "+p.toFixed(2)+"s goal: "+y+" skip sn "+E+" to part "+d)}n.tuneInGoal=y}if(l=this.getDeliveryDirectives(n,t.deliveryDirectives,u,d),c||!v)return void this.loadPlaylist(l)}else l=this.getDeliveryDirectives(n,t.deliveryDirectives,u,d);var T=Object(a.computeReloadInterval)(n,s);void 0!==u&&n.canBlockReload&&(T-=n.partTarget||1),this.log("reload live playlist "+e+" in "+Math.round(T)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(l)}),T)}else this.clearTimer()},e.getDeliveryDirectives=function getDeliveryDirectives(e,t,r,i){var a=Object(n.getSkipValue)(e,r);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,a=n.HlsSkip.No),new n.HlsUrlParameters(r,i,a)},e.retryLoadingOrFail=function retryLoadingOrFail(e){var t,r=this,i=this.hls.config,n=this.retryCount<i.levelLoadingMaxRetry;if(n)if(this.retryCount++,e.details.indexOf("LoadTimeOut")>-1&&null!==(t=e.context)&&void 0!==t&&t.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+e.details+'"'),this.loadPlaylist();else{var a=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),a),this.warn("retry playlist loading #"+this.retryCount+" in "+a+' ms after "'+e.details+'"')}else this.warn('cannot recover from error "'+e.details+'"'),this.clearTimer(),e.fatal=!0;return n},BasePlaylistController}()},"./src/controller/base-stream-controller.ts":
34
- /*!**************************************************!*\
35
- !*** ./src/controller/base-stream-controller.ts ***!
36
- \**************************************************/
37
- /*! exports provided: State, default */function(e,t,r){"use strict";r.r(t),r.d(t,"State",(function(){return E})),r.d(t,"default",(function(){return T}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../task-loop */"./src/task-loop.ts"),a=r(/*! ./fragment-tracker */"./src/controller/fragment-tracker.ts"),s=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),o=r(/*! ../utils/logger */"./src/utils/logger.ts"),l=r(/*! ../events */"./src/events.ts"),u=r(/*! ../errors */"./src/errors.ts"),d=r(/*! ../types/transmuxer */"./src/types/transmuxer.ts"),c=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),h=r(/*! ../utils/discontinuities */"./src/utils/discontinuities.ts"),f=r(/*! ./fragment-finders */"./src/controller/fragment-finders.ts"),g=r(/*! ./level-helper */"./src/controller/level-helper.ts"),v=r(/*! ../loader/fragment-loader */"./src/loader/fragment-loader.ts"),p=r(/*! ../crypt/decrypter */"./src/crypt/decrypter.ts"),m=r(/*! ../utils/time-ranges */"./src/utils/time-ranges.ts"),y=r(/*! ../types/loader */"./src/types/loader.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var E={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",BACKTRACKING:"BACKTRACKING",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},T=function(e){function BaseStreamController(t,r,i){var n;return(n=e.call(this)||this).hls=void 0,n.fragPrevious=null,n.fragCurrent=null,n.fragmentTracker=void 0,n.transmuxer=null,n._state=E.STOPPED,n.media=void 0,n.mediaBuffer=void 0,n.config=void 0,n.bitrateTest=!1,n.lastCurrentTime=0,n.nextLoadPosition=0,n.startPosition=0,n.loadedmetadata=!1,n.fragLoadError=0,n.retryDate=0,n.levels=null,n.fragmentLoader=void 0,n.levelLastLoaded=null,n.startFragRequested=!1,n.decrypter=void 0,n.initPTS=[],n.onvseeking=null,n.onvended=null,n.logPrefix="",n.log=void 0,n.warn=void 0,n.logPrefix=i,n.log=o.logger.log.bind(o.logger,i+":"),n.warn=o.logger.warn.bind(o.logger,i+":"),n.hls=t,n.fragmentLoader=new v.default(t.config),n.fragmentTracker=r,n.config=t.config,n.decrypter=new p.default(t,t.config),t.on(l.Events.KEY_LOADED,n.onKeyLoaded,function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(n)),n}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(BaseStreamController,e);var t=BaseStreamController.prototype;return t.doTick=function doTick(){this.onTickEnd()},t.onTickEnd=function onTickEnd(){},t.startLoad=function startLoad(e){},t.stopLoad=function stopLoad(){this.fragmentLoader.abort();var e=this.fragCurrent;e&&this.fragmentTracker.removeFragment(e),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=E.STOPPED},t._streamEnded=function _streamEnded(e,t){var r=this.fragCurrent,i=this.fragmentTracker;if(!t.live&&r&&r.sn===t.endSN&&!e.nextStart){var n=i.getState(r);return n===a.FragmentState.PARTIAL||n===a.FragmentState.OK}return!1},t.onMediaAttached=function onMediaAttached(e,t){var r=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);var i=this.config;this.levels&&i.autoStartLoad&&this.state===E.STOPPED&&this.startLoad(i.startPosition)},t.onMediaDetaching=function onMediaDetaching(){var e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},t.onMediaSeeking=function onMediaSeeking(){var e=this.config,t=this.fragCurrent,r=this.media,n=this.mediaBuffer,a=this.state,o=r?r.currentTime:0,l=s.BufferHelper.bufferInfo(n||r,o,e.maxBufferHole);if(this.log("media seeking to "+(Object(i.isFiniteNumber)(o)?o.toFixed(3):o)+", state: "+a),a===E.ENDED)this.resetLoadingState();else if(t&&!l.len){var u=e.maxFragLookUpTolerance,d=t.start-u,c=o>t.start+t.duration+u;(o<d||c)&&(c&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.loader.abort()),this.resetLoadingState())}r&&(this.lastCurrentTime=o),this.loadedmetadata||l.len||(this.nextLoadPosition=this.startPosition=o),this.tickImmediate()},t.onMediaEnded=function onMediaEnded(){this.startPosition=this.lastCurrentTime=0},t.onKeyLoaded=function onKeyLoaded(e,t){if(this.state===E.KEY_LOADING&&t.frag===this.fragCurrent&&this.levels){this.state=E.IDLE;var r=this.levels[t.frag.level].details;r&&this.loadFragment(t.frag,r,t.frag.start)}},t.onHandlerDestroying=function onHandlerDestroying(){this.stopLoad(),e.prototype.onHandlerDestroying.call(this)},t.onHandlerDestroyed=function onHandlerDestroyed(){this.state=E.STOPPED,this.hls.off(l.Events.KEY_LOADED,this.onKeyLoaded,this),this.fragmentLoader&&this.fragmentLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.fragmentLoader=this.fragmentTracker=null,e.prototype.onHandlerDestroyed.call(this)},t.loadKey=function loadKey(e,t){this.log("Loading key for "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+e.level),this.state=E.KEY_LOADING,this.fragCurrent=e,this.hls.trigger(l.Events.KEY_LOADING,{frag:e})},t.loadFragment=function loadFragment(e,t,r){this._loadFragForPlayback(e,t,r)},t._loadFragForPlayback=function _loadFragForPlayback(e,t,r){var i=this;this._doFragLoad(e,t,r,(function progressCallback(t){if(i.fragContextChanged(e))return i.warn("Fragment "+e.sn+(t.part?" p: "+t.part.index:"")+" of level "+e.level+" was dropped during download."),void i.fragmentTracker.removeFragment(e);e.stats.chunkCount++,i._handleFragmentLoadProgress(t)})).then((function(t){if(t){i.fragLoadError=0;var r=i.state;if(!i.fragContextChanged(e))return"payload"in t&&(i.log("Loaded fragment "+e.sn+" of level "+e.level),i.hls.trigger(l.Events.FRAG_LOADED,t),i.state===E.BACKTRACKING)?(i.fragmentTracker.backtrack(e,t),void i.resetFragmentLoading(e)):void i._handleFragmentLoadComplete(t);(r===E.FRAG_LOADING||r===E.BACKTRACKING||!i.fragCurrent&&r===E.PARSING)&&(i.fragmentTracker.removeFragment(e),i.state=E.IDLE)}})).catch((function(t){i.warn(t),i.resetFragmentLoading(e)}))},t.flushMainBuffer=function flushMainBuffer(e,t,r){if(void 0===r&&(r=null),e-t){var i={startOffset:e,endOffset:t,type:r};this.fragLoadError=0,this.hls.trigger(l.Events.BUFFER_FLUSHING,i)}},t._loadInitSegment=function _loadInitSegment(e){var t=this;this._doFragLoad(e).then((function(r){if(!r||t.fragContextChanged(e)||!t.levels)throw new Error("init load aborted");return r})).then((function(r){var i=t.hls,n=r.payload,a=e.decryptdata;if(n&&n.byteLength>0&&a&&a.key&&a.iv&&"AES-128"===a.method){var s=self.performance.now();return t.decrypter.webCryptoDecrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).then((function(t){var n=self.performance.now();return i.trigger(l.Events.FRAG_DECRYPTED,{frag:e,payload:t,stats:{tstart:s,tdecrypt:n}}),r.payload=t,r}))}return r})).then((function(r){var i=t.fragCurrent,n=t.hls,a=t.levels;if(!a)throw new Error("init load aborted, missing levels");var s=a[e.level].details;console.assert(s,"Level details are defined when init segment is loaded");var o=e.stats;t.state=E.IDLE,t.fragLoadError=0,e.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===i&&n.trigger(l.Events.FRAG_BUFFERED,{stats:o,frag:i,part:null,id:e.type}),t.tick()})).catch((function(r){t.warn(r),t.resetFragmentLoading(e)}))},t.fragContextChanged=function fragContextChanged(e){var t=this.fragCurrent;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId},t.fragBufferedComplete=function fragBufferedComplete(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+e.level+" "+m.default.toString(s.BufferHelper.getBuffered(r))),this.state=E.IDLE,this.tick()},t._handleFragmentLoadComplete=function _handleFragmentLoadComplete(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some((function(e){return!e})),s=new d.ChunkMetadata(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(s)}},t._handleFragmentLoadProgress=function _handleFragmentLoadProgress(e){},t._doFragLoad=function _doFragLoad(e,t,r,n){var a=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(e.start,r||0),this.config.lowLatencyMode&&t){var s=t.partList;if(s&&n){r>e.end&&t.fragmentHint&&(e=t.fragmentHint);var o=this.getNextPart(s,e,r);if(o>-1){var u=s[o];return this.log("Loading part sn: "+e.sn+" p: "+u.index+" cc: "+e.cc+" of playlist ["+t.startSN+"-"+t.endSN+"] parts [0-"+o+"-"+(s.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=E.FRAG_LOADING,this.hls.trigger(l.Events.FRAG_LOADING,{frag:e,part:s[o],targetBufferTime:r}),this.doFragPartsLoad(e,s,o,n).catch((function(e){return a.handleFragLoadError(e)}))}if(!e.url||this.loadedEndOfParts(s,r))return Promise.resolve(null)}}return this.log("Loading fragment "+e.sn+" cc: "+e.cc+" "+(t?"of ["+t.startSN+"-"+t.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),Object(i.isFiniteNumber)(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=E.FRAG_LOADING,this.hls.trigger(l.Events.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragmentLoader.load(e,n).catch((function(e){return a.handleFragLoadError(e)}))},t.doFragPartsLoad=function doFragPartsLoad(e,t,r,i){var n=this;return new Promise((function(a,s){var o=[];!function loadPartIndex(r){var u=t[r];n.fragmentLoader.loadPart(e,u,i).then((function(i){o[u.index]=i;var s=i.part;n.hls.trigger(l.Events.FRAG_LOADED,i);var d=t[r+1];if(!d||d.fragment!==e)return a({frag:e,part:s,partsLoaded:o});loadPartIndex(r+1)})).catch(s)}(r)}))},t.handleFragLoadError=function handleFragLoadError(e){var t=e.data;return t&&t.details===u.ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(l.Events.ERROR,t),null},t._handleTransmuxerFlush=function _handleTransmuxerFlush(e){var t=this.getCurrentContext(e);if(t&&this.state===E.PARSING){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(r,i,n,e.partial)}else this.fragCurrent||(this.state=E.IDLE)},t.getCurrentContext=function getCurrentContext(e){var t=this.levels,r=e.level,i=e.sn,n=e.part;if(!t||!t[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var a=t[r],s=n>-1?Object(g.getPartWith)(a,i,n):null,o=s?s.fragment:Object(g.getFragmentWithSN)(a,i,this.fragCurrent);return o?{frag:o,part:s,level:a}:null},t.bufferFragmentData=function bufferFragmentData(e,t,r,i){if(e&&this.state===E.PARSING){var n=e.data1,a=e.data2,s=n;if(n&&a&&(s=Object(c.appendUint8Array)(n,a)),s&&s.length){var o={type:e.type,frag:t,part:r,chunkMeta:i,parent:t.type,data:s};this.hls.trigger(l.Events.BUFFER_APPENDING,o),e.dropped&&e.independent&&!r&&this.flushBufferGap(t)}}},t.flushBufferGap=function flushBufferGap(e){var t=this.media;if(t)if(s.BufferHelper.isBuffered(t,t.currentTime)){var r=t.currentTime,i=s.BufferHelper.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),o=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}else this.flushMainBuffer(0,e.start)},t.getFwdBufferInfo=function getFwdBufferInfo(e,t){var r=this.config,n=this.getLoadPosition();if(!Object(i.isFiniteNumber)(n))return null;var a=s.BufferHelper.bufferInfo(e,n,r.maxBufferHole);if(0===a.len&&void 0!==a.nextStart){var o=this.fragmentTracker.getBufferedFrag(n,t);if(o&&a.nextStart<o.end)return s.BufferHelper.bufferInfo(e,n,Math.max(a.nextStart,r.maxBufferHole))}return a},t.getMaxBufferLength=function getMaxBufferLength(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)},t.reduceMaxBufferLength=function reduceMaxBufferLength(e){var t=this.config,r=e||t.maxBufferLength;return t.maxMaxBufferLength>=r&&(t.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+t.maxMaxBufferLength+"s"),!0)},t.getNextFragment=function getNextFragment(e,t){var r,i,n=t.fragments,a=n.length;if(!a)return null;var s,o=this.config,l=n[0].start;if(t.live){var u=o.initialLiveManifestSize;if(a<u)return this.warn("Not enough fragments to start playback (have: "+a+", need: "+u+")"),null;t.PTSKnown||this.startFragRequested||-1!==this.startPosition||(s=this.getInitialLiveFragment(t,n),this.startPosition=s?this.hls.liveSyncPosition||s.start:e)}else e<=l&&(s=n[0]);if(!s){var d=o.lowLatencyMode?t.partEnd:t.fragmentEnd;s=this.getFragmentAtPosition(e,d,t)}return null===(r=s)||void 0===r||!r.initSegment||null!==(i=s)&&void 0!==i&&i.initSegment.data||this.bitrateTest||(s=s.initSegment),s},t.getNextPart=function getNextPart(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,i>-1&&r<l.start)break;var u=l.loaded;!u&&(n||l.independent||a)&&l.fragment===t&&(i=s),n=u}return i},t.loadedEndOfParts=function loadedEndOfParts(e,t){var r=e[e.length-1];return r&&t>r.start&&r.loaded},t.getInitialLiveFragment=function getInitialLiveFragment(e,t){var r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=Object(f.findFragmentByPDT)(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var n=r.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=Object(f.findFragWithCC)(t,r.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},t.getFragmentAtPosition=function getFragmentAtPosition(e,t,r){var i,n=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,d=n.maxFragLookUpTolerance,c=!!(n.lowLatencyMode&&r.partList&&u);if(c&&u&&!this.bitrateTest&&(o=o.concat(u),l=u.sn),e<t){var h=e>t-d?0:d;i=Object(f.findFragmentByPTS)(s,o,e,h)}else i=o[o.length-1];if(i){var g=i.sn-r.startSN,v=s&&i.level===s.level,p=o[g+1];if(this.fragmentTracker.getState(i)===a.FragmentState.BACKTRACKED){i=null;for(var m=g;o[m]&&this.fragmentTracker.getState(o[m])===a.FragmentState.BACKTRACKED;)i=s?o[m--]:o[--m];i||(i=p)}else s&&i.sn===s.sn&&!c&&v&&(i.sn<l&&this.fragmentTracker.getState(p)!==a.FragmentState.OK?(this.log("SN "+i.sn+" just loaded, load next one: "+p.sn),i=p):i=null)}return i},t.synchronizeToLiveEdge=function synchronizeToLiveEdge(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=r.currentTime,a=e.fragments[0].start,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&r.readyState<4||n<s-l)&&(this.loadedmetadata||(this.nextLoadPosition=i),r.readyState&&(this.warn("Playback: "+n.toFixed(3)+" is located too far from the end of live sliding playlist: "+s+", reset currentTime to : "+i.toFixed(3)),r.currentTime=i))}}},t.alignPlaylists=function alignPlaylists(e,t){var r=this.levels,n=this.levelLastLoaded,a=this.fragPrevious,s=null!==n?r[n]:null,o=e.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;var l=e.fragments[0].start,u=!t,d=e.alignedSliding&&Object(i.isFiniteNumber)(l);if(u||!d&&!l){Object(h.alignStream)(a,s,e);var c=e.fragments[0].start;return this.log("Live playlist sliding: "+c.toFixed(2)+" start-sn: "+(t?t.startSN:"na")+"->"+e.startSN+" prev-sn: "+(a?a.sn:"na")+" fragments: "+o),c}return l},t.waitForCdnTuneIn=function waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},t.setStartPosition=function setStartPosition(e,t){var r=this.startPosition;if(r<t&&(r=-1),-1===r||-1===this.lastCurrentTime){var n=e.startTimeOffset;Object(i.isFiniteNumber)(n)?(r=t+n,n<0&&(r+=e.totalduration),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Start time offset "+n+" found in playlist, adjust startPosition to "+r),this.startPosition=r):e.live?r=this.hls.liveSyncPosition||t:this.startPosition=r=0,this.lastCurrentTime=r}this.nextLoadPosition=r},t.getLoadPosition=function getLoadPosition(){var e=this.media,t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t},t.handleFragLoadAborted=function handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn("Fragment "+e.sn+(t?" part"+t.index:"")+" of level "+e.level+" was aborted"),this.resetFragmentLoading(e))},t.resetFragmentLoading=function resetFragmentLoading(e){this.fragCurrent&&this.fragContextChanged(e)||(this.state=E.IDLE)},t.onFragmentOrKeyLoadError=function onFragmentOrKeyLoadError(e,t){if(!t.fatal){var r=t.frag;if(r&&r.type===e){var i=this.fragCurrent;console.assert(i&&r.sn===i.sn&&r.level===i.level&&r.urlId===i.urlId,"Frag load error must match current frag to retry");var n=this.config;if(this.fragLoadError+1<=n.fragLoadingMaxRetry){if(this.resetLiveStartWhenNotLoaded(r.level))return;var a=Math.min(Math.pow(2,this.fragLoadError)*n.fragLoadingRetryDelay,n.fragLoadingMaxRetryTimeout);this.warn("Fragment "+r.sn+" of "+e+" "+r.level+" failed to load, retrying in "+a+"ms"),this.retryDate=self.performance.now()+a,this.fragLoadError++,this.state=E.FRAG_LOADING_WAITING_RETRY}else t.levelRetry?(e===y.PlaylistLevelType.AUDIO&&(this.fragCurrent=null),this.fragLoadError=0,this.state=E.IDLE):(o.logger.error(t.details+" reaches max retry, redispatch as fatal ..."),t.fatal=!0,this.hls.stopLoad(),this.state=E.ERROR)}}},t.afterBufferFlushed=function afterBufferFlushed(e,t,r){if(e){var i=s.BufferHelper.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===E.ENDED&&this.resetLoadingState()}},t.resetLoadingState=function resetLoadingState(){this.fragCurrent=null,this.fragPrevious=null,this.state=E.IDLE},t.resetLiveStartWhenNotLoaded=function resetLiveStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;var t=this.levels?this.levels[e].details:null;if(null!=t&&t.live)return this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState(),!0;this.nextLoadPosition=this.startPosition}return!1},t.updateLevelTiming=function updateLevelTiming(e,t,r,i){var n=this,a=r.details;console.assert(!!a,"level.details must be defined"),Object.keys(e.elementaryStreams).reduce((function(t,s){var o=e.elementaryStreams[s];if(o){var u=o.endPTS-o.startPTS;if(u<=0)return n.warn("Could not parse fragment "+e.sn+" "+s+" duration reliably ("+u+") resetting transmuxer to fallback to playlist timing"),n.resetTransmuxer(),t||!1;var d=i?0:Object(g.updateFragPTSDTS)(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return n.hls.trigger(l.Events.LEVEL_PTS_UPDATED,{details:a,level:r,drift:d,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)?(this.state=E.PARSED,this.hls.trigger(l.Events.FRAG_PARSED,{frag:e,part:t})):this.resetLoadingState()},t.resetTransmuxer=function resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(BaseStreamController,[{key:"state",get:function get(){return this._state},set:function set(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}]),BaseStreamController}(n.default)},"./src/controller/buffer-controller.ts":
38
- /*!*********************************************!*\
39
- !*** ./src/controller/buffer-controller.ts ***!
40
- \*********************************************/
41
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return f}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),s=r(/*! ../errors */"./src/errors.ts"),o=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),l=r(/*! ../utils/mediasource-helper */"./src/utils/mediasource-helper.ts"),u=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),d=r(/*! ./buffer-operation-queue */"./src/controller/buffer-operation-queue.ts"),c=Object(l.getMediaSource)(),h=/([ha]vc.)(?:\.[^.,]+)+/,f=function(){function BufferController(e){var t=this;this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=function(){var e=t.hls,r=t.media,i=t.mediaSource;a.logger.log("[buffer-controller]: Media source opened"),r&&(t.updateMediaElementDuration(),e.trigger(n.Events.MEDIA_ATTACHED,{media:r})),i&&i.removeEventListener("sourceopen",t._onMediaSourceOpen),t.checkPendingTracks()},this._onMediaSourceClose=function(){a.logger.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=function(){a.logger.log("[buffer-controller]: Media source ended")},this.hls=e,this._initSourceBuffer(),this.registerListeners()}var e=BufferController.prototype;return e.hasSourceTypes=function hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},e.destroy=function destroy(){this.unregisterListeners(),this.details=null},e.registerListeners=function registerListeners(){var e=this.hls;e.on(n.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(n.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(n.Events.BUFFER_RESET,this.onBufferReset,this),e.on(n.Events.BUFFER_APPENDING,this.onBufferAppending,this),e.on(n.Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(n.Events.BUFFER_EOS,this.onBufferEos,this),e.on(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(n.Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(n.Events.FRAG_PARSED,this.onFragParsed,this),e.on(n.Events.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function unregisterListeners(){var e=this.hls;e.off(n.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(n.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(n.Events.BUFFER_RESET,this.onBufferReset,this),e.off(n.Events.BUFFER_APPENDING,this.onBufferAppending,this),e.off(n.Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(n.Events.BUFFER_EOS,this.onBufferEos,this),e.off(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(n.Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(n.Events.FRAG_PARSED,this.onFragParsed,this),e.off(n.Events.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function _initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new d.default(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},e.onManifestParsed=function onManifestParsed(e,t){var r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,a.logger.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function onMediaAttaching(e,t){var r=this.media=t.media;if(r&&c){var i=this.mediaSource=new c;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},e.onMediaDetaching=function onMediaDetaching(){var e=this.media,t=this.mediaSource,r=this._objectUrl;if(t){if(a.logger.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){a.logger.warn("[buffer-controller]: onMediaDetaching: "+e.message+" while calling endOfStream")}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(r&&self.URL.revokeObjectURL(r),e.src===r?(e.removeAttribute("src"),e.load()):a.logger.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(n.Events.MEDIA_DETACHED,void 0)},e.onBufferReset=function onBufferReset(){var e=this;this.getSourceBufferTypes().forEach((function(t){var r=e.sourceBuffer[t];try{r&&(e.removeBufferListeners(t),e.mediaSource&&e.mediaSource.removeSourceBuffer(r),e.sourceBuffer[t]=void 0)}catch(e){a.logger.warn("[buffer-controller]: Failed to reset the "+t+" buffer",e)}})),this._initSourceBuffer()},e.onBufferCodecs=function onBufferCodecs(e,t){var r=this,i=this.getSourceBufferTypes().length;Object.keys(t).forEach((function(e){if(i){var n=r.tracks[e];if(n&&"function"==typeof n.buffer.changeType){var a=t[e],s=a.codec,o=a.levelCodec,l=a.container;if((n.levelCodec||n.codec).replace(h,"$1")!==(o||s).replace(h,"$1")){var u=l+";codecs="+(o||s);r.appendChangeType(e,u)}}}else r.pendingTracks[e]=t[e]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function appendChangeType(e,t){var r=this,i=this.operationQueue,n={execute:function execute(){var n=r.sourceBuffer[e];n&&(a.logger.log("[buffer-controller]: changing "+e+" sourceBuffer type to "+t),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:function onStart(){},onComplete:function onComplete(){},onError:function onError(t){a.logger.warn("[buffer-controller]: Failed to change "+e+" SourceBuffer type",t)}};i.append(n,e)},e.onBufferAppending=function onBufferAppending(e,t){var r=this,i=this.hls,l=this.operationQueue,u=this.tracks,d=t.data,c=t.type,h=t.frag,f=t.part,g=t.chunkMeta,v=g.buffering[c],p=self.performance.now();v.start=p;var m=h.stats.buffering,y=f?f.stats.buffering:null;0===m.start&&(m.start=p),y&&0===y.start&&(y.start=p);var E=u.audio,T="audio"===c&&1===g.id&&"audio/mpeg"===(null==E?void 0:E.container),S={execute:function execute(){if(v.executeStart=self.performance.now(),T){var e=r.sourceBuffer[c];if(e){var t=h.start-e.timestampOffset;Math.abs(t)>=.1&&(a.logger.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+h.start+" (delta: "+t+") sn: "+h.sn+")"),e.timestampOffset=h.start)}}r.appendExecutor(d,c)},onStart:function onStart(){},onComplete:function onComplete(){var e=self.performance.now();v.executeEnd=v.end=e,0===m.first&&(m.first=e),y&&0===y.first&&(y.first=e);var t=r.sourceBuffer,i={};for(var a in t)i[a]=o.BufferHelper.getBuffered(t[a]);r.appendError=0,r.hls.trigger(n.Events.BUFFER_APPENDED,{type:c,frag:h,part:f,chunkMeta:g,parent:h.type,timeRanges:i})},onError:function onError(e){a.logger.error("[buffer-controller]: Error encountered while trying to append to the "+c+" SourceBuffer",e);var t={type:s.ErrorTypes.MEDIA_ERROR,parent:h.type,details:s.ErrorDetails.BUFFER_APPEND_ERROR,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=s.ErrorDetails.BUFFER_FULL_ERROR:(r.appendError++,t.details=s.ErrorDetails.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(a.logger.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),t.fatal=!0)),i.trigger(n.Events.ERROR,t)}};l.append(S,c)},e.onBufferFlushing=function onBufferFlushing(e,t){var r=this,i=this.operationQueue,s=function flushOperation(e){return{execute:r.removeExecutor.bind(r,e,t.startOffset,t.endOffset),onStart:function onStart(){},onComplete:function onComplete(){r.hls.trigger(n.Events.BUFFER_FLUSHED,{type:e})},onError:function onError(t){a.logger.warn("[buffer-controller]: Failed to remove from "+e+" SourceBuffer",t)}}};t.type?i.append(s(t.type),t.type):this.getSourceBufferTypes().forEach((function(e){i.append(s(e),e)}))},e.onFragParsed=function onFragParsed(e,t){var r=this,i=t.frag,s=t.part,o=[],l=s?s.elementaryStreams:i.elementaryStreams;l[u.ElementaryStreamTypes.AUDIOVIDEO]?o.push("audiovideo"):(l[u.ElementaryStreamTypes.AUDIO]&&o.push("audio"),l[u.ElementaryStreamTypes.VIDEO]&&o.push("video"));0===o.length&&a.logger.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function onUnblocked(){var e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);var t=s?s.stats:i.stats;r.hls.trigger(n.Events.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})}),o)},e.onFragChanged=function onFragChanged(e,t){this.flushBackBuffer()},e.onBufferEos=function onBufferEos(e,t){var r=this;this.getSourceBufferTypes().reduce((function(e,i){var n=r.sourceBuffer[i];return t.type&&t.type!==i||n&&!n.ended&&(n.ended=!0,a.logger.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),e&&!(n&&!n.ended)}),!0)&&this.blockBuffers((function(){var e=r.mediaSource;e&&"open"===e.readyState&&e.endOfStream()}))},e.onLevelUpdated=function onLevelUpdated(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function flushBackBuffer(){var e=this.hls,t=this.details,r=this.media,a=this.sourceBuffer;if(r&&null!==t){var s=this.getSourceBufferTypes();if(s.length){var l=t.live&&null!==e.config.liveBackBufferLength?e.config.liveBackBufferLength:e.config.backBufferLength;if(Object(i.isFiniteNumber)(l)&&!(l<0)){var u=r.currentTime,d=t.levelTargetDuration,c=Math.max(l,d),h=Math.floor(u/d)*d-c;s.forEach((function(r){var i=a[r];if(i){var s=o.BufferHelper.getBuffered(i);s.length>0&&h>s.start(0)&&(e.trigger(n.Events.BACK_BUFFER_REACHED,{bufferEnd:h}),t.live&&e.trigger(n.Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:h}),e.trigger(n.Events.BUFFER_FLUSHING,{startOffset:0,endOffset:h,type:r}))}}))}}}},e.updateMediaElementDuration=function updateMediaElementDuration(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var e=this.details,t=this.hls,r=this.media,n=this.mediaSource,s=e.fragments[0].start+e.totalduration,o=r.duration,l=Object(i.isFiniteNumber)(n.duration)?n.duration:0;e.live&&t.config.liveDurationInfinity?(a.logger.log("[buffer-controller]: Media Source duration is set to Infinity"),n.duration=1/0,this.updateSeekableRange(e)):(s>l&&s>o||!Object(i.isFiniteNumber)(o))&&(a.logger.log("[buffer-controller]: Updating Media Source duration to "+s.toFixed(3)),n.duration=s)}},e.updateSeekableRange=function updateSeekableRange(e){var t=this.mediaSource,r=e.fragments;if(r.length&&e.live&&null!=t&&t.setLiveSeekableRange){var i=Math.max(0,r[0].start),n=Math.max(i,i+e.totalduration);t.setLiveSeekableRange(i,n)}},e.checkPendingTracks=function checkPendingTracks(){var e=this.bufferCodecEventsExpected,t=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!e||2===i){this.createSourceBuffers(r),this.pendingTracks={};var a=this.getSourceBufferTypes();if(0===a.length)return void this.hls.trigger(n.Events.ERROR,{type:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});a.forEach((function(e){t.executeNext(e)}))}},e.createSourceBuffers=function createSourceBuffers(e){var t=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var o in e)if(!t[o]){var l=e[o];if(!l)throw Error("source buffer exists for track "+o+", however track does not");var u=l.levelCodec||l.codec,d=l.container+";codecs="+u;a.logger.log("[buffer-controller]: creating sourceBuffer("+d+")");try{var c=t[o]=r.addSourceBuffer(d),h=o;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.tracks[o]={buffer:c,codec:u,container:l.container,levelCodec:l.levelCodec,id:l.id},i++}catch(e){a.logger.error("[buffer-controller]: error while trying to add sourceBuffer: "+e.message),this.hls.trigger(n.Events.ERROR,{type:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:d})}}i&&this.hls.trigger(n.Events.BUFFER_CREATED,{tracks:this.tracks})},e._onSBUpdateStart=function _onSBUpdateStart(e){this.operationQueue.current(e).onStart()},e._onSBUpdateEnd=function _onSBUpdateEnd(e){var t=this.operationQueue;t.current(e).onComplete(),t.shiftAndExecuteNext(e)},e._onSBUpdateError=function _onSBUpdateError(e,t){a.logger.error("[buffer-controller]: "+e+" SourceBuffer error",t),this.hls.trigger(n.Events.ERROR,{type:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(e);r&&r.onError(t)},e.removeExecutor=function removeExecutor(e,t,r){var n=this.media,s=this.mediaSource,o=this.operationQueue,l=this.sourceBuffer[e];if(!n||!s||!l)return a.logger.warn("[buffer-controller]: Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void o.shiftAndExecuteNext(e);var u=Object(i.isFiniteNumber)(n.duration)?n.duration:1/0,d=Object(i.isFiniteNumber)(s.duration)?s.duration:1/0,c=Math.max(0,t),h=Math.min(r,u,d);h>c?(a.logger.log("[buffer-controller]: Removing ["+c+","+h+"] from the "+e+" SourceBuffer"),console.assert(!l.updating,e+" sourceBuffer must not be updating"),l.remove(c,h)):o.shiftAndExecuteNext(e)},e.appendExecutor=function appendExecutor(e,t){var r=this.operationQueue,i=this.sourceBuffer[t];if(!i)return a.logger.warn("[buffer-controller]: Attempting to append to the "+t+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(t);i.ended=!1,console.assert(!i.updating,t+" sourceBuffer must not be updating"),i.appendBuffer(e)},e.blockBuffers=function blockBuffers(e,t){var r=this;if(void 0===t&&(t=this.getSourceBufferTypes()),!t.length)return a.logger.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve(e);var i=this.operationQueue,n=t.map((function(e){return i.appendBlocker(e)}));Promise.all(n).then((function(){e(),t.forEach((function(e){var t=r.sourceBuffer[e];t&&t.updating||i.shiftAndExecuteNext(e)}))}))},e.getSourceBufferTypes=function getSourceBufferTypes(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function addBufferListener(e,t,r){var i=this.sourceBuffer[e];if(i){var n=r.bind(this,e);this.listeners[e].push({event:t,listener:n}),i.addEventListener(t,n)}},e.removeBufferListeners=function removeBufferListeners(e){var t=this.sourceBuffer[e];t&&this.listeners[e].forEach((function(e){t.removeEventListener(e.event,e.listener)}))},BufferController}()},"./src/controller/buffer-operation-queue.ts":
42
- /*!**************************************************!*\
43
- !*** ./src/controller/buffer-operation-queue.ts ***!
44
- \**************************************************/
45
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return n}));var i=r(/*! ../utils/logger */"./src/utils/logger.ts"),n=function(){function BufferOperationQueue(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}var e=BufferOperationQueue.prototype;return e.append=function append(e,t){var r=this.queues[t];r.push(e),1===r.length&&this.buffers[t]&&this.executeNext(t)},e.insertAbort=function insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)},e.appendBlocker=function appendBlocker(e){var t,r=new Promise((function(e){t=e})),i={execute:t,onStart:function onStart(){},onComplete:function onComplete(){},onError:function onError(){}};return this.append(i,e),r},e.executeNext=function executeNext(e){var t=this.buffers,r=this.queues,n=t[e],a=r[e];if(a.length){var s=a[0];try{s.execute()}catch(t){i.logger.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),s.onError(t),n&&n.updating||(a.shift(),this.executeNext(e))}}},e.shiftAndExecuteNext=function shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)},e.current=function current(e){return this.queues[e][0]},BufferOperationQueue}()},"./src/controller/cap-level-controller.ts":
46
- /*!************************************************!*\
47
- !*** ./src/controller/cap-level-controller.ts ***!
48
- \************************************************/
49
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../events */"./src/events.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var n=function(){function CapLevelController(e){this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.hls=void 0,this.streamController=void 0,this.clientRect=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var e=CapLevelController.prototype;return e.setStreamController=function setStreamController(e){this.streamController=e},e.destroy=function destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},e.registerListeners=function registerListeners(){var e=this.hls;e.on(i.Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(i.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(i.Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this)},e.unregisterListener=function unregisterListener(){var e=this.hls;e.off(i.Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(i.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(i.Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this)},e.onFpsDropLevelCapping=function onFpsDropLevelCapping(e,t){CapLevelController.isLevelAllowed(t.droppedLevel,this.restrictedLevels)&&this.restrictedLevels.push(t.droppedLevel)},e.onMediaAttaching=function onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null},e.onManifestParsed=function onManifestParsed(e,t){var r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()},e.onBufferCodecs=function onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()},e.onMediaDetaching=function onMediaDetaching(){this.stopCapping()},e.detectPlayerSize=function detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){var e=this.hls.levels;if(e.length){var t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},e.getMaxLevel=function getMaxLevel(e){var t=this,r=this.hls.levels;if(!r.length)return-1;var i=r.filter((function(r,i){return CapLevelController.isLevelAllowed(i,t.restrictedLevels)&&i<=e}));return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)},e.startCapping=function startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},e.stopCapping=function stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},e.getDimensions=function getDimensions(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},CapLevelController.isLevelAllowed=function isLevelAllowed(e,t){return void 0===t&&(t=[]),-1===t.indexOf(e)},CapLevelController.getMaxLevelByMediaSize=function getMaxLevelByMediaSize(e,t,r){if(!e||!e.length)return-1;for(var i=function atGreatestBandiwdth(e,t){return!t||(e.width!==t.width||e.height!==t.height)},n=e.length-1,a=0;a<e.length;a+=1){var s=e[a];if((s.width>=t||s.height>=r)&&i(s,e[a+1])){n=a;break}}return n},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(CapLevelController,[{key:"mediaWidth",get:function get(){return this.getDimensions().width*CapLevelController.contentScaleFactor}},{key:"mediaHeight",get:function get(){return this.getDimensions().height*CapLevelController.contentScaleFactor}}],[{key:"contentScaleFactor",get:function get(){var e=1;try{e=self.devicePixelRatio}catch(e){}return e}}]),CapLevelController}();t.default=n},"./src/controller/eme-controller.ts":
50
- /*!******************************************!*\
51
- !*** ./src/controller/eme-controller.ts ***!
52
- \******************************************/
53
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../errors */"./src/errors.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),s=r(/*! ../utils/mediakeys-helper */"./src/utils/mediakeys-helper.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var o=function(){function EMEController(e){this.hls=void 0,this._widevineLicenseUrl=void 0,this._licenseXhrSetup=void 0,this._licenseResponseCallback=void 0,this._emeEnabled=void 0,this._requestMediaKeySystemAccess=void 0,this._drmSystemOptions=void 0,this._config=void 0,this._mediaKeysList=[],this._media=null,this._hasSetMediaKeys=!1,this._requestLicenseFailureCount=0,this.mediaKeysPromise=null,this._onMediaEncrypted=this.onMediaEncrypted.bind(this),this.hls=e,this._config=e.config,this._widevineLicenseUrl=this._config.widevineLicenseUrl,this._licenseXhrSetup=this._config.licenseXhrSetup,this._licenseResponseCallback=this._config.licenseResponseCallback,this._emeEnabled=this._config.emeEnabled,this._requestMediaKeySystemAccess=this._config.requestMediaKeySystemAccessFunc,this._drmSystemOptions=this._config.drmSystemOptions,this._registerListeners()}var e=EMEController.prototype;return e.destroy=function destroy(){this._unregisterListeners(),this.hls=this._onMediaEncrypted=null,this._requestMediaKeySystemAccess=null},e._registerListeners=function _registerListeners(){this.hls.on(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(i.Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(i.Events.MANIFEST_PARSED,this.onManifestParsed,this)},e._unregisterListeners=function _unregisterListeners(){this.hls.off(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(i.Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(i.Events.MANIFEST_PARSED,this.onManifestParsed,this)},e.getLicenseServerUrl=function getLicenseServerUrl(e){switch(e){case s.KeySystems.WIDEVINE:if(!this._widevineLicenseUrl)break;return this._widevineLicenseUrl}throw new Error('no license server URL configured for key-system "'+e+'"')},e._attemptKeySystemAccess=function _attemptKeySystemAccess(e,t,r){var i=this,n=function getSupportedMediaKeySystemConfigurations(e,t,r,i){switch(e){case s.KeySystems.WIDEVINE:return function createWidevineMediaKeySystemConfigurations(e,t,r){var i={audioCapabilities:[],videoCapabilities:[]};return e.forEach((function(e){i.audioCapabilities.push({contentType:'audio/mp4; codecs="'+e+'"',robustness:r.audioRobustness||""})})),t.forEach((function(e){i.videoCapabilities.push({contentType:'video/mp4; codecs="'+e+'"',robustness:r.videoRobustness||""})})),[i]}(t,r,i);default:throw new Error("Unknown key-system: "+e)}}(e,t,r,this._drmSystemOptions);a.logger.log("Requesting encrypted media key-system access");var o=this.requestMediaKeySystemAccess(e,n);this.mediaKeysPromise=o.then((function(t){return i._onMediaKeySystemAccessObtained(e,t)})),o.catch((function(t){a.logger.error('Failed to obtain key-system "'+e+'" access:',t)}))},e._onMediaKeySystemAccessObtained=function _onMediaKeySystemAccessObtained(e,t){var r=this;a.logger.log('Access for key-system "'+e+'" obtained');var i={mediaKeysSessionInitialized:!1,mediaKeySystemAccess:t,mediaKeySystemDomain:e};this._mediaKeysList.push(i);var n=Promise.resolve().then((function(){return t.createMediaKeys()})).then((function(t){return i.mediaKeys=t,a.logger.log('Media-keys created for key-system "'+e+'"'),r._onMediaKeysCreated(),t}));return n.catch((function(e){a.logger.error("Failed to create media-keys:",e)})),n},e._onMediaKeysCreated=function _onMediaKeysCreated(){var e=this;this._mediaKeysList.forEach((function(t){t.mediaKeysSession||(t.mediaKeysSession=t.mediaKeys.createSession(),e._onNewMediaKeySession(t.mediaKeysSession))}))},e._onNewMediaKeySession=function _onNewMediaKeySession(e){var t=this;a.logger.log("New key-system session "+e.sessionId),e.addEventListener("message",(function(r){t._onKeySessionMessage(e,r.message)}),!1)},e._onKeySessionMessage=function _onKeySessionMessage(e,t){a.logger.log("Got EME message event, creating license request"),this._requestLicense(t,(function(t){a.logger.log("Received license data (length: "+(t?t.byteLength:t)+"), updating key-session"),e.update(t)}))},e.onMediaEncrypted=function onMediaEncrypted(e){var t=this;if(a.logger.log('Media is encrypted using "'+e.initDataType+'" init data type'),!this.mediaKeysPromise)return a.logger.error("Fatal: Media is encrypted but no CDM access or no keys have been requested"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_KEYS,fatal:!0});var r=function finallySetKeyAndStartSession(r){t._media&&(t._attemptSetMediaKeys(r),t._generateRequestWithPreferredKeySession(e.initDataType,e.initData))};this.mediaKeysPromise.then(r).catch(r)},e._attemptSetMediaKeys=function _attemptSetMediaKeys(e){if(!this._media)throw new Error("Attempted to set mediaKeys without first attaching a media element");if(!this._hasSetMediaKeys){var t=this._mediaKeysList[0];if(!t||!t.mediaKeys)return a.logger.error("Fatal: Media is encrypted but no CDM access or no keys have been obtained yet"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_KEYS,fatal:!0});a.logger.log("Setting keys for encrypted media"),this._media.setMediaKeys(t.mediaKeys),this._hasSetMediaKeys=!0}},e._generateRequestWithPreferredKeySession=function _generateRequestWithPreferredKeySession(e,t){var r=this,s=this._mediaKeysList[0];if(!s)return a.logger.error("Fatal: Media is encrypted but not any key-system access has been obtained yet"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_ACCESS,fatal:!0});if(s.mediaKeysSessionInitialized)a.logger.warn("Key-Session already initialized but requested again");else{var o=s.mediaKeysSession;if(!o)return a.logger.error("Fatal: Media is encrypted but no key-session existing"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_SESSION,fatal:!0});if(!t)return a.logger.warn("Fatal: initData required for generating a key session is null"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_INIT_DATA,fatal:!0});a.logger.log('Generating key-session request for "'+e+'" init data type'),s.mediaKeysSessionInitialized=!0,o.generateRequest(e,t).then((function(){a.logger.debug("Key-session generation succeeded")})).catch((function(e){a.logger.error("Error generating key-session request:",e),r.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_SESSION,fatal:!1})}))}},e._createLicenseXhr=function _createLicenseXhr(e,t,r){var i=new XMLHttpRequest;i.responseType="arraybuffer",i.onreadystatechange=this._onLicenseRequestReadyStageChange.bind(this,i,e,t,r);var n=this._licenseXhrSetup;if(n)try{n.call(this.hls,i,e),n=void 0}catch(e){a.logger.error(e)}try{i.readyState||i.open("POST",e,!0),n&&n.call(this.hls,i,e)}catch(e){throw new Error("issue setting up KeySystem license XHR "+e)}return i},e._onLicenseRequestReadyStageChange=function _onLicenseRequestReadyStageChange(e,t,r,s){switch(e.readyState){case 4:if(200===e.status){this._requestLicenseFailureCount=0,a.logger.log("License request succeeded");var o=e.response,l=this._licenseResponseCallback;if(l)try{o=l.call(this.hls,e,t)}catch(e){a.logger.error(e)}s(o)}else{if(a.logger.error("License Request XHR failed ("+t+"). Status: "+e.status+" ("+e.statusText+")"),this._requestLicenseFailureCount++,this._requestLicenseFailureCount>3)return void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0});var u=3-this._requestLicenseFailureCount+1;a.logger.warn("Retrying license request, "+u+" attempts left"),this._requestLicense(r,s)}}},e._generateLicenseRequestChallenge=function _generateLicenseRequestChallenge(e,t){switch(e.mediaKeySystemDomain){case s.KeySystems.WIDEVINE:return t}throw new Error("unsupported key-system: "+e.mediaKeySystemDomain)},e._requestLicense=function _requestLicense(e,t){a.logger.log("Requesting content license for key-system");var r=this._mediaKeysList[0];if(!r)return a.logger.error("Fatal error: Media is encrypted but no key-system access has been obtained yet"),void this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_NO_ACCESS,fatal:!0});try{var s=this.getLicenseServerUrl(r.mediaKeySystemDomain),o=this._createLicenseXhr(s,e,t);a.logger.log("Sending license request to URL: "+s);var l=this._generateLicenseRequestChallenge(r,e);o.send(l)}catch(e){a.logger.error("Failure requesting DRM license: "+e),this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.KEY_SYSTEM_ERROR,details:n.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}},e.onMediaAttached=function onMediaAttached(e,t){if(this._emeEnabled){var r=t.media;this._media=r,r.addEventListener("encrypted",this._onMediaEncrypted)}},e.onMediaDetached=function onMediaDetached(){var e=this._media,t=this._mediaKeysList;e&&(e.removeEventListener("encrypted",this._onMediaEncrypted),this._media=null,this._mediaKeysList=[],Promise.all(t.map((function(e){if(e.mediaKeysSession)return e.mediaKeysSession.close().catch((function(){}))}))).then((function(){return e.setMediaKeys(null)})).catch((function(){})))},e.onManifestParsed=function onManifestParsed(e,t){if(this._emeEnabled){var r=t.levels.map((function(e){return e.audioCodec})).filter((function(e){return!!e})),i=t.levels.map((function(e){return e.videoCodec})).filter((function(e){return!!e}));this._attemptKeySystemAccess(s.KeySystems.WIDEVINE,r,i)}},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(EMEController,[{key:"requestMediaKeySystemAccess",get:function get(){if(!this._requestMediaKeySystemAccess)throw new Error("No requestMediaKeySystemAccess function configured");return this._requestMediaKeySystemAccess}}]),EMEController}();t.default=o},"./src/controller/fps-controller.ts":
54
- /*!******************************************!*\
55
- !*** ./src/controller/fps-controller.ts ***!
56
- \******************************************/
57
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../utils/logger */"./src/utils/logger.ts"),a=function(){function FPSController(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}var e=FPSController.prototype;return e.setStreamController=function setStreamController(e){this.streamController=e},e.registerListeners=function registerListeners(){this.hls.on(i.Events.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function unregisterListeners(){this.hls.off(i.Events.MEDIA_ATTACHING,this.onMediaAttaching)},e.destroy=function destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function onMediaAttaching(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function checkFPS(e,t,r){var a=performance.now();if(t){if(this.lastTime){var s=a-this.lastTime,o=r-this.lastDroppedFrames,l=t-this.lastDecodedFrames,u=1e3*o/s,d=this.hls;if(d.trigger(i.Events.FPS_DROP,{currentDropped:o,currentDecoded:l,totalDroppedFrames:r}),u>0&&o>d.config.fpsDroppedMonitoringThreshold*l){var c=d.currentLevel;n.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(-1===d.autoLevelCapping||d.autoLevelCapping>=c)&&(c-=1,d.trigger(i.Events.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:d.currentLevel}),d.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},e.checkFPSInterval=function checkFPSInterval(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},FPSController}();t.default=a},"./src/controller/fragment-finders.ts":
58
- /*!********************************************!*\
59
- !*** ./src/controller/fragment-finders.ts ***!
60
- \********************************************/
61
- /*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */function(e,t,r){"use strict";r.r(t),r.d(t,"findFragmentByPDT",(function(){return findFragmentByPDT})),r.d(t,"findFragmentByPTS",(function(){return findFragmentByPTS})),r.d(t,"fragmentWithinToleranceTest",(function(){return fragmentWithinToleranceTest})),r.d(t,"pdtWithinToleranceTest",(function(){return pdtWithinToleranceTest})),r.d(t,"findFragWithCC",(function(){return findFragWithCC}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../utils/binary-search */"./src/utils/binary-search.ts");function findFragmentByPDT(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!Object(i.isFiniteNumber)(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(var n=0;n<e.length;++n){var a=e[n];if(pdtWithinToleranceTest(t,r,a))return a}return null}function findFragmentByPTS(e,t,r,i){void 0===r&&(r=0),void 0===i&&(i=0);var a=null;if(e?a=t[e.sn-t[0].sn+1]||null:0===r&&0===t[0].start&&(a=t[0]),a&&0===fragmentWithinToleranceTest(r,i,a))return a;var s=n.default.search(t,fragmentWithinToleranceTest.bind(null,r,i));return s||a}function fragmentWithinToleranceTest(e,t,r){void 0===e&&(e=0),void 0===t&&(t=0);var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function pdtWithinToleranceTest(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function findFragWithCC(e,t){return n.default.search(e,(function(e){return e.cc<t?1:e.cc>t?-1:0}))}},"./src/controller/fragment-tracker.ts":
62
- /*!********************************************!*\
63
- !*** ./src/controller/fragment-tracker.ts ***!
64
- \********************************************/
65
- /*! exports provided: FragmentState, FragmentTracker */function(e,t,r){"use strict";r.r(t),r.d(t,"FragmentState",(function(){return i})),r.d(t,"FragmentTracker",(function(){return s}));var i,n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../types/loader */"./src/types/loader.ts");!function(e){e.NOT_LOADED="NOT_LOADED",e.BACKTRACKED="BACKTRACKED",e.APPENDING="APPENDING",e.PARTIAL="PARTIAL",e.OK="OK"}(i||(i={}));var s=function(){function FragmentTracker(e){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=e,this._registerListeners()}var e=FragmentTracker.prototype;return e._registerListeners=function _registerListeners(){var e=this.hls;e.on(n.Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(n.Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(n.Events.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function _unregisterListeners(){var e=this.hls;e.off(n.Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(n.Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(n.Events.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function destroy(){this._unregisterListeners(),this.fragments=this.timeRanges=null},e.getAppendedFrag=function getAppendedFrag(e,t){if(t===a.PlaylistLevelType.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var n=i.length;n--;){var s=i[n],o=s?s.end:r.appendedPTS;if(s.start<=e&&void 0!==o&&e<=o)return n>9&&(this.activeParts=i.slice(n-9)),s}else if(r.start<=e&&void 0!==r.appendedPTS&&e<=r.appendedPTS)return r}return this.getBufferedFrag(e,t)},e.getBufferedFrag=function getBufferedFrag(e,t){for(var r=this.fragments,i=Object.keys(r),n=i.length;n--;){var a=r[i[n]];if((null==a?void 0:a.body.type)===t&&a.buffered){var s=a.body;if(s.start<=e&&e<=s.end)return s}}return null},e.detectEvictedFragments=function detectEvictedFragments(e,t,r){var i=this;Object.keys(this.fragments).forEach((function(n){var a=i.fragments[n];if(a)if(a.buffered){var s=a.range[e];s&&s.time.some((function(e){var r=!i.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&i.removeFragment(a.body),r}))}else a.body.type===r&&i.removeFragment(a.body)}))},e.detectPartialFragments=function detectPartialFragments(e){var t=this,r=this.timeRanges,i=e.frag,n=e.part;if(r&&"initSegment"!==i.sn){var a=getFragmentKey(i),s=this.fragments[a];s&&(Object.keys(r).forEach((function(e){var a=i.elementaryStreams[e];if(a){var o=r[e],l=null!==n||!0===a.partial;s.range[e]=t.getBufferedTimes(i,n,l,o)}})),s.backtrack=s.loaded=null,Object.keys(s.range).length?s.buffered=!0:this.removeFragment(s.body))}},e.fragBuffered=function fragBuffered(e){var t=getFragmentKey(e),r=this.fragments[t];r&&(r.backtrack=r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function getBufferedTimes(e,t,r,i){for(var n={time:[],partial:r},a=t?t.start:e.start,s=t?t.end:e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<i.length;u++){var d=i.start(u)-this.bufferPadding,c=i.end(u)+this.bufferPadding;if(l>=d&&o<=c){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(a<c&&s>d)n.partial=!0,n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=d)break}return n},e.getPartialFragment=function getPartialFragment(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&isPartial(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))})),n},e.getState=function getState(e){var t=getFragmentKey(e),r=this.fragments[t];return r?r.buffered?isPartial(r)?i.PARTIAL:i.OK:r.backtrack?i.BACKTRACKED:i.APPENDING:i.NOT_LOADED},e.backtrack=function backtrack(e,t){var r=getFragmentKey(e),i=this.fragments[r];if(!i||i.backtrack)return null;var backtrack=i.backtrack=t||i.loaded;return i.loaded=null,backtrack},e.getBacktrackData=function getBacktrackData(e){var t=getFragmentKey(e),r=this.fragments[t];if(r){var i,n=r.backtrack;if(null!=n&&null!==(i=n.payload)&&void 0!==i&&i.byteLength)return n;this.removeFragment(e)}return null},e.isTimeBuffered=function isTimeBuffered(e,t,r){for(var i,n,a=0;a<r.length;a++){if(i=r.start(a)-this.bufferPadding,n=r.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1},e.onFragLoaded=function onFragLoaded(e,t){var r=t.frag,i=t.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var n=getFragmentKey(r);this.fragments[n]={body:r,loaded:t,backtrack:null,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function onBufferAppended(e,t){var r=this,i=t.frag,n=t.part,s=t.timeRanges;if(i.type===a.PlaylistLevelType.MAIN)if(this.activeFragment=i,n){var o=this.activeParts;o||(this.activeParts=o=[]),o.push(n)}else this.activeParts=null;this.timeRanges=s,Object.keys(s).forEach((function(e){var t=s[e];if(r.detectEvictedFragments(e,t),!n)for(var a=0;a<t.length;a++)i.appendedPTS=Math.max(t.end(a),i.appendedPTS||0)}))},e.onFragBuffered=function onFragBuffered(e,t){this.detectPartialFragments(t)},e.hasFragment=function hasFragment(e){var t=getFragmentKey(e);return!!this.fragments[t]},e.removeFragmentsInRange=function removeFragmentsInRange(e,t,r){var i=this;Object.keys(this.fragments).forEach((function(n){var a=i.fragments[n];if(a&&a.buffered){var s=a.body;s.type===r&&s.start<t&&s.end>e&&i.removeFragment(s)}}))},e.removeFragment=function removeFragment(e){var t=getFragmentKey(e);e.stats.loaded=0,e.clearElementaryStreamInfo(),delete this.fragments[t]},e.removeAllFragments=function removeAllFragments(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},FragmentTracker}();function isPartial(e){var t,r;return e.buffered&&((null===(t=e.range.video)||void 0===t?void 0:t.partial)||(null===(r=e.range.audio)||void 0===r?void 0:r.partial))}function getFragmentKey(e){return e.type+"_"+e.level+"_"+e.urlId+"_"+e.sn}},"./src/controller/gap-controller.ts":
66
- /*!******************************************!*\
67
- !*** ./src/controller/gap-controller.ts ***!
68
- \******************************************/
69
- /*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */function(e,t,r){"use strict";r.r(t),r.d(t,"STALL_MINIMUM_DURATION_MS",(function(){return o})),r.d(t,"MAX_START_GAP_JUMP",(function(){return l})),r.d(t,"SKIP_BUFFER_HOLE_STEP_SECONDS",(function(){return u})),r.d(t,"SKIP_BUFFER_RANGE_START",(function(){return d})),r.d(t,"default",(function(){return c}));var i=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),n=r(/*! ../errors */"./src/errors.ts"),a=r(/*! ../events */"./src/events.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=250,l=2,u=.1,d=.05,c=function(){function GapController(e,t,r,i){this.config=void 0,this.media=void 0,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=r,this.hls=i}var e=GapController.prototype;return e.destroy=function destroy(){this.hls=this.fragmentTracker=this.media=null},e.poll=function poll(e){var t=this.config,r=this.media,n=this.stalled,a=r.currentTime,u=r.seeking,d=this.seeking&&!u,c=!this.seeking&&u;if(this.seeking=u,a===e){if((c||d)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&&i.BufferHelper.getBuffered(r).length){var h=i.BufferHelper.bufferInfo(r,a,0),f=h.len>0,g=h.nextStart||0;if(f||g){if(u){var v=h.len>l,p=!g||g-a>l&&!this.fragmentTracker.getPartialFragment(a);if(v||p)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var m,y=Math.max(g,h.start||0)-a,E=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,T=(null==E?void 0:null===(m=E.details)||void 0===m?void 0:m.live)?2*E.details.targetduration:l;if(y>0&&y<=T)return void this._trySkipBufferHole(null)}var S=self.performance.now();if(null!==n){var b=S-n;!u&&b>=o&&this._reportStall(h.len);var L=i.BufferHelper.bufferInfo(r,a,t.maxBufferHole);this._tryFixBufferStall(L,b)}else this.stalled=S}}}else if(this.moved=!0,null!==n){if(this.stallReported){var A=self.performance.now()-n;s.logger.warn("playback not stuck anymore @"+a+", after "+Math.round(A)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},e._tryFixBufferStall=function _tryFixBufferStall(e,t){var r=this.config,i=this.fragmentTracker,n=this.media.currentTime,a=i.getPartialFragment(n);if(a&&this._trySkipBufferHole(a))return;e.len>r.maxBufferHole&&t>1e3*r.highBufferWatchdogPeriod&&(s.logger.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},e._reportStall=function _reportStall(e){var t=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,s.logger.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+e+")"),t.trigger(a.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:e}))},e._trySkipBufferHole=function _trySkipBufferHole(e){for(var t=this.config,r=this.hls,o=this.media,l=o.currentTime,c=0,h=i.BufferHelper.getBuffered(o),f=0;f<h.length;f++){var g=h.start(f);if(l+t.maxBufferHole>=c&&l<g){var v=Math.max(g+d,o.currentTime+u);return s.logger.warn("skipping hole, adjusting currentTime from "+l+" to "+v),this.moved=!0,this.stalled=null,o.currentTime=v,e&&r.trigger(a.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,reason:"fragment loaded with buffer holes, seeking from "+l+" to "+v,frag:e}),v}c=h.end(f)}return 0},e._tryNudgeBuffer=function _tryNudgeBuffer(){var e=this.config,t=this.hls,r=this.media,i=r.currentTime,o=(this.nudgeRetry||0)+1;if(this.nudgeRetry=o,o<e.nudgeMaxRetry){var l=i+o*e.nudgeOffset;s.logger.warn("Nudging 'currentTime' from "+i+" to "+l),r.currentTime=l,t.trigger(a.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_NUDGE_ON_STALL,fatal:!1})}else s.logger.error("Playhead still not moving while enough data buffered @"+i+" after "+e.nudgeMaxRetry+" nudges"),t.trigger(a.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!0})},GapController}()},"./src/controller/id3-track-controller.ts":
70
- /*!************************************************!*\
71
- !*** ./src/controller/id3-track-controller.ts ***!
72
- \************************************************/
73
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../utils/texttrack-utils */"./src/utils/texttrack-utils.ts"),a=r(/*! ../demux/id3 */"./src/demux/id3.ts"),s=function(){function ID3TrackController(e){this.hls=void 0,this.id3Track=null,this.media=null,this.hls=e,this._registerListeners()}var e=ID3TrackController.prototype;return e.destroy=function destroy(){this._unregisterListeners()},e._registerListeners=function _registerListeners(){var e=this.hls;e.on(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(i.Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(i.Events.BUFFER_FLUSHING,this.onBufferFlushing,this)},e._unregisterListeners=function _unregisterListeners(){var e=this.hls;e.off(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(i.Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(i.Events.BUFFER_FLUSHING,this.onBufferFlushing,this)},e.onMediaAttached=function onMediaAttached(e,t){this.media=t.media},e.onMediaDetaching=function onMediaDetaching(){this.id3Track&&(Object(n.clearCurrentCues)(this.id3Track),this.id3Track=null,this.media=null)},e.getID3Track=function getID3Track(e){if(this.media){for(var t=0;t<e.length;t++){var r=e[t];if("metadata"===r.kind&&"id3"===r.label)return Object(n.sendAddTrackEvent)(r,this.media),r}return this.media.addTextTrack("metadata","id3")}},e.onFragParsingMetadata=function onFragParsingMetadata(e,t){if(this.media){var r=t.frag,i=t.samples;this.id3Track||(this.id3Track=this.getID3Track(this.media.textTracks),this.id3Track.mode="hidden");for(var n=self.WebKitDataCue||self.VTTCue||self.TextTrackCue,s=0;s<i.length;s++){var o=a.getID3Frames(i[s].data);if(o){var l=i[s].pts,u=s<i.length-1?i[s+1].pts:r.end;u-l<=0&&(u=l+.25);for(var d=0;d<o.length;d++){var c=o[d];if(!a.isTimeStampFrame(c)){var h=new n(l,u,"");h.value=c,this.id3Track.addCue(h)}}}}}},e.onBufferFlushing=function onBufferFlushing(e,t){var r=t.startOffset,i=t.endOffset,a=t.type;if(!a||"audio"===a){var s=this.id3Track;s&&Object(n.removeCuesInRange)(s,r,i)}},ID3TrackController}();t.default=s},"./src/controller/latency-controller.ts":
74
- /*!**********************************************!*\
75
- !*** ./src/controller/latency-controller.ts ***!
76
- \**********************************************/
77
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return s}));var i=r(/*! ../errors */"./src/errors.ts"),n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var s=function(){function LatencyController(e){var t=this;this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=function(){return t.timeupdate()},this.hls=e,this.config=e.config,this.registerListeners()}var e=LatencyController.prototype;return e.destroy=function destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null},e.registerListeners=function registerListeners(){this.hls.on(n.Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(n.Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(n.Events.ERROR,this.onError,this)},e.unregisterListeners=function unregisterListeners(){this.hls.off(n.Events.MEDIA_ATTACHED,this.onMediaAttached),this.hls.off(n.Events.MEDIA_DETACHING,this.onMediaDetaching),this.hls.off(n.Events.MANIFEST_LOADING,this.onManifestLoading),this.hls.off(n.Events.LEVEL_UPDATED,this.onLevelUpdated),this.hls.off(n.Events.ERROR,this.onError)},e.onMediaAttached=function onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)},e.onMediaDetaching=function onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)},e.onManifestLoading=function onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0},e.onLevelUpdated=function onLevelUpdated(e,t){var r=t.details;this.levelDetails=r,r.advanced&&this.timeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)},e.onError=function onError(e,t){t.details===i.ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,a.logger.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))},e.timeupdate=function timeupdate(){var e=this.media,t=this.levelDetails;if(e&&t){this.currentTime=e.currentTime;var r=this.computeLatency();if(null!==r){this._latency=r;var i=this.config,n=i.lowLatencyMode,a=i.maxLiveSyncPlaybackRate;if(n&&1!==a){var s=this.targetLatency;if(null!==s){var o=r-s,l=o<Math.min(this.maxLatency,s+t.targetduration);if(t.live&&l&&o>.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(u,Math.max(1,d))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}}}}},e.estimateLiveEdge=function estimateLiveEdge(){var e=this.levelDetails;return null===e?null:e.edge+e.age},e.computeLatency=function computeLatency(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(LatencyController,[{key:"latency",get:function get(){return this._latency||0}},{key:"maxLatency",get:function get(){var e=this.config,t=this.levelDetails;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function get(){var e=this.levelDetails;if(null===e)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||t;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var d=i;return u+Math.min(1*this.stallCount,d)}},{key:"liveSyncPosition",get:function get(){var e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(null===e||null===t||null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function get(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function get(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function get(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return r?e.buffered.end(r-1):t.edge-this.currentTime}}]),LatencyController}()},"./src/controller/level-controller.ts":
78
- /*!********************************************!*\
79
- !*** ./src/controller/level-controller.ts ***!
80
- \********************************************/
81
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return c}));var i=r(/*! ../types/level */"./src/types/level.ts"),n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../errors */"./src/errors.ts"),s=r(/*! ../utils/codecs */"./src/utils/codecs.ts"),o=r(/*! ./level-helper */"./src/controller/level-helper.ts"),l=r(/*! ./base-playlist-controller */"./src/controller/base-playlist-controller.ts"),u=r(/*! ../types/loader */"./src/types/loader.ts");function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e}).apply(this,arguments)}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var d=/chrome|firefox/.test(navigator.userAgent.toLowerCase()),c=function(e){function LevelController(t){var r;return(r=e.call(this,t,"[level-controller]")||this)._levels=[],r._firstLevel=-1,r._startLevel=void 0,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.onParsedComplete=void 0,r._registerListeners(),r}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(LevelController,e);var t=LevelController.prototype;return t._registerListeners=function _registerListeners(){var e=this.hls;e.on(n.Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(n.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(n.Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(n.Events.FRAG_LOADED,this.onFragLoaded,this),e.on(n.Events.ERROR,this.onError,this)},t._unregisterListeners=function _unregisterListeners(){var e=this.hls;e.off(n.Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(n.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(n.Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(n.Events.FRAG_LOADED,this.onFragLoaded,this),e.off(n.Events.ERROR,this.onError,this)},t.destroy=function destroy(){this._unregisterListeners(),this.manualLevelIndex=-1,this._levels.length=0,e.prototype.destroy.call(this)},t.startLoad=function startLoad(){this._levels.forEach((function(e){e.loadError=0})),e.prototype.startLoad.call(this)},t.onManifestLoaded=function onManifestLoaded(e,t){var r,l,u=[],c=[],h=[],f={},g=!1,v=!1,p=!1;if(t.levels.forEach((function(e){var t=e.attrs;g=g||!(!e.width||!e.height),v=v||!!e.videoCodec,p=p||!!e.audioCodec,d&&e.audioCodec&&-1!==e.audioCodec.indexOf("mp4a.40.34")&&(e.audioCodec=void 0);var r=e.bitrate+"-"+e.attrs.RESOLUTION+"-"+e.attrs.CODECS;(l=f[r])?l.url.push(e.url):(l=new i.Level(e),f[r]=l,u.push(l)),t&&(t.AUDIO&&Object(o.addGroupId)(l,"audio",t.AUDIO),t.SUBTITLES&&Object(o.addGroupId)(l,"text",t.SUBTITLES))})),(g||v)&&p&&(u=u.filter((function(e){var t=e.videoCodec,r=e.width,i=e.height;return!!t||!(!r||!i)}))),u=u.filter((function(e){var t=e.audioCodec,r=e.videoCodec;return(!t||Object(s.isCodecSupportedInMp4)(t,"audio"))&&(!r||Object(s.isCodecSupportedInMp4)(r,"video"))})),t.audioTracks&&(c=t.audioTracks.filter((function(e){return!e.audioCodec||Object(s.isCodecSupportedInMp4)(e.audioCodec,"audio")})),Object(o.assignTrackIdsByGroup)(c)),t.subtitles&&(h=t.subtitles,Object(o.assignTrackIdsByGroup)(h)),u.length>0){r=u[0].bitrate,u.sort((function(e,t){return e.bitrate-t.bitrate})),this._levels=u;for(var m=0;m<u.length;m++)if(u[m].bitrate===r){this._firstLevel=m,this.log("manifest loaded, "+u.length+" level(s) found, first bitrate: "+r);break}var y=p&&!v,E={levels:u,audioTracks:c,subtitleTracks:h,firstLevel:this._firstLevel,stats:t.stats,audio:p,video:v,altAudio:!y&&c.some((function(e){return!!e.url}))};this.hls.trigger(n.Events.MANIFEST_PARSED,E),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}else this.hls.trigger(n.Events.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,reason:"no level with compatible codecs found in manifest"})},t.onError=function onError(t,r){if(e.prototype.onError.call(this,t,r),!r.fatal){var i=r.context,n=this._levels[this.currentLevelIndex];if(i&&(i.type===u.PlaylistContextType.AUDIO_TRACK&&n.audioGroupIds&&i.groupId===n.audioGroupIds[n.urlId]||i.type===u.PlaylistContextType.SUBTITLE_TRACK&&n.textGroupIds&&i.groupId===n.textGroupIds[n.urlId]))this.redundantFailover(this.currentLevelIndex);else{var s,o=!1,l=!0;switch(r.details){case a.ErrorDetails.FRAG_LOAD_ERROR:case a.ErrorDetails.FRAG_LOAD_TIMEOUT:case a.ErrorDetails.KEY_LOAD_ERROR:case a.ErrorDetails.KEY_LOAD_TIMEOUT:if(r.frag){var d=this._levels[r.frag.level];d?(d.fragmentError++,d.fragmentError>this.hls.config.fragLoadingMaxRetry&&(s=r.frag.level)):s=r.frag.level}break;case a.ErrorDetails.LEVEL_LOAD_ERROR:case a.ErrorDetails.LEVEL_LOAD_TIMEOUT:i&&(i.deliveryDirectives&&(l=!1),s=i.level),o=!0;break;case a.ErrorDetails.REMUX_ALLOC_ERROR:s=r.level,o=!0}void 0!==s&&this.recoverLevel(r,s,o,l)}}},t.recoverLevel=function recoverLevel(e,t,r,i){var n=e.details,a=this._levels[t];if(a.loadError++,r){if(!this.retryLoadingOrFail(e))return void(this.currentLevelIndex=-1);e.levelRetry=!0}if(i){var s=a.url.length;if(s>1&&a.loadError<s)e.levelRetry=!0,this.redundantFailover(t);else if(-1===this.manualLevelIndex){var o=0===t?this._levels.length-1:t-1;this.currentLevelIndex!==o&&0===this._levels[o].loadError&&(this.warn(n+": switch to "+o),e.levelRetry=!0,this.hls.nextAutoLevel=o)}}},t.redundantFailover=function redundantFailover(e){var t=this._levels[e],r=t.url.length;if(r>1){var i=(t.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(e){e.urlId=i})),this.level=e}},t.onFragLoaded=function onFragLoaded(e,t){var r=t.frag;if(void 0!==r&&r.type===u.PlaylistLevelType.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},t.onLevelLoaded=function onLevelLoaded(e,t){var r,i,n=t.level,a=t.details,s=this._levels[n];if(!s)return this.warn("Invalid level index "+n),void(null!==(i=t.deliveryDirectives)&&void 0!==i&&i.skip&&(a.deltaUpdateFailed=!0));n===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0,this.retryCount=0),this.playlistLoaded(n,t,s.details)):null!==(r=t.deliveryDirectives)&&void 0!==r&&r.skip&&(a.deltaUpdateFailed=!0)},t.onAudioTrackSwitched=function onAudioTrackSwitched(e,t){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,n=this.hls.audioTracks[t.id].groupId,a=0;a<r.audioGroupIds.length;a++)if(r.audioGroupIds[a]===n){i=a;break}i!==r.urlId&&(r.urlId=i,this.startLoad())}},t.loadPlaylist=function loadPlaylist(e){var t=this.currentLevelIndex,r=this._levels[t];if(this.canLoad&&r&&r.url.length>0){var i=r.urlId,a=r.url[i];if(e)try{a=e.addDirectives(a)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}this.log("Attempt loading level index "+t+(e?" at sn "+e.msn+" part "+e.part:"")+" with URL-id "+i+" "+a),this.clearTimer(),this.hls.trigger(n.Events.LEVEL_LOADING,{url:a,level:t,id:i,deliveryDirectives:e||null})}},t.removeLevel=function removeLevel(e,t){var r=function filterLevelAndGroupByIdIndex(e,r){return r!==t},i=this._levels.filter((function(i,n){return n!==e||i.url.length>1&&void 0!==t&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(e,t){var r=e.details;return null!=r&&r.fragments&&r.fragments.forEach((function(e){e.level=t})),e}));this._levels=i,this.hls.trigger(n.Events.LEVELS_UPDATED,{levels:i})},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(LevelController,[{key:"levels",get:function get(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function get(){return this.currentLevelIndex},set:function set(e){var t,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==e||null===(t=r[e])||void 0===t||!t.details)){if(e<0||e>=r.length){var i=e<0;if(this.hls.trigger(n.Events.ERROR,{type:a.ErrorTypes.OTHER_ERROR,details:a.ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:i,reason:"invalid level idx"}),i)return;e=Math.min(e,r.length-1)}this.clearTimer();var s=this.currentLevelIndex,o=r[s],l=r[e];this.log("switching to level "+e+" from "+s),this.currentLevelIndex=e;var u=_extends({},l,{level:e,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete u._urlId,this.hls.trigger(n.Events.LEVEL_SWITCHING,u);var d=l.details;if(!d||d.live){var c=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(c)}}}},{key:"manualLevel",get:function get(){return this.manualLevelIndex},set:function set(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function get(){return this._firstLevel},set:function set(e){this._firstLevel=e}},{key:"startLevel",get:function get(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function set(e){this._startLevel=e}},{key:"nextLoadLevel",get:function get(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function set(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}]),LevelController}(l.default)},"./src/controller/level-helper.ts":
82
- /*!****************************************!*\
83
- !*** ./src/controller/level-helper.ts ***!
84
- \****************************************/
85
- /*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, addSliding, computeReloadInterval, getFragmentWithSN, getPartWith */function(e,t,r){"use strict";r.r(t),r.d(t,"addGroupId",(function(){return addGroupId})),r.d(t,"assignTrackIdsByGroup",(function(){return assignTrackIdsByGroup})),r.d(t,"updatePTS",(function(){return updatePTS})),r.d(t,"updateFragPTSDTS",(function(){return updateFragPTSDTS})),r.d(t,"mergeDetails",(function(){return mergeDetails})),r.d(t,"mapPartIntersection",(function(){return mapPartIntersection})),r.d(t,"mapFragmentIntersection",(function(){return mapFragmentIntersection})),r.d(t,"adjustSliding",(function(){return adjustSliding})),r.d(t,"addSliding",(function(){return addSliding})),r.d(t,"computeReloadInterval",(function(){return computeReloadInterval})),r.d(t,"getFragmentWithSN",(function(){return getFragmentWithSN})),r.d(t,"getPartWith",(function(){return getPartWith}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../utils/logger */"./src/utils/logger.ts");function addGroupId(e,t,r){switch(t){case"audio":e.audioGroupIds||(e.audioGroupIds=[]),e.audioGroupIds.push(r);break;case"text":e.textGroupIds||(e.textGroupIds=[]),e.textGroupIds.push(r)}}function assignTrackIdsByGroup(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}function updatePTS(e,t,r){updateFromToPTS(e[t],e[r])}function updateFromToPTS(e,t){var r=t.startPTS;if(Object(i.isFiniteNumber)(r)){var n,a=0;t.sn>e.sn?(a=r-e.start,n=e):(a=e.start-r,n=t),n.duration!==a&&(n.duration=a)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function updateFragPTSDTS(e,t,r,a,s,o){a-r<=0&&(n.logger.warn("Fragment should have a positive duration",t),a=r+t.duration,o=s+t.duration);var l=r,u=a,d=t.startPTS,c=t.endPTS;if(Object(i.isFiniteNumber)(d)){var h=Math.abs(d-r);Object(i.isFiniteNumber)(t.deltaPTS)?t.deltaPTS=Math.max(h,t.deltaPTS):t.deltaPTS=h,l=Math.max(r,d),r=Math.min(r,d),s=Math.min(s,t.startDTS),u=Math.min(a,c),a=Math.max(a,c),o=Math.max(o,t.endDTS)}t.duration=a-r;var f=r-t.start;t.appendedPTS=a,t.start=t.startPTS=r,t.maxStartPTS=l,t.startDTS=s,t.endPTS=a,t.minEndPTS=u,t.endDTS=o;var g,v=t.sn;if(!e||v<e.startSN||v>e.endSN)return 0;var p=v-e.startSN,m=e.fragments;for(m[p]=t,g=p;g>0;g--)updateFromToPTS(m[g],m[g-1]);for(g=p;g<m.length-1;g++)updateFromToPTS(m[g],m[g+1]);return e.fragmentHint&&updateFromToPTS(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,f}function mergeDetails(e,t){for(var r=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){r=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;var l,u=0;if(mapFragmentIntersection(e,t,(function(e,n){var a;e.relurl&&(u=e.cc-n.cc),Object(i.isFiniteNumber)(e.startPTS)&&Object(i.isFiniteNumber)(e.endPTS)&&(n.start=n.startPTS=e.startPTS,n.startDTS=e.startDTS,n.appendedPTS=e.appendedPTS,n.maxStartPTS=e.maxStartPTS,n.endPTS=e.endPTS,n.endDTS=e.endDTS,n.minEndPTS=e.minEndPTS,n.duration=e.endPTS-e.startPTS,n.duration&&(l=n),t.PTSKnown=t.alignedSliding=!0),n.elementaryStreams=e.elementaryStreams,n.loader=e.loader,n.stats=e.stats,n.urlId=e.urlId,e.initSegment?(n.initSegment=e.initSegment,r=e.initSegment):n.initSegment&&n.initSegment.relurl!=(null===(a=r)||void 0===a?void 0:a.relurl)||(n.initSegment=r)})),t.skippedSegments&&(t.deltaUpdateFailed=t.fragments.some((function(e){return!e})),t.deltaUpdateFailed)){n.logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var d=t.skippedSegments;d--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}var c=t.fragments;if(u){n.logger.warn("discontinuity sliding from playlist, take drift into account");for(var h=0;h<c.length;h++)c[h].cc+=u}t.skippedSegments&&(t.startCC=t.fragments[0].cc);for(var f=0;f<c.length;f++){var g,v=c[f];v.initSegment&&v.initSegment.relurl==(null===(g=r)||void 0===g?void 0:g.relurl)&&(v.initSegment=r)}mapPartIntersection(e.partList,t.partList,(function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),l?updateFragPTSDTS(t,l,l.startPTS,l.endPTS,l.startDTS,l.endDTS):adjustSliding(e,t),c.length&&(t.totalduration=t.edge-c[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var p=t.advancedDateTime;if(t.advanced&&p){var m=t.edge;t.driftStart||(t.driftStartTime=p,t.driftStart=m),t.driftEndTime=p,t.driftEnd=m}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function mapPartIntersection(e,t,r){if(e&&t)for(var i=0,n=0,a=e.length;n<=a;n++){var s=e[n],o=t[n+i];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):i--}}function mapFragmentIntersection(e,t,r){for(var i=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=n;u<=a;u++){var d=l[s+u],c=o[u];i&&!c&&u<i&&(c=t.fragments[u]=d),d&&c&&r(d,c)}}function adjustSliding(e,t){var r=t.startSN+t.skippedSegments-e.startSN,i=e.fragments;r<0||r>=i.length||addSliding(t,i[r].start)}function addSliding(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function computeReloadInterval(e,t){var r,i=1e3*e.levelTargetDuration,n=i/2,a=e.age,s=a>0&&a<3*i,o=t.loading.end-t.loading.start,l=e.availabilityDelay;if(!1===e.updated)if(s){var u=333*e.misses;r=Math.max(Math.min(n,2*o),u),e.availabilityDelay=(e.availabilityDelay||0)+r}else r=n;else s?(l=Math.min(l||i/2,a),e.availabilityDelay=l,r=l+i-a):r=i-o;return Math.round(r)}function getFragmentWithSN(e,t,r){if(!e||!e.details)return null;var i=e.details,n=i.fragments[t-i.startSN];return n||((n=i.fragmentHint)&&n.sn===t?n:t<i.startSN&&r&&r.sn===t?r:null)}function getPartWith(e,t,r){if(!e||!e.details)return null;var i=e.details.partList;if(i)for(var n=i.length;n--;){var a=i[n];if(a.index===r&&a.fragment.sn===t)return a}return null}},"./src/controller/stream-controller.ts":
86
- /*!*********************************************!*\
87
- !*** ./src/controller/stream-controller.ts ***!
88
- \*********************************************/
89
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return p}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./base-stream-controller */"./src/controller/base-stream-controller.ts"),a=r(/*! ../is-supported */"./src/is-supported.ts"),s=r(/*! ../events */"./src/events.ts"),o=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),l=r(/*! ./fragment-tracker */"./src/controller/fragment-tracker.ts"),u=r(/*! ../types/loader */"./src/types/loader.ts"),d=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),c=r(/*! ../demux/transmuxer-interface */"./src/demux/transmuxer-interface.ts"),h=r(/*! ../types/transmuxer */"./src/types/transmuxer.ts"),f=r(/*! ./gap-controller */"./src/controller/gap-controller.ts"),g=r(/*! ../errors */"./src/errors.ts"),v=r(/*! ../utils/logger */"./src/utils/logger.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var p=function(e){function StreamController(t,r){var i;return(i=e.call(this,t,r,"[stream-controller]")||this).audioCodecSwap=!1,i.gapController=null,i.level=-1,i._forceStartLoad=!1,i.altAudio=!1,i.audioOnly=!1,i.fragPlaying=null,i.onvplaying=null,i.onvseeked=null,i.fragLastKbps=0,i.stalled=!1,i.couldBacktrack=!1,i.audioCodecSwitch=!1,i.videoBuffer=null,i._registerListeners(),i}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(StreamController,e);var t=StreamController.prototype;return t._registerListeners=function _registerListeners(){var e=this.hls;e.on(s.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(s.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(s.Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(s.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(s.Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(s.Events.ERROR,this.onError,this),e.on(s.Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(s.Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(s.Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(s.Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(s.Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(s.Events.FRAG_BUFFERED,this.onFragBuffered,this)},t._unregisterListeners=function _unregisterListeners(){var e=this.hls;e.off(s.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(s.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(s.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(s.Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(s.Events.ERROR,this.onError,this),e.off(s.Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(s.Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(s.Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(s.Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(s.Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(s.Events.FRAG_BUFFERED,this.onFragBuffered,this)},t.onHandlerDestroying=function onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()},t.startLoad=function startLoad(e){if(this.levels){var t=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&&(r.config.testBandwidth?(i=0,this.bitrateTest=!0):i=r.nextAutoLevel),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&-1===e&&(this.log("Override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=n.State.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=n.State.STOPPED},t.stopLoad=function stopLoad(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},t.doTick=function doTick(){switch(this.state){case n.State.IDLE:this.doTickIdle();break;case n.State.WAITING_LEVEL:var e,t=this.levels,r=this.level,i=null==t?void 0:null===(e=t[r])||void 0===e?void 0:e.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=n.State.IDLE;break}break;case n.State.FRAG_LOADING_WAITING_RETRY:var a,s=self.performance.now(),o=this.retryDate;(!o||s>=o||null!==(a=this.media)&&void 0!==a&&a.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.state=n.State.IDLE)}this.onTickEnd()},t.onTickEnd=function onTickEnd(){e.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},t.doTickIdle=function doTickIdle(){var e,t,r=this.hls,i=this.levelLastLoaded,a=this.levels,o=this.media,c=r.config,h=r.nextLoadLevel;if(null!==i&&(o||!this.startFragRequested&&c.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&a&&a[h]){var f=a[h];this.level=r.nextLoadLevel=h;var g=f.details;if(!g||this.state===n.State.WAITING_LEVEL||g.live&&this.levelLastLoaded!==h)this.state=n.State.WAITING_LEVEL;else{var v=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:o,u.PlaylistLevelType.MAIN);if(null!==v)if(!(v.len>=this.getMaxBufferLength(f.maxBitrate))){if(this._streamEnded(v,g)){var p={};return this.altAudio&&(p.type="video"),this.hls.trigger(s.Events.BUFFER_EOS,p),void(this.state=n.State.ENDED)}var m=v.end,y=this.getNextFragment(m,g);if(this.couldBacktrack&&!this.fragPrevious&&y&&"initSegment"!==y.sn){var E=y.sn-g.startSN;E>1&&(y=g.fragments[E-1],this.fragmentTracker.removeFragment(y))}if(y&&this.fragmentTracker.getState(y)===l.FragmentState.OK&&this.nextLoadPosition>m){var T=this.audioOnly&&!this.altAudio?d.ElementaryStreamTypes.AUDIO:d.ElementaryStreamTypes.VIDEO;this.afterBufferFlushed(o,T,u.PlaylistLevelType.MAIN),y=this.getNextFragment(this.nextLoadPosition,g)}y&&(!y.initSegment||y.initSegment.data||this.bitrateTest||(y=y.initSegment),"identity"!==(null===(e=y.decryptdata)||void 0===e?void 0:e.keyFormat)||null!==(t=y.decryptdata)&&void 0!==t&&t.key?this.loadFragment(y,g,m):this.loadKey(y,g))}}}},t.loadFragment=function loadFragment(t,r,i){var n,a=this.fragmentTracker.getState(t);if(this.fragCurrent=t,a===l.FragmentState.BACKTRACKED){var s=this.fragmentTracker.getBacktrackData(t);if(s)return this._handleFragmentLoadProgress(s),void this._handleFragmentLoadComplete(s);a=l.FragmentState.NOT_LOADED}a===l.FragmentState.NOT_LOADED||a===l.FragmentState.PARTIAL?"initSegment"===t.sn?this._loadInitSegment(t):this.bitrateTest?(t.bitrateTest=!0,this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t)):(this.startFragRequested=!0,e.prototype.loadFragment.call(this,t,r,i)):a===l.FragmentState.APPENDING?this.reduceMaxBufferLength(t.duration)&&this.fragmentTracker.removeFragment(t):0===(null===(n=this.media)||void 0===n?void 0:n.buffered.length)&&this.fragmentTracker.removeAllFragments()},t.getAppendedFrag=function getAppendedFrag(e){var t=this.fragmentTracker.getAppendedFrag(e,u.PlaylistLevelType.MAIN);return t&&"fragment"in t?t.fragment:t},t.getBufferedFrag=function getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,u.PlaylistLevelType.MAIN)},t.followingBufferedFrag=function followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null},t.immediateLevelSwitch=function immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},t.nextLevelSwitch=function nextLevelSwitch(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!t.paused&&e){var n=e[this.hls.nextLoadLevel],a=this.fragLastKbps;r=a&&this.fragCurrent?this.fragCurrent.duration*n.maxBitrate/(1e3*a)+1:0}else r=0;var s=this.getBufferedFrag(t.currentTime+r);if(s){var o=this.followingBufferedFrag(s);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,d=Math.max(s.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,.5*u),.75*u));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}},t.abortCurrentFrag=function abortCurrentFrag(){var e=this.fragCurrent;this.fragCurrent=null,null!=e&&e.loader&&e.loader.abort(),this.state===n.State.KEY_LOADING&&(this.state=n.State.IDLE),this.nextLoadPosition=this.getLoadPosition()},t.flushMainBuffer=function flushMainBuffer(t,r){e.prototype.flushMainBuffer.call(this,t,r,this.altAudio?"video":null)},t.onMediaAttached=function onMediaAttached(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new f.default(this.config,i,this.fragmentTracker,this.hls)},t.onMediaDetaching=function onMediaDetaching(){var t=this.media;t&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),e.prototype.onMediaDetaching.call(this)},t.onMediaPlaying=function onMediaPlaying(){this.tick()},t.onMediaSeeked=function onMediaSeeked(){var e=this.media,t=e?e.currentTime:null;Object(i.isFiniteNumber)(t)&&this.log("Media seeked to "+t.toFixed(3)),this.tick()},t.onManifestLoading=function onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(s.Events.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=this.stalled=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null},t.onManifestParsed=function onManifestParsed(e,t){var r,i=!1,n=!1;t.levels.forEach((function(e){(r=e.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(i=!0),-1!==r.indexOf("mp4a.40.5")&&(n=!0))})),this.audioCodecSwitch=i&&n&&!Object(a.changeTypeSupported)(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1},t.onLevelLoading=function onLevelLoading(e,t){var r=this.levels;if(r&&this.state===n.State.IDLE){var i=r[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(i.details))&&(this.state=n.State.WAITING_LEVEL)}},t.onLevelLoaded=function onLevelLoaded(e,t){var r,i=this.levels,a=t.level,o=t.details,l=o.totalduration;if(i){this.log("Level "+a+" loaded ["+o.startSN+","+o.endSN+"], cc ["+o.startCC+", "+o.endCC+"] duration:"+l);var u=this.fragCurrent;!u||this.state!==n.State.FRAG_LOADING&&this.state!==n.State.FRAG_LOADING_WAITING_RETRY||u.level!==t.level&&u.loader&&(this.state=n.State.IDLE,u.loader.abort());var d=i[a],c=0;if(o.live||null!==(r=d.details)&&void 0!==r&&r.live){if(o.fragments[0]||(o.deltaUpdateFailed=!0),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details)}if(d.details=o,this.levelLastLoaded=a,this.hls.trigger(s.Events.LEVEL_UPDATED,{details:o,level:a}),this.state===n.State.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=n.State.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,c),this.tick()}else this.warn("Levels were reset while loading level "+a)},t._handleFragmentLoadProgress=function _handleFragmentLoadProgress(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.levels;if(a){var s=a[r.level],o=s.details;if(o){var l=s.videoCodec,d=o.PTSKnown||!o.live,f=null===(t=r.initSegment)||void 0===t?void 0:t.data,g=this._getAudioCodec(s),v=this.transmuxer=this.transmuxer||new c.default(this.hls,u.PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=i?i.index:-1,m=-1!==p,y=new h.ChunkMetadata(r.level,r.sn,r.stats.chunkCount,n.byteLength,p,m),E=this.initPTS[r.cc];v.push(n,f,g,l,r,i,o.totalduration,d,y,E)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},t.onAudioTrackSwitching=function onAudioTrackSwitching(e,t){var r=this.altAudio,i=!!t.url,n=t.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var a=this.fragCurrent;null!=a&&a.loader&&(this.log("Switching to main audio track, cancel main fragment load"),a.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(s.Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(s.Events.AUDIO_TRACK_SWITCHED,{id:n})}},t.onAudioTrackSwitched=function onAudioTrackSwitched(e,t){var r=t.id,i=!!this.hls.audioTracks[r].url;if(i){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i,this.tick()},t.onBufferCreated=function onBufferCreated(e,t){var r,i,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},t.onFragBuffered=function onFragBuffered(e,t){var r=t.frag,i=t.part;if(!r||r.type===u.PlaylistLevelType.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===n.State.PARSED&&(this.state=n.State.IDLE));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},t.onError=function onError(e,t){switch(t.details){case g.ErrorDetails.FRAG_LOAD_ERROR:case g.ErrorDetails.FRAG_LOAD_TIMEOUT:case g.ErrorDetails.KEY_LOAD_ERROR:case g.ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(u.PlaylistLevelType.MAIN,t);break;case g.ErrorDetails.LEVEL_LOAD_ERROR:case g.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==n.State.ERROR&&(t.fatal?(this.warn(""+t.details),this.state=n.State.ERROR):t.levelRetry||this.state!==n.State.WAITING_LEVEL||(this.state=n.State.IDLE));break;case g.ErrorDetails.BUFFER_FULL_ERROR:if("main"===t.parent&&(this.state===n.State.PARSING||this.state===n.State.PARSED)){var r=!0,i=this.getFwdBufferInfo(this.media,u.PlaylistLevelType.MAIN);i&&i.len>.5&&(r=!this.reduceMaxBufferLength(i.len)),r&&(this.warn("buffer full error also media.currentTime is not buffered, flush main"),this.immediateLevelSwitch()),this.resetLoadingState()}}},t.checkBuffer=function checkBuffer(){var e=this.media,t=this.gapController;if(e&&t&&e.readyState){var r=o.BufferHelper.getBuffered(e);!this.loadedmetadata&&r.length?(this.loadedmetadata=!0,this.seekToStartPos()):t.poll(this.lastCurrentTime),this.lastCurrentTime=e.currentTime}},t.onFragLoadEmergencyAborted=function onFragLoadEmergencyAborted(){this.state=n.State.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},t.onBufferFlushed=function onBufferFlushed(e,t){var r=t.type;if(r!==d.ElementaryStreamTypes.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===d.ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,u.PlaylistLevelType.MAIN)}},t.onLevelsUpdated=function onLevelsUpdated(e,t){this.levels=t.levels},t.swapAudioCodec=function swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap},t.seekToStartPos=function seekToStartPos(){var e=this.media,t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void v.logger.log("could not seek to "+r+", already seeking at "+t);var i=o.BufferHelper.getBuffered(e),n=(i.length?i.start(0):0)-r;n>0&&n<this.config.maxBufferHole&&(v.logger.log("adjusting start position by "+n+" to match buffer start"),r+=n,this.startPosition=r),this.log("seek to target start position "+r+" from current time "+t),e.currentTime=r}},t._getAudioCodec=function _getAudioCodec(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t},t._loadBitrateTestFrag=function _loadBitrateTestFrag(e){var t=this;this._doFragLoad(e).then((function(r){var i=t.hls;if(r&&!i.nextLoadLevel&&!t.fragContextChanged(e)){t.fragLoadError=0,t.state=n.State.IDLE,t.startFragRequested=!1,t.bitrateTest=!1;var a=e.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(s.Events.FRAG_LOADED,r)}}))},t._handleTransmuxComplete=function _handleTransmuxComplete(e){var t,r="main",a=this.hls,o=e.remuxResult,l=e.chunkMeta,u=this.getCurrentContext(l);if(!u)return this.warn("The loading context changed while buffering fragment "+l.sn+" of level "+l.level+". This chunk will not be buffered."),void this.resetLiveStartWhenNotLoaded(l.level);var c=u.frag,h=u.part,f=u.level,g=o.video,v=o.text,p=o.id3,m=o.initSegment,y=this.altAudio?void 0:o.audio;if(!this.fragContextChanged(c)){if(this.state=n.State.PARSING,m){m.tracks&&(this._bufferInitSegment(f,m.tracks,c,l),a.trigger(s.Events.FRAG_PARSING_INIT_SEGMENT,{frag:c,id:r,tracks:m.tracks}));var E=m.initPTS,T=m.timescale;Object(i.isFiniteNumber)(E)&&(this.initPTS[c.cc]=E,a.trigger(s.Events.INIT_PTS_FOUND,{frag:c,id:r,initPTS:E,timescale:T}))}if(g&&!1!==o.independent){if(f.details){var S=g.startPTS,b=g.endPTS,L=g.startDTS,A=g.endDTS;if(h)h.elementaryStreams[g.type]={startPTS:S,endPTS:b,startDTS:L,endDTS:A};else if(g.firstKeyFrame&&g.independent&&(this.couldBacktrack=!0),g.dropped&&g.independent){if(this.getLoadPosition()+this.config.maxBufferHole<S)return void this.backtrack(c);c.setElementaryStreamInfo(g.type,c.start,b,c.start,A,!0)}c.setElementaryStreamInfo(g.type,S,b,L,A),this.bufferFragmentData(g,c,h,l)}}else if(!1===o.independent)return void this.backtrack(c);if(y){var _=y.startPTS,D=y.endPTS,k=y.startDTS,C=y.endDTS;h&&(h.elementaryStreams[d.ElementaryStreamTypes.AUDIO]={startPTS:_,endPTS:D,startDTS:k,endDTS:C}),c.setElementaryStreamInfo(d.ElementaryStreamTypes.AUDIO,_,D,k,C),this.bufferFragmentData(y,c,h,l)}if(null!=p&&null!==(t=p.samples)&&void 0!==t&&t.length){var R={frag:c,id:r,samples:p.samples};a.trigger(s.Events.FRAG_PARSING_METADATA,R)}if(v){var P={frag:c,id:r,samples:v.samples};a.trigger(s.Events.FRAG_PARSING_USERDATA,P)}}},t._bufferInitSegment=function _bufferInitSegment(e,t,r,i){var a=this;if(this.state===n.State.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;var o=t.audio,l=t.video,u=t.audiovideo;if(o){var d=e.audioCodec,c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(d&&(d=-1!==d.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==o.metadata.channelCount&&-1===c.indexOf("firefox")&&(d="mp4a.40.5")),-1!==c.indexOf("android")&&"audio/mpeg"!==o.container&&(d="mp4a.40.2",this.log("Android: force audio codec to "+d)),e.audioCodec&&e.audioCodec!==d&&this.log('Swapping manifest audio codec "'+e.audioCodec+'" for "'+d+'"'),o.levelCodec=d,o.id="main",this.log("Init audio buffer, container:"+o.container+", codecs[selected/level/parsed]=["+(d||"")+"/"+(e.audioCodec||"")+"/"+o.codec+"]")}l&&(l.levelCodec=e.videoCodec,l.id="main",this.log("Init video buffer, container:"+l.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+l.codec+"]")),u&&this.log("Init audiovideo buffer, container:"+u.container+", codecs[level/parsed]=["+(e.attrs.CODECS||"")+"/"+u.codec+"]"),this.hls.trigger(s.Events.BUFFER_CODECS,t),Object.keys(t).forEach((function(e){var n=t[e].initSegment;null!=n&&n.byteLength&&a.hls.trigger(s.Events.BUFFER_APPENDING,{type:e,data:n,frag:r,part:null,chunkMeta:i,parent:r.type})})),this.tick()}},t.backtrack=function backtrack(e){this.couldBacktrack=!0,this.resetTransmuxer(),this.flushBufferGap(e);var t=this.fragmentTracker.backtrack(e);this.fragPrevious=null,this.nextLoadPosition=e.start,t?this.resetFragmentLoading(e):this.state=n.State.BACKTRACKING},t.checkFragmentChanged=function checkFragmentChanged(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(o.BufferHelper.isBuffered(e,r)?t=this.getAppendedFrag(r):o.BufferHelper.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){var i=this.fragPlaying,n=t.level;i&&t.sn===i.sn&&i.level===n&&t.urlId===i.urlId||(this.hls.trigger(s.Events.FRAG_CHANGED,{frag:t}),i&&i.level===n||this.hls.trigger(s.Events.LEVEL_SWITCHED,{level:n}),this.fragPlaying=t)}}},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(StreamController,[{key:"nextLevel",get:function get(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentLevel",get:function get(){var e=this.media;if(e){var t=this.getAppendedFrag(e.currentTime);if(t)return t.level}return-1}},{key:"nextBufferedFrag",get:function get(){var e=this.media;if(e){var t=this.getAppendedFrag(e.currentTime);return this.followingBufferedFrag(t)}return null}},{key:"forceStartLoad",get:function get(){return this._forceStartLoad}}]),StreamController}(n.default)},"./src/controller/subtitle-stream-controller.ts":
90
- /*!******************************************************!*\
91
- !*** ./src/controller/subtitle-stream-controller.ts ***!
92
- \******************************************************/
93
- /*! exports provided: SubtitleStreamController */function(e,t,r){"use strict";r.r(t),r.d(t,"SubtitleStreamController",(function(){return f}));var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../utils/logger */"./src/utils/logger.ts"),a=r(/*! ../utils/buffer-helper */"./src/utils/buffer-helper.ts"),s=r(/*! ./fragment-finders */"./src/controller/fragment-finders.ts"),o=r(/*! ../utils/discontinuities */"./src/utils/discontinuities.ts"),l=r(/*! ./level-helper */"./src/controller/level-helper.ts"),u=r(/*! ./fragment-tracker */"./src/controller/fragment-tracker.ts"),d=r(/*! ./base-stream-controller */"./src/controller/base-stream-controller.ts"),c=r(/*! ../types/loader */"./src/types/loader.ts"),h=r(/*! ../types/level */"./src/types/level.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var f=function(e){function SubtitleStreamController(t,r){var i;return(i=e.call(this,t,r,"[subtitle-stream-controller]")||this).levels=[],i.currentTrackId=-1,i.tracksBuffered=[],i.mainDetails=null,i._registerListeners(),i}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(SubtitleStreamController,e);var t=SubtitleStreamController.prototype;return t.onHandlerDestroying=function onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null},t._registerListeners=function _registerListeners(){var e=this.hls;e.on(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(i.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(i.Events.ERROR,this.onError,this),e.on(i.Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(i.Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(i.Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(i.Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(i.Events.BUFFER_FLUSHING,this.onBufferFlushing,this)},t._unregisterListeners=function _unregisterListeners(){var e=this.hls;e.off(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(i.Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(i.Events.ERROR,this.onError,this),e.off(i.Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(i.Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(i.Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(i.Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(i.Events.BUFFER_FLUSHING,this.onBufferFlushing,this)},t.startLoad=function startLoad(){this.stopLoad(),this.state=d.State.IDLE,this.setInterval(500),this.tick()},t.onManifestLoading=function onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()},t.onLevelLoaded=function onLevelLoaded(e,t){this.mainDetails=t.details},t.onSubtitleFragProcessed=function onSubtitleFragProcessed(e,t){var r=t.frag,i=t.success;if(this.fragPrevious=r,this.state=d.State.IDLE,i){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=r.start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=r.start+r.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(r)}}},t.onBufferFlushing=function onBufferFlushing(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=this.currentTrackId,a=this.levels;if(!a.length||!a[n]||!a[n].details)return;var s=i-a[n].details.targetduration;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach((function(e){for(var t=0;t<e.length;)if(e[t].end<=s)e.shift();else{if(!(e[t].start<s))break;e[t].start=s,t++}})),this.fragmentTracker.removeFragmentsInRange(r,s,c.PlaylistLevelType.SUBTITLE)}},t.onError=function onError(e,t){var r,i=t.frag;i&&i.type===c.PlaylistLevelType.SUBTITLE&&(null!==(r=this.fragCurrent)&&void 0!==r&&r.loader&&this.fragCurrent.loader.abort(),this.state=d.State.IDLE)},t.onSubtitleTracksUpdated=function onSubtitleTracksUpdated(e,t){var r=this,i=t.subtitleTracks;this.tracksBuffered=[],this.levels=i.map((function(e){return new h.Level(e)})),this.fragmentTracker.removeAllFragments(),this.fragPrevious=null,this.levels.forEach((function(e){r.tracksBuffered[e.id]=[]})),this.mediaBuffer=null},t.onSubtitleTrackSwitch=function onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,this.levels.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.setInterval(500)):this.mediaBuffer=null}else this.clearInterval()},t.onSubtitleTrackLoaded=function onSubtitleTrackLoaded(e,t){var r,i=t.details,n=t.id,a=this.currentTrackId,u=this.levels;if(u.length){var c=u[a];if(!(n>=u.length||n!==a)&&c){if(this.mediaBuffer=this.mediaBufferTimeRanges,i.live||null!==(r=c.details)&&void 0!==r&&r.live){var h=this.mainDetails;if(i.deltaUpdateFailed||!h)return;var f=h.fragments[0];if(c.details)0===this.alignPlaylists(i,c.details)&&f&&Object(l.addSliding)(i,f.start);else i.hasProgramDateTime&&h.hasProgramDateTime?Object(o.alignPDT)(i,h):f&&Object(l.addSliding)(i,f.start)}if(c.details=i,this.levelLastLoaded=n,this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===d.State.IDLE)Object(s.findFragmentByPTS)(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)}}},t._handleFragmentLoadComplete=function _handleFragmentLoadComplete(e){var t=e.frag,r=e.payload,n=t.decryptdata,a=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&n&&n.key&&n.iv&&"AES-128"===n.method){var s=performance.now();this.decrypter.webCryptoDecrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer).then((function(e){var r=performance.now();a.trigger(i.Events.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:s,tdecrypt:r}})}))}},t.doTick=function doTick(){if(this.media){if(this.state===d.State.IDLE){var e,t=this.currentTrackId,r=this.levels;if(!r.length||!r[t]||!r[t].details)return;var o=r[t].details,l=o.targetduration,c=this.config,h=this.media,f=a.BufferHelper.bufferedInfo(this.mediaBufferTimeRanges,h.currentTime-l,c.maxBufferHole),g=f.end;if(f.len>this.getMaxBufferLength()+l)return;console.assert(o,"Subtitle track details are defined on idle subtitle stream controller tick");var v,p=o.fragments,m=p.length,y=o.edge,E=this.fragPrevious;if(g<y){var T=c.maxFragLookUpTolerance;E&&o.hasProgramDateTime&&(v=Object(s.findFragmentByPDT)(p,E.endProgramDateTime,T)),v||!(v=Object(s.findFragmentByPTS)(E,p,g,T))&&E&&E.start<p[0].start&&(v=p[0])}else v=p[m-1];null!==(e=v)&&void 0!==e&&e.encrypted?(n.logger.log("Loading key for "+v.sn),this.state=d.State.KEY_LOADING,this.hls.trigger(i.Events.KEY_LOADING,{frag:v})):v&&this.fragmentTracker.getState(v)===u.FragmentState.NOT_LOADED&&this.loadFragment(v,o,g)}}else this.state=d.State.IDLE},t.loadFragment=function loadFragment(t,r,i){this.fragCurrent=t,e.prototype.loadFragment.call(this,t,r,i)},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(SubtitleStreamController,[{key:"mediaBufferTimeRanges",get:function get(){return this.tracksBuffered[this.currentTrackId]||[]}}]),SubtitleStreamController}(d.default)},"./src/controller/subtitle-track-controller.ts":
94
- /*!*****************************************************!*\
95
- !*** ./src/controller/subtitle-track-controller.ts ***!
96
- \*****************************************************/
97
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../utils/texttrack-utils */"./src/utils/texttrack-utils.ts"),a=r(/*! ./base-playlist-controller */"./src/controller/base-playlist-controller.ts"),s=r(/*! ../types/loader */"./src/types/loader.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var o=function(e){function SubtitleTrackController(t){var r;return(r=e.call(this,t,"[subtitle-track-controller]")||this).media=null,r.tracks=[],r.groupId=null,r.tracksInGroup=[],r.trackId=-1,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.trackChangeListener=function(){return r.onTextTracksChanged()},r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r.subtitleDisplay=!0,r.registerListeners(),r}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(SubtitleTrackController,e);var t=SubtitleTrackController.prototype;return t.destroy=function destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,e.prototype.destroy.call(this)},t.registerListeners=function registerListeners(){var e=this.hls;e.on(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(i.Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(i.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(i.Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(i.Events.ERROR,this.onError,this)},t.unregisterListeners=function unregisterListeners(){var e=this.hls;e.off(i.Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(i.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(i.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(i.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(i.Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(i.Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(i.Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(i.Events.ERROR,this.onError,this)},t.onMediaAttached=function onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},t.pollTrackChange=function pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)},t.onMediaDetaching=function onMediaDetaching(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),filterSubtitleTracks(this.media.textTracks).forEach((function(e){Object(n.clearCurrentCues)(e)})),this.subtitleTrack=-1,this.media=null)},t.onManifestLoading=function onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0},t.onManifestParsed=function onManifestParsed(e,t){this.tracks=t.subtitleTracks},t.onSubtitleTrackLoaded=function onSubtitleTrackLoaded(e,t){var r=t.id,i=t.details,n=this.trackId,a=this.tracksInGroup[n];if(a){var s=a.details;a.details=t.details,this.log("subtitle track "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&(this.retryCount=0,this.playlistLoaded(r,t,s))}else this.warn("Invalid subtitle track id "+r)},t.onLevelLoading=function onLevelLoading(e,t){this.switchLevel(t.level)},t.onLevelSwitching=function onLevelSwitching(e,t){this.switchLevel(t.level)},t.switchLevel=function switchLevel(e){var t=this.hls.levels[e];if(null!=t&&t.textGroupIds){var r=t.textGroupIds[t.urlId];if(this.groupId!==r){var n=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0,a=this.tracks.filter((function(e){return!r||e.groupId===r}));this.tracksInGroup=a;var s=this.findTrackId(null==n?void 0:n.name)||this.findTrackId();this.groupId=r;var o={subtitleTracks:a};this.log("Updating subtitle tracks, "+a.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(i.Events.SUBTITLE_TRACKS_UPDATED,o),-1!==s&&this.setSubtitleTrack(s,n)}}},t.findTrackId=function findTrackId(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||e===i.name))return i.id}return-1},t.onError=function onError(t,r){e.prototype.onError.call(this,t,r),!r.fatal&&r.context&&r.context.type===s.PlaylistContextType.SUBTITLE_TRACK&&r.context.id===this.trackId&&r.context.groupId===this.groupId&&this.retryLoadingOrFail(r)},t.loadPlaylist=function loadPlaylist(e){var t=this.tracksInGroup[this.trackId];if(this.shouldLoadTrack(t)){var r=t.id,n=t.groupId,a=t.url;if(e)try{a=e.addDirectives(a)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}this.log("Loading subtitle playlist for id "+r),this.hls.trigger(i.Events.SUBTITLE_TRACK_LOADING,{url:a,id:r,groupId:n,deliveryDirectives:e||null})}},t.toggleTrackModes=function toggleTrackModes(e){var t=this,r=this.media,i=this.subtitleDisplay,n=this.trackId;if(r){var a=filterSubtitleTracks(r.textTracks),s=a.filter((function(e){return e.groupId===t.groupId}));if(-1===e)[].slice.call(a).forEach((function(e){e.mode="disabled"}));else{var o=s[n];o&&(o.mode="disabled")}var l=s[e];l&&(l.mode=i?"showing":"hidden")}},t.setSubtitleTrack=function setSubtitleTrack(e,t){var r,n=this.tracksInGroup;if(this.media){if(this.trackId!==e&&this.toggleTrackModes(e),!(this.trackId===e&&(-1===e||null!==(r=n[e])&&void 0!==r&&r.details)||e<-1||e>=n.length)){this.clearTimer();var a=n[e];if(this.log("Switching to subtitle track "+e),this.trackId=e,a){var s=a.id,o=a.groupId,l=void 0===o?"":o,u=a.name,d=a.type,c=a.url;this.hls.trigger(i.Events.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:d,url:c});var h=this.switchParams(a.url,null==t?void 0:t.details);this.loadPlaylist(h)}else this.hls.trigger(i.Events.SUBTITLE_TRACK_SWITCH,{id:e})}}else this.queuedDefaultTrack=e},t.onTextTracksChanged=function onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),this.media&&this.hls.config.renderTextTracksNatively){for(var e=-1,t=filterSubtitleTracks(this.media.textTracks),r=0;r<t.length;r++)if("hidden"===t[r].mode)e=r;else if("showing"===t[r].mode){e=r;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(SubtitleTrackController,[{key:"subtitleTracks",get:function get(){return this.tracksInGroup}},{key:"subtitleTrack",get:function get(){return this.trackId},set:function set(e){this.selectDefaultTrack=!1;var t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}}]),SubtitleTrackController}(a.default);function filterSubtitleTracks(e){for(var t=[],r=0;r<e.length;r++){var i=e[r];"subtitles"===i.kind&&i.label&&t.push(e[r])}return t}t.default=o},"./src/controller/timeline-controller.ts":
98
- /*!***********************************************!*\
99
- !*** ./src/controller/timeline-controller.ts ***!
100
- \***********************************************/
101
- /*! exports provided: TimelineController */function(e,t,r){"use strict";r.r(t),r.d(t,"TimelineController",(function(){return h}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../utils/cea-608-parser */"./src/utils/cea-608-parser.ts"),s=r(/*! ../utils/output-filter */"./src/utils/output-filter.ts"),o=r(/*! ../utils/webvtt-parser */"./src/utils/webvtt-parser.ts"),l=r(/*! ../utils/texttrack-utils */"./src/utils/texttrack-utils.ts"),u=r(/*! ../utils/imsc1-ttml-parser */"./src/utils/imsc1-ttml-parser.ts"),d=r(/*! ../types/loader */"./src/types/loader.ts"),c=r(/*! ../utils/logger */"./src/utils/logger.ts"),h=function(){function TimelineController(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.timescale=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!1}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){var t=new s.default(this,"textTrack1"),r=new s.default(this,"textTrack2"),i=new s.default(this,"textTrack3"),o=new s.default(this,"textTrack4");this.cea608Parser1=new a.default(1,t,r),this.cea608Parser2=new a.default(3,i,o)}e.on(n.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(n.Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(n.Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(n.Events.FRAG_LOADING,this.onFragLoading,this),e.on(n.Events.FRAG_LOADED,this.onFragLoaded,this),e.on(n.Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(n.Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(n.Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(n.Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}var e=TimelineController.prototype;return e.destroy=function destroy(){var e=this.hls;e.off(n.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(n.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(n.Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(n.Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(n.Events.FRAG_LOADING,this.onFragLoading,this),e.off(n.Events.FRAG_LOADED,this.onFragLoaded,this),e.off(n.Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(n.Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(n.Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(n.Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(n.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null},e.addCues=function addCues(e,t,r,i,a){for(var s,o,l,u,d=!1,c=a.length;c--;){var h=a[c],f=(s=h[0],o=h[1],l=t,u=r,Math.min(o,u)-Math.max(s,l));if(f>=0&&(h[0]=Math.min(h[0],t),h[1]=Math.max(h[1],r),d=!0,f/(r-t)>.5))return}if(d||a.push([t,r]),this.config.renderTextTracksNatively){var g=this.captionsTracks[e];this.Cues.newCue(g,t,r,i)}else{var v=this.Cues.newCue(null,t,r,i);this.hls.trigger(n.Events.CUES_PARSED,{type:"captions",cues:v,track:e})}},e.onInitPtsFound=function onInitPtsFound(e,t){var r=this,i=t.frag,a=t.id,s=t.initPTS,o=t.timescale,l=this.unparsedVttFrags;"main"===a&&(this.initPTS[i.cc]=s,this.timescale[i.cc]=o),l.length&&(this.unparsedVttFrags=[],l.forEach((function(e){r.onFragLoaded(n.Events.FRAG_LOADED,e)})))},e.getExistingTrack=function getExistingTrack(e){var t=this.media;if(t)for(var r=0;r<t.textTracks.length;r++){var i=t.textTracks[r];if(i[e])return i}return null},e.createCaptionsTrack=function createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)},e.createNativeTrack=function createNativeTrack(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,i=this.media,n=t[e],a=n.label,s=n.languageCode,o=this.getExistingTrack(e);if(o)r[e]=o,Object(l.clearCurrentCues)(r[e]),Object(l.sendAddTrackEvent)(r[e],i);else{var u=this.createTextTrack("captions",a,s);u&&(u[e]=!0,r[e]=u)}}},e.createNonNativeTrack=function createNonNativeTrack(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(n.Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}},e.createTextTrack=function createTextTrack(e,t,r){var i=this.media;if(i)return i.addTextTrack(e,t,r)},e.onMediaAttaching=function onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()},e.onMediaDetaching=function onMediaDetaching(){var e=this.captionsTracks;Object.keys(e).forEach((function(t){Object(l.clearCurrentCues)(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}},e.onManifestLoading=function onManifestLoading(){this.lastSn=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!1}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=this.unparsedVttFrags||[],this.initPTS=[],this.timescale=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},e._cleanTracks=function _cleanTracks(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var r=0;r<t.length;r++)Object(l.clearCurrentCues)(t[r])}},e.onSubtitleTracksUpdated=function onSubtitleTracksUpdated(e,t){var r=this;this.textTracks=[];var i=t.subtitleTracks||[],a=i.some((function(e){return e.textCodec===u.IMSC1_CODEC}));if(this.config.enableWebVTT||a&&this.config.enableIMSC1){var s=this.tracks&&i&&this.tracks.length===i.length;if(this.tracks=i||[],this.config.renderTextTracksNatively){var o=this.media?this.media.textTracks:[];this.tracks.forEach((function(e,t){var i;if(t<o.length){for(var n=null,a=0;a<o.length;a++)if(canReuseVttTextTrack(o[a],e)){n=o[a];break}n&&(i=n)}i?Object(l.clearCurrentCues)(i):(i=r.createTextTrack("subtitles",e.name,e.lang))&&(i.mode="disabled"),i&&(i.groupId=e.groupId,r.textTracks.push(i))}))}else if(!s&&this.tracks&&this.tracks.length){var d=this.tracks.map((function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}}));this.hls.trigger(n.Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:d})}}},e.onManifestLoaded=function onManifestLoaded(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var i="textTrack"+t[1],n=r.captionsProperties[i];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}}))},e.onFragLoading=function onFragLoading(e,t){var r=this.cea608Parser1,i=this.cea608Parser2,n=this.lastSn;if(this.enabled&&r&&i&&t.frag.type===d.PlaylistLevelType.MAIN){var a=t.frag.sn;a!==n+1&&(r.reset(),i.reset()),this.lastSn=a}},e.onFragLoaded=function onFragLoaded(e,t){var r=t.frag,a=t.payload,s=this.initPTS,o=this.unparsedVttFrags;if(r.type===d.PlaylistLevelType.SUBTITLE)if(a.byteLength){if(!Object(i.isFiniteNumber)(s[r.cc]))return o.push(t),void(s.length&&this.hls.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Missing initial subtitle PTS")}));var l=r.decryptdata;if(null==l||null==l.key||"AES-128"!==l.method){var c=this.tracks[r.level],h=this.vttCCs;h[r.cc]||(h[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),c&&c.textCodec===u.IMSC1_CODEC?this._parseIMSC1(r,a):this._parseVTTs(r,a,h)}}else this.hls.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})},e._parseIMSC1=function _parseIMSC1(e,t){var r=this,i=this.hls;Object(u.parseIMSC1)(t,this.initPTS[e.cc],this.timescale[e.cc],(function(t){r._appendCues(t,e.level),i.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(function(t){c.logger.log("Failed to parse IMSC1: "+t),i.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))},e._parseVTTs=function _parseVTTs(e,t,r){var i=this,a=this.hls;Object(o.parseWebVTT)(t,this.initPTS[e.cc],this.timescale[e.cc],r,e.cc,e.start,(function(t){i._appendCues(t,e.level),a.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(function(r){i._fallbackToIMSC1(e,t),c.logger.log("Failed to parse VTT cue: "+r),a.trigger(n.Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})}))},e._fallbackToIMSC1=function _fallbackToIMSC1(e,t){var r=this,i=this.tracks[e.level];i.textCodec||Object(u.parseIMSC1)(t,this.initPTS[e.cc],this.timescale[e.cc],(function(){i.textCodec=u.IMSC1_CODEC,r._parseIMSC1(e,t)}),(function(){i.textCodec="wvtt"}))},e._appendCues=function _appendCues(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[t];if("disabled"===i.mode)return;e.forEach((function(e){return Object(l.addCueToTrack)(i,e)}))}else{var a=this.tracks[t].default?"default":"subtitles"+t;r.trigger(n.Events.CUES_PARSED,{type:"subtitles",cues:e,track:a})}},e.onFragDecrypted=function onFragDecrypted(e,t){var r=t.frag;if(r.type===d.PlaylistLevelType.SUBTITLE){if(!Object(i.isFiniteNumber)(this.initPTS[r.cc]))return void this.unparsedVttFrags.push(t);this.onFragLoaded(n.Events.FRAG_LOADED,t)}},e.onSubtitleTracksCleared=function onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}},e.onFragParsingUserdata=function onFragParsingUserdata(e,t){var r=this.cea608Parser1,i=this.cea608Parser2;if(this.enabled&&r&&i)for(var n=0;n<t.samples.length;n++){var a=t.samples[n].bytes;if(a){var s=this.extractCea608Data(a);r.addData(t.samples[n].pts,s[0]),i.addData(t.samples[n].pts,s[1])}}},e.onBufferFlushing=function onBufferFlushing(e,t){var r=t.startOffset,i=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<i)){if(!a||"video"===a){var o=this.captionsTracks;Object.keys(o).forEach((function(e){return Object(l.removeCuesInRange)(o[e],r,i)}))}if(this.config.renderTextTracksNatively&&0===r&&void 0!==n){var u=this.textTracks;Object.keys(u).forEach((function(e){return Object(l.removeCuesInRange)(u[e],r,n)}))}}},e.extractCea608Data=function extractCea608Data(e){for(var t=31&e[0],r=2,i=[[],[]],n=0;n<t;n++){var a=e[r++],s=127&e[r++],o=127&e[r++],l=3&a;0===s&&0===o||0!=(4&a)&&(0!==l&&1!==l||(i[l].push(s),i[l].push(o)))}return i},TimelineController}();function canReuseVttTextTrack(e,t){return e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}},"./src/crypt/aes-crypto.ts":
102
- /*!*********************************!*\
103
- !*** ./src/crypt/aes-crypto.ts ***!
104
- \*********************************/
105
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return i}));var i=function(){function AESCrypto(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}return AESCrypto.prototype.decrypt=function decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},AESCrypto}()},"./src/crypt/aes-decryptor.ts":
106
- /*!************************************!*\
107
- !*** ./src/crypt/aes-decryptor.ts ***!
108
- \************************************/
109
- /*! exports provided: removePadding, default */function(e,t,r){"use strict";r.r(t),r.d(t,"removePadding",(function(){return removePadding})),r.d(t,"default",(function(){return n}));var i=r(/*! ../utils/typed-array */"./src/utils/typed-array.ts");function removePadding(e){var t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?Object(i.sliceUint8)(e,0,t-r):e}var n=function(){function AESDecryptor(){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.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}var e=AESDecryptor.prototype;return e.uint8ArrayToUint32Array_=function uint8ArrayToUint32Array_(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},e.initTable=function initTable(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],d=o[2],c=o[3],h=new Uint32Array(256),f=0,g=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 p=g^g<<1^g<<2^g<<3^g<<4;p=p>>>8^255&p^99,e[f]=p,t[p]=f;var m=h[f],y=h[m],E=h[y],T=257*h[p]^16843008*p;i[f]=T<<24|T>>>8,n[f]=T<<16|T>>>16,a[f]=T<<8|T>>>24,s[f]=T,T=16843009*E^65537*y^257*m^16843008*f,l[p]=T<<24|T>>>8,u[p]=T<<16|T>>>16,d[p]=T<<8|T>>>24,c[p]=T,f?(f=m^h[h[h[E^m]]],g^=h[h[g]]):f=g=1}},e.expandKey=function expandKey(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var a,s,o,l,u=this.ksRows=4*(n+6+1),d=this.keySchedule=new Uint32Array(u),c=this.invKeySchedule=new Uint32Array(u),h=this.sBox,f=this.rcon,g=this.invSubMix,v=g[0],p=g[1],m=g[2],y=g[3];for(a=0;a<u;a++)a<n?o=d[a]=t[a]:(l=o,a%n==0?(l=h[(l=l<<8|l>>>24)>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l],l^=f[a/n|0]<<24):n>6&&a%n==4&&(l=h[l>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l]),d[a]=o=(d[a-n]^l)>>>0);for(s=0;s<u;s++)a=u-s,l=3&s?d[a]:d[a-4],c[s]=s<4||a<=4?l:v[h[l>>>24]]^p[h[l>>>16&255]]^m[h[l>>>8&255]]^y[h[255&l]],c[s]=c[s]>>>0}},e.networkToHostOrderSwap=function networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24},e.decrypt=function decrypt(e,t,r){for(var i,n,a,s,o,l,u,d,c,h,f,g,v,p,m=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,T=this.invSubMix,S=T[0],b=T[1],L=T[2],A=T[3],_=this.uint8ArrayToUint32Array_(r),D=_[0],k=_[1],C=_[2],R=_[3],P=new Int32Array(e),I=new Int32Array(P.length),x=this.networkToHostOrderSwap;t<P.length;){for(c=x(P[t]),h=x(P[t+1]),f=x(P[t+2]),g=x(P[t+3]),o=c^y[0],l=g^y[1],u=f^y[2],d=h^y[3],v=4,p=1;p<m;p++)i=S[o>>>24]^b[l>>16&255]^L[u>>8&255]^A[255&d]^y[v],n=S[l>>>24]^b[u>>16&255]^L[d>>8&255]^A[255&o]^y[v+1],a=S[u>>>24]^b[d>>16&255]^L[o>>8&255]^A[255&l]^y[v+2],s=S[d>>>24]^b[o>>16&255]^L[l>>8&255]^A[255&u]^y[v+3],o=i,l=n,u=a,d=s,v+=4;i=E[o>>>24]<<24^E[l>>16&255]<<16^E[u>>8&255]<<8^E[255&d]^y[v],n=E[l>>>24]<<24^E[u>>16&255]<<16^E[d>>8&255]<<8^E[255&o]^y[v+1],a=E[u>>>24]<<24^E[d>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[v+2],s=E[d>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&u]^y[v+3],I[t]=x(i^D),I[t+1]=x(s^k),I[t+2]=x(a^C),I[t+3]=x(n^R),D=c,k=h,C=f,R=g,t+=4}return I.buffer},AESDecryptor}()},"./src/crypt/decrypter.ts":
110
- /*!********************************!*\
111
- !*** ./src/crypt/decrypter.ts ***!
112
- \********************************/
113
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return u}));var i=r(/*! ./aes-crypto */"./src/crypt/aes-crypto.ts"),n=r(/*! ./fast-aes-key */"./src/crypt/fast-aes-key.ts"),a=r(/*! ./aes-decryptor */"./src/crypt/aes-decryptor.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),l=r(/*! ../utils/typed-array */"./src/utils/typed-array.ts"),u=function(){function Decrypter(e,t,r){var i=(void 0===r?{}:r).removePKCS7Padding,n=void 0===i||i;if(this.logEnabled=!0,this.observer=void 0,this.config=void 0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.observer=e,this.config=t,this.removePKCS7Padding=n,n)try{var a=self.crypto;a&&(this.subtle=a.subtle||a.webkitSubtle)}catch(e){}null===this.subtle&&(this.config.enableSoftwareAES=!0)}var e=Decrypter.prototype;return e.destroy=function destroy(){this.observer=null},e.isSync=function isSync(){return this.config.enableSoftwareAES},e.flush=function flush(){var e=this.currentResult;if(e){var t=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Object(a.removePadding)(t):t}this.reset()},e.reset=function reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},e.decrypt=function decrypt(e,t,r,i){if(this.config.enableSoftwareAES){this.softwareDecrypt(new Uint8Array(e),t,r);var n=this.flush();n&&i(n.buffer)}else this.webCryptoDecrypt(new Uint8Array(e),t,r).then(i)},e.softwareDecrypt=function softwareDecrypt(e,t,r){var i=this.currentIV,n=this.currentResult,s=this.remainderData;this.logOnce("JS AES decrypt"),s&&(e=Object(o.appendUint8Array)(s,e),this.remainderData=null);var u=this.getValidChunk(e);if(!u.length)return null;i&&(r=i);var d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new a.default),d.expandKey(t);var c=n;return this.currentResult=d.decrypt(u.buffer,0,r),this.currentIV=Object(l.sliceUint8)(u,-16).buffer,c||null},e.webCryptoDecrypt=function webCryptoDecrypt(e,t,r){var a=this,s=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new n.default(s,t)),this.fastAesKey.expandKey().then((function(t){return s?new i.default(s,r).decrypt(e.buffer,t):Promise.reject(new Error("web crypto not initialized"))})).catch((function(i){return a.onWebCryptoError(i,e,t,r)}))},e.onWebCryptoError=function onWebCryptoError(e,t,r,i){return s.logger.warn("[decrypter.ts]: WebCrypto Error, disable WebCrypto API:",e),this.config.enableSoftwareAES=!0,this.logEnabled=!0,this.softwareDecrypt(t,r,i)},e.getValidChunk=function getValidChunk(e){var t=e,r=e.length-e.length%16;return r!==e.length&&(t=Object(l.sliceUint8)(e,0,r),this.remainderData=Object(l.sliceUint8)(e,r)),t},e.logOnce=function logOnce(e){this.logEnabled&&(s.logger.log("[decrypter.ts]: "+e),this.logEnabled=!1)},Decrypter}()},"./src/crypt/fast-aes-key.ts":
114
- /*!***********************************!*\
115
- !*** ./src/crypt/fast-aes-key.ts ***!
116
- \***********************************/
117
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return i}));var i=function(){function FastAESKey(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}return FastAESKey.prototype.expandKey=function expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},FastAESKey}()},"./src/demux/aacdemuxer.ts":
118
- /*!*********************************!*\
119
- !*** ./src/demux/aacdemuxer.ts ***!
120
- \*********************************/
121
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ./base-audio-demuxer */"./src/demux/base-audio-demuxer.ts"),n=r(/*! ./adts */"./src/demux/adts.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),s=r(/*! ../demux/id3 */"./src/demux/id3.ts");function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var o=function(e){function AACDemuxer(t,r){var i;return(i=e.call(this)||this).observer=void 0,i.config=void 0,i.observer=t,i.config=r,i}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(AACDemuxer,e);var t=AACDemuxer.prototype;return t.resetInitSegment=function resetInitSegment(t,r,i){e.prototype.resetInitSegment.call(this,t,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:0,pid:-1,sequenceNumber:0,isAAC:!0,samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}},AACDemuxer.probe=function probe(e){if(!e)return!1;for(var t=(s.getID3Data(e,0)||[]).length,r=e.length;t<r;t++)if(n.probe(e,t))return a.logger.log("ADTS sync word found !"),!0;return!1},t.canParse=function canParse(e,t){return n.canParse(e,t)},t.appendFrame=function appendFrame(e,t,r){n.initTrackConfig(e,this.observer,t,r,e.manifestCodec);var i=n.appendFrame(e,t,r,this.initPTS,this.frameIndex);if(i&&0===i.missing)return i},AACDemuxer}(i.default);o.minProbeByteLength=9,t.default=o},"./src/demux/adts.ts":
122
- /*!***************************!*\
123
- !*** ./src/demux/adts.ts ***!
124
- \***************************/
125
- /*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */function(e,t,r){"use strict";r.r(t),r.d(t,"getAudioConfig",(function(){return getAudioConfig})),r.d(t,"isHeaderPattern",(function(){return isHeaderPattern})),r.d(t,"getHeaderLength",(function(){return getHeaderLength})),r.d(t,"getFullFrameLength",(function(){return getFullFrameLength})),r.d(t,"canGetFrameLength",(function(){return canGetFrameLength})),r.d(t,"isHeader",(function(){return isHeader})),r.d(t,"canParse",(function(){return canParse})),r.d(t,"probe",(function(){return probe})),r.d(t,"initTrackConfig",(function(){return initTrackConfig})),r.d(t,"getFrameDuration",(function(){return getFrameDuration})),r.d(t,"parseFrameHeader",(function(){return parseFrameHeader})),r.d(t,"appendFrame",(function(){return appendFrame}));var i=r(/*! ../utils/logger */"./src/utils/logger.ts"),n=r(/*! ../errors */"./src/errors.ts"),a=r(/*! ../events */"./src/events.ts");function getAudioConfig(e,t,r,s){var o,l,u,d,c=navigator.userAgent.toLowerCase(),h=s,f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];o=1+((192&t[r+2])>>>6);var g=(60&t[r+2])>>>2;if(!(g>f.length-1))return u=(1&t[r+2])<<2,u|=(192&t[r+3])>>>6,i.logger.log("manifest codec:"+s+", ADTS type:"+o+", samplingIndex:"+g),/firefox/i.test(c)?g>=6?(o=5,d=new Array(4),l=g-3):(o=2,d=new Array(2),l=g):-1!==c.indexOf("android")?(o=2,d=new Array(2),l=g):(o=5,d=new Array(4),s&&(-1!==s.indexOf("mp4a.40.29")||-1!==s.indexOf("mp4a.40.5"))||!s&&g>=6?l=g-3:((s&&-1!==s.indexOf("mp4a.40.2")&&(g>=6&&1===u||/vivaldi/i.test(c))||!s&&1===u)&&(o=2,d=new Array(2)),l=g)),d[0]=o<<3,d[0]|=(14&g)>>1,d[1]|=(1&g)<<7,d[1]|=u<<3,5===o&&(d[1]|=(14&l)>>1,d[2]=(1&l)<<7,d[2]|=8,d[3]=0),{config:d,samplerate:f[g],channelCount:u,codec:"mp4a.40."+o,manifestCodec:h};e.trigger(a.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+g})}function isHeaderPattern(e,t){return 255===e[t]&&240==(246&e[t+1])}function getHeaderLength(e,t){return 1&e[t+1]?7:9}function getFullFrameLength(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function canGetFrameLength(e,t){return t+5<e.length}function isHeader(e,t){return t+1<e.length&&isHeaderPattern(e,t)}function canParse(e,t){return canGetFrameLength(e,t)&&isHeaderPattern(e,t)&&getFullFrameLength(e,t)<=e.length-t}function probe(e,t){if(isHeader(e,t)){var r=getHeaderLength(e,t);if(t+r>=e.length)return!1;var i=getFullFrameLength(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||isHeader(e,n)}return!1}function initTrackConfig(e,t,r,n,a){if(!e.samplerate){var s=getAudioConfig(t,r,n,a);if(!s)return;e.config=s.config,e.samplerate=s.samplerate,e.channelCount=s.channelCount,e.codec=s.codec,e.manifestCodec=s.manifestCodec,i.logger.log("parsed codec:"+e.codec+", rate:"+s.samplerate+", channels:"+s.channelCount)}}function getFrameDuration(e){return 9216e4/e}function parseFrameHeader(e,t,r,i,n){var a=getHeaderLength(e,t),s=getFullFrameLength(e,t);if((s-=a)>0)return{headerLength:a,frameLength:s,stamp:r+i*n}}function appendFrame(e,t,r,i,n){var a=parseFrameHeader(t,r,i,n,getFrameDuration(e.samplerate));if(a){var s,o=a.frameLength,l=a.headerLength,u=a.stamp,d=l+o,c=Math.max(0,r+d-t.length);c?(s=new Uint8Array(d-l)).set(t.subarray(r+l,t.length),0):s=t.subarray(r+l,r+d);var h={unit:s,pts:u};return c||e.samples.push(h),{sample:h,length:d,missing:c}}}},"./src/demux/base-audio-demuxer.ts":
126
- /*!*****************************************!*\
127
- !*** ./src/demux/base-audio-demuxer.ts ***!
128
- \*****************************************/
129
- /*! exports provided: initPTSFn, default */function(e,t,r){"use strict";r.r(t),r.d(t,"initPTSFn",(function(){return u}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../demux/id3 */"./src/demux/id3.ts"),a=r(/*! ./dummy-demuxed-track */"./src/demux/dummy-demuxed-track.ts"),s=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),o=r(/*! ../utils/typed-array */"./src/utils/typed-array.ts"),l=function(){function BaseAudioDemuxer(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.initPTS=null}var e=BaseAudioDemuxer.prototype;return e.resetInitSegment=function resetInitSegment(e,t,r){this._id3Track={type:"id3",id:0,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function resetTimeStamp(){},e.resetContiguity=function resetContiguity(){},e.canParse=function canParse(e,t){return!1},e.appendFrame=function appendFrame(e,t,r){},e.demux=function demux(e,t){this.cachedData&&(e=Object(s.appendUint8Array)(this.cachedData,e),this.cachedData=null);var r,i,l=n.getID3Data(e,0),d=l?l.length:0,c=this._audioTrack,h=this._id3Track,f=l?n.getTimeStamp(l):void 0,g=e.length;for(0!==this.frameIndex&&null!==this.initPTS||(this.initPTS=u(f,t)),l&&l.length>0&&h.samples.push({pts:this.initPTS,dts:this.initPTS,data:l}),i=this.initPTS;d<g;){if(this.canParse(e,d)){var v=this.appendFrame(c,e,d);v?(this.frameIndex++,i=v.sample.pts,r=d+=v.length):d=g}else n.canParse(e,d)?(l=n.getID3Data(e,d),h.samples.push({pts:i,dts:i,data:l}),r=d+=l.length):d++;if(d===g&&r!==g){var p=Object(o.sliceUint8)(e,r);this.cachedData?this.cachedData=Object(s.appendUint8Array)(this.cachedData,p):this.cachedData=p}}return{audioTrack:c,avcTrack:Object(a.dummyTrack)(),id3Track:h,textTrack:Object(a.dummyTrack)()}},e.demuxSampleAes=function demuxSampleAes(e,t,r){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},e.flush=function flush(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),this.frameIndex=0,{audioTrack:this._audioTrack,avcTrack:Object(a.dummyTrack)(),id3Track:this._id3Track,textTrack:Object(a.dummyTrack)()}},e.destroy=function destroy(){},BaseAudioDemuxer}(),u=function initPTSFn(e,t){return Object(i.isFiniteNumber)(e)?90*e:9e4*t};t.default=l},"./src/demux/chunk-cache.ts":
130
- /*!**********************************!*\
131
- !*** ./src/demux/chunk-cache.ts ***!
132
- \**********************************/
133
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return i}));var i=function(){function ChunkCache(){this.chunks=[],this.dataLength=0}var e=ChunkCache.prototype;return e.push=function push(e){this.chunks.push(e),this.dataLength+=e.length},e.flush=function flush(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function concatUint8Arrays(e,t){for(var r=new Uint8Array(t),i=0,n=0;n<e.length;n++){var a=e[n];r.set(a,i),i+=a.length}return r}(t,r),this.reset(),e):new Uint8Array(0)},e.reset=function reset(){this.chunks.length=0,this.dataLength=0},ChunkCache}()},"./src/demux/dummy-demuxed-track.ts":
134
- /*!******************************************!*\
135
- !*** ./src/demux/dummy-demuxed-track.ts ***!
136
- \******************************************/
137
- /*! exports provided: dummyTrack */function(e,t,r){"use strict";function dummyTrack(){return{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}r.r(t),r.d(t,"dummyTrack",(function(){return dummyTrack}))},"./src/demux/exp-golomb.ts":
138
- /*!*********************************!*\
139
- !*** ./src/demux/exp-golomb.ts ***!
140
- \*********************************/
141
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../utils/logger */"./src/utils/logger.ts"),n=function(){function ExpGolomb(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var e=ExpGolomb.prototype;return e.loadWord=function loadWord(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},e.skipBits=function skipBits(e){var t;this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},e.readBits=function readBits(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&i.logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0?this.word<<=t:this.bytesAvailable>0&&this.loadWord(),(t=e-t)>0&&this.bitsAvailable?r<<t|this.readBits(t):r},e.skipLZ=function skipLZ(){var e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},e.skipUEG=function skipUEG(){this.skipBits(1+this.skipLZ())},e.skipEG=function skipEG(){this.skipBits(1+this.skipLZ())},e.readUEG=function readUEG(){var e=this.skipLZ();return this.readBits(e+1)-1},e.readEG=function readEG(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},e.readBoolean=function readBoolean(){return 1===this.readBits(1)},e.readUByte=function readUByte(){return this.readBits(8)},e.readUShort=function readUShort(){return this.readBits(16)},e.readUInt=function readUInt(){return this.readBits(32)},e.skipScalingList=function skipScalingList(e){for(var t=8,r=8,i=0;i<e;i++)0!==r&&(r=(t+this.readEG()+256)%256),t=0===r?t:r},e.readSPS=function readSPS(){var e,t,r,i=0,n=0,a=0,s=0,o=this.readUByte.bind(this),l=this.readBits.bind(this),u=this.readUEG.bind(this),d=this.readBoolean.bind(this),c=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();var v=o();if(l(5),c(3),o(),f(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){var p=u();if(3===p&&c(1),f(),f(),c(1),d())for(t=3!==p?8:12,r=0;r<t;r++)d()&&g(r<6?16:64)}f();var m=u();if(0===m)u();else if(1===m)for(c(1),h(),h(),e=u(),r=0;r<e;r++)h();f(),c(1);var y=u(),E=u(),T=l(1);0===T&&c(1),c(1),d()&&(i=u(),n=u(),a=u(),s=u());var S=[1,1];if(d()&&d())switch(o()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[o()<<8|o(),o()<<8|o()]}return{width:Math.ceil(16*(y+1)-2*i-2*n),height:(2-T)*(E+1)*16-(T?2:4)*(a+s),pixelRatio:S}},e.readSliceType=function readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()},ExpGolomb}();t.default=n},"./src/demux/id3.ts":
142
- /*!**************************!*\
143
- !*** ./src/demux/id3.ts ***!
144
- \**************************/
145
- /*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */function(e,t,r){"use strict";r.r(t),r.d(t,"isHeader",(function(){return n})),r.d(t,"isFooter",(function(){return a})),r.d(t,"getID3Data",(function(){return s})),r.d(t,"canParse",(function(){return l})),r.d(t,"getTimeStamp",(function(){return u})),r.d(t,"isTimeStampFrame",(function(){return d})),r.d(t,"getID3Frames",(function(){return h})),r.d(t,"decodeFrame",(function(){return f})),r.d(t,"utf8ArrayToStr",(function(){return y})),r.d(t,"testables",(function(){return E}));var i,n=function isHeader(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},a=function isFooter(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128},s=function getID3Data(e,t){for(var r=t,i=0;n(e,t);){i+=10,i+=o(e,t+6),a(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(r,r+i)},o=function readSize(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]},l=function canParse(e,t){return n(e,t)&&o(e,t+6)+10<=e.length-t},u=function getTimeStamp(e){for(var t=h(e),r=0;r<t.length;r++){var i=t[r];if(d(i))return m(i)}},d=function isTimeStampFrame(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info},c=function getFrameData(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=o(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}},h=function getID3Frames(e){for(var t=0,r=[];n(e,t);){for(var i=o(e,t+6),s=(t+=10)+i;t+8<s;){var l=c(e.subarray(t)),u=f(l);u&&r.push(u),t+=l.size+10}a(e,t)&&(t+=10)}return r},f=function decodeFrame(e){return"PRIV"===e.type?g(e):"W"===e.type[0]?p(e):v(e)},g=function decodePrivFrame(e){if(!(e.size<2)){var t=y(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}},v=function decodeTextFrame(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=y(e.data.subarray(t),!0);t+=r.length+1;var i=y(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=y(e.data.subarray(1));return{key:e.type,data:n}}},p=function decodeURLFrame(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=y(e.data.subarray(t),!0);t+=r.length+1;var i=y(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=y(e.data);return{key:e.type,data:n}},m=function readTimeStamp(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}},y=function utf8ArrayToStr(e,t){void 0===t&&(t=!1);var r=getTextDecoder();if(r){var i=r.decode(e);if(t){var n=i.indexOf("\0");return-1!==n?i.substring(0,n):i}return i.replace(/\0/g,"")}for(var a,s,o,l=e.length,u="",d=0;d<l;){if(0===(a=e[d++])&&t)return u;if(0!==a&&3!==a)switch(a>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(a);break;case 12:case 13:s=e[d++],u+=String.fromCharCode((31&a)<<6|63&s);break;case 14:s=e[d++],o=e[d++],u+=String.fromCharCode((15&a)<<12|(63&s)<<6|(63&o)<<0)}}return u},E={decodeTextFrame:v};function getTextDecoder(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},"./src/demux/mp3demuxer.ts":
146
- /*!*********************************!*\
147
- !*** ./src/demux/mp3demuxer.ts ***!
148
- \*********************************/
149
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ./base-audio-demuxer */"./src/demux/base-audio-demuxer.ts"),n=r(/*! ../demux/id3 */"./src/demux/id3.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),s=r(/*! ./mpegaudio */"./src/demux/mpegaudio.ts");function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}var o=function(e){function MP3Demuxer(){return e.apply(this,arguments)||this}!function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(MP3Demuxer,e);var t=MP3Demuxer.prototype;return t.resetInitSegment=function resetInitSegment(t,r,i){e.prototype.resetInitSegment.call(this,t,r,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:0,pid:-1,sequenceNumber:0,isAAC:!1,samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}},MP3Demuxer.probe=function probe(e){if(!e)return!1;for(var t=(n.getID3Data(e,0)||[]).length,r=e.length;t<r;t++)if(s.probe(e,t))return a.logger.log("MPEG Audio sync word found !"),!0;return!1},t.canParse=function canParse(e,t){return s.canParse(e,t)},t.appendFrame=function appendFrame(e,t,r){if(null!==this.initPTS)return s.appendFrame(e,t,r,this.initPTS,this.frameIndex)},MP3Demuxer}(i.default);o.minProbeByteLength=4,t.default=o},"./src/demux/mp4demuxer.ts":
150
- /*!*********************************!*\
151
- !*** ./src/demux/mp4demuxer.ts ***!
152
- \*********************************/
153
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),n=r(/*! ./dummy-demuxed-track */"./src/demux/dummy-demuxed-track.ts"),a=function(){function MP4Demuxer(e,t){this.remainderData=null,this.config=void 0,this.config=t}var e=MP4Demuxer.prototype;return e.resetTimeStamp=function resetTimeStamp(){},e.resetInitSegment=function resetInitSegment(){},e.resetContiguity=function resetContiguity(){},MP4Demuxer.probe=function probe(e){return Object(i.findBox)({data:e,start:0,end:Math.min(e.length,16384)},["moof"]).length>0},e.demux=function demux(e){var t=e,r=Object(n.dummyTrack)();if(this.config.progressive){this.remainderData&&(t=Object(i.appendUint8Array)(this.remainderData,e));var a=Object(i.segmentValidRange)(t);this.remainderData=a.remainder,r.samples=a.valid||new Uint8Array}else r.samples=t;return{audioTrack:Object(n.dummyTrack)(),avcTrack:r,id3Track:Object(n.dummyTrack)(),textTrack:Object(n.dummyTrack)()}},e.flush=function flush(){var e=Object(n.dummyTrack)();return e.samples=this.remainderData||new Uint8Array,this.remainderData=null,{audioTrack:Object(n.dummyTrack)(),avcTrack:e,id3Track:Object(n.dummyTrack)(),textTrack:Object(n.dummyTrack)()}},e.demuxSampleAes=function demuxSampleAes(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function destroy(){},MP4Demuxer}();a.minProbeByteLength=1024,t.default=a},"./src/demux/mpegaudio.ts":
154
- /*!********************************!*\
155
- !*** ./src/demux/mpegaudio.ts ***!
156
- \********************************/
157
- /*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */function(e,t,r){"use strict";r.r(t),r.d(t,"appendFrame",(function(){return appendFrame})),r.d(t,"parseHeader",(function(){return parseHeader})),r.d(t,"isHeaderPattern",(function(){return isHeaderPattern})),r.d(t,"isHeader",(function(){return isHeader})),r.d(t,"canParse",(function(){return canParse})),r.d(t,"probe",(function(){return probe}));var i=null,n=[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],a=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],s=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],o=[0,1,1,4];function appendFrame(e,t,r,i,n){if(!(r+24>t.length)){var a=parseHeader(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function parseHeader(e,t){var r=e[t+1]>>3&3,l=e[t+1]>>1&3,u=e[t+2]>>4&15,d=e[t+2]>>2&3;if(1!==r&&0!==u&&15!==u&&3!==d){var c=e[t+2]>>1&1,h=e[t+3]>>6,f=1e3*n[14*(3===r?3-l:3===l?3:4)+u-1],g=a[3*(3===r?0:2===r?1:2)+d],v=3===h?1:2,p=s[r][l],m=o[l],y=8*p*m,E=Math.floor(p*f/g+c)*m;if(null===i){var T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);i=T?parseInt(T[1]):0}return!!i&&i<=87&&2===l&&f>=224e3&&0===h&&(e[t+3]=128|e[t+3]),{sampleRate:g,channelCount:v,frameLength:E,samplesPerFrame:y}}}function isHeaderPattern(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function isHeader(e,t){return t+1<e.length&&isHeaderPattern(e,t)}function canParse(e,t){return isHeaderPattern(e,t)&&4<=e.length-t}function probe(e,t){if(t+1<e.length&&isHeaderPattern(e,t)){var r=parseHeader(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var n=t+i;return n===e.length||isHeader(e,n)}return!1}},"./src/demux/sample-aes.ts":
158
- /*!*********************************!*\
159
- !*** ./src/demux/sample-aes.ts ***!
160
- \*********************************/
161
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../crypt/decrypter */"./src/crypt/decrypter.ts"),n=r(/*! ./tsdemuxer */"./src/demux/tsdemuxer.ts"),a=function(){function SampleAesDecrypter(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new i.default(e,t,{removePKCS7Padding:!1})}var e=SampleAesDecrypter.prototype;return e.decryptBuffer=function decryptBuffer(e,t){this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,t)},e.decryptAacSample=function decryptAacSample(e,t,r,i){var n=e[t].unit,a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length),o=this;this.decryptBuffer(s,(function(a){var s=new Uint8Array(a);n.set(s,16),i||o.decryptAacSamples(e,t+1,r)}))},e.decryptAacSamples=function decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}},e.getAvcEncryptedData=function getAvcEncryptedData(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<=e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r},e.getAvcDecryptedUnit=function getAvcDecryptedUnit(e,t){for(var r=new Uint8Array(t),i=0,n=32;n<=e.length-16;n+=160,i+=16)e.set(r.subarray(i,i+16),n);return e},e.decryptAvcSample=function decryptAvcSample(e,t,r,i,a,s){var o=Object(n.discardEPB)(a.data),l=this.getAvcEncryptedData(o),u=this;this.decryptBuffer(l.buffer,(function(n){a.data=u.getAvcDecryptedUnit(o,n),s||u.decryptAvcSamples(e,t,r+1,i)}))},e.decryptAvcSamples=function decryptAvcSamples(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,a,s),!s)return}}}},SampleAesDecrypter}();t.default=a},"./src/demux/transmuxer-interface.ts":
162
- /*!*******************************************!*\
163
- !*** ./src/demux/transmuxer-interface.ts ***!
164
- \*******************************************/
165
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return c}));var i=r(/*! webworkify-webpack */"./node_modules/webworkify-webpack/index.js"),n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../demux/transmuxer */"./src/demux/transmuxer.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ../errors */"./src/errors.ts"),l=r(/*! ../utils/mediasource-helper */"./src/utils/mediasource-helper.ts"),u=r(/*! eventemitter3 */"./node_modules/eventemitter3/index.js"),d=Object(l.getMediaSource)()||{isTypeSupported:function isTypeSupported(){return!1}},c=function(){function TransmuxerInterface(e,t,r,l){var c=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.hls=e,this.id=t,this.onTransmuxComplete=r,this.onFlush=l;var h=e.config,f=function forwardMessage(t,r){(r=r||{}).frag=c.frag,r.id=c.id,e.trigger(t,r)};this.observer=new u.EventEmitter,this.observer.on(n.Events.FRAG_DECRYPTED,f),this.observer.on(n.Events.ERROR,f);var g={mp4:d.isTypeSupported("video/mp4"),mpeg:d.isTypeSupported("audio/mpeg"),mp3:d.isTypeSupported('audio/mp4; codecs="mp3"')},v=navigator.vendor;if(h.enableWorker&&"undefined"!=typeof Worker){var p;s.logger.log("demuxing in webworker");try{p=this.worker=i(/*! ../demux/transmuxer-worker.ts */"./src/demux/transmuxer-worker.ts"),this.onwmsg=this.onWorkerMessage.bind(this),p.addEventListener("message",this.onwmsg),p.onerror=function(t){e.trigger(n.Events.ERROR,{type:o.ErrorTypes.OTHER_ERROR,details:o.ErrorDetails.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",error:new Error(t.message+" ("+t.filename+":"+t.lineno+")")})},p.postMessage({cmd:"init",typeSupported:g,vendor:v,id:t,config:JSON.stringify(h)})}catch(e){s.logger.warn("Error in worker:",e),s.logger.error("Error while initializing DemuxerWorker, fallback to inline"),p&&self.URL.revokeObjectURL(p.objectURL),this.transmuxer=new a.default(this.observer,g,h,v,t),this.worker=null}}else this.transmuxer=new a.default(this.observer,g,h,v,t)}var e=TransmuxerInterface.prototype;return e.destroy=function destroy(){var e=this.worker;if(e)e.removeEventListener("message",this.onwmsg),e.terminate(),this.worker=null;else{var t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.observer=null},e.push=function push(e,t,r,i,n,o,l,u,d,c){var h=this;d.transmuxing.start=self.performance.now();var f=this.transmuxer,g=this.worker,v=o?o.start:n.start,p=n.decryptdata,m=this.frag,y=!(m&&n.cc===m.cc),E=!(m&&d.level===m.level),T=m?d.sn-m.sn:-1,S=this.part?d.part-this.part.index:1,b=!E&&(1===T||0===T&&1===S),L=self.performance.now();(E||T||0===n.stats.parsing.start)&&(n.stats.parsing.start=L),!o||!S&&b||(o.stats.parsing.start=L);var A=new a.TransmuxState(y,b,u,E,v);if(!b||y){s.logger.log("[transmuxer-interface, "+n.type+"]: Starting new transmux session for sn: "+d.sn+" p: "+d.part+" level: "+d.level+" id: "+d.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+b+"\n accurateTimeOffset: "+u+"\n timeOffset: "+v);var _=new a.TransmuxConfig(r,i,t,l,c);this.configureTransmuxer(_)}if(this.frag=n,this.part=o,g)g.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:d,state:A},e instanceof ArrayBuffer?[e]:[]);else if(f){var D=f.push(e,p,d,A);Object(a.isPromise)(D)?D.then((function(e){h.handleTransmuxComplete(e)})):this.handleTransmuxComplete(D)}},e.flush=function flush(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:e});else if(r){var n=r.flush(e);Object(a.isPromise)(n)?n.then((function(r){t.handleFlushResult(r,e)})):this.handleFlushResult(n,e)}},e.handleFlushResult=function handleFlushResult(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},e.onWorkerMessage=function onWorkerMessage(e){var t=e.data,r=this.hls;switch(t.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}},e.configureTransmuxer=function configureTransmuxer(e){var t=this.worker,r=this.transmuxer;t?t.postMessage({cmd:"configure",config:e}):r&&r.configure(e)},e.handleTransmuxComplete=function handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},TransmuxerInterface}()},"./src/demux/transmuxer-worker.ts":
166
- /*!****************************************!*\
167
- !*** ./src/demux/transmuxer-worker.ts ***!
168
- \****************************************/
169
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return TransmuxerWorker}));var i=r(/*! ../demux/transmuxer */"./src/demux/transmuxer.ts"),n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),s=r(/*! eventemitter3 */"./node_modules/eventemitter3/index.js");function TransmuxerWorker(e){var t=new s.EventEmitter,r=function forwardMessage(t,r){e.postMessage({event:t,data:r})};t.on(n.Events.FRAG_DECRYPTED,r),t.on(n.Events.ERROR,r),e.addEventListener("message",(function(n){var s=n.data;switch(s.cmd){case"init":var o=JSON.parse(s.config);e.transmuxer=new i.default(t,s.typeSupported,o,s.vendor,s.id),Object(a.enableLogs)(o.debug),r("init",null);break;case"configure":e.transmuxer.configure(s.config);break;case"demux":var l=e.transmuxer.push(s.data,s.decryptdata,s.chunkMeta,s.state);Object(i.isPromise)(l)?l.then((function(t){emitTransmuxComplete(e,t)})):emitTransmuxComplete(e,l);break;case"flush":var u=s.chunkMeta,d=e.transmuxer.flush(u);Object(i.isPromise)(d)?d.then((function(t){handleFlushResult(e,t,u)})):handleFlushResult(e,d,u)}}))}function emitTransmuxComplete(e,t){if(!function isEmptyResult(e){return!(e.audio||e.video||e.text||e.id3||e.initSegment)}(t.remuxResult)){var r=[],i=t.remuxResult,n=i.audio,a=i.video;n&&addToTransferable(r,n),a&&addToTransferable(r,a),e.postMessage({event:"transmuxComplete",data:t},r)}}function addToTransferable(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function handleFlushResult(e,t,r){t.forEach((function(t){emitTransmuxComplete(e,t)})),e.postMessage({event:"flush",data:r})}},"./src/demux/transmuxer.ts":
170
- /*!*********************************!*\
171
- !*** ./src/demux/transmuxer.ts ***!
172
- \*********************************/
173
- /*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return y})),r.d(t,"isPromise",(function(){return isPromise})),r.d(t,"TransmuxConfig",(function(){return T})),r.d(t,"TransmuxState",(function(){return S}));var i,n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../errors */"./src/errors.ts"),s=r(/*! ../crypt/decrypter */"./src/crypt/decrypter.ts"),o=r(/*! ../demux/aacdemuxer */"./src/demux/aacdemuxer.ts"),l=r(/*! ../demux/mp4demuxer */"./src/demux/mp4demuxer.ts"),u=r(/*! ../demux/tsdemuxer */"./src/demux/tsdemuxer.ts"),d=r(/*! ../demux/mp3demuxer */"./src/demux/mp3demuxer.ts"),c=r(/*! ../remux/mp4-remuxer */"./src/remux/mp4-remuxer.ts"),h=r(/*! ../remux/passthrough-remuxer */"./src/remux/passthrough-remuxer.ts"),f=r(/*! ./chunk-cache */"./src/demux/chunk-cache.ts"),g=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),v=r(/*! ../utils/logger */"./src/utils/logger.ts");try{i=self.performance.now.bind(self.performance)}catch(e){v.logger.debug("Unable to use Performance API on this environment"),i=self.Date.now}var p=[{demux:u.default,remux:c.default},{demux:l.default,remux:h.default},{demux:o.default,remux:c.default},{demux:d.default,remux:c.default}],m=1024;p.forEach((function(e){var t=e.demux;m=Math.max(m,t.minProbeByteLength)}));var y=function(){function Transmuxer(e,t,r,i,n){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.cache=new f.default,this.observer=e,this.typeSupported=t,this.config=r,this.vendor=i,this.id=n}var e=Transmuxer.prototype;return e.configure=function configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},e.push=function push(e,t,r,n){var a=this,s=r.transmuxing;s.executeStart=i();var o=new Uint8Array(e),l=this.cache,u=this.config,d=this.currentTransmuxState,c=this.transmuxConfig;n&&(this.currentTransmuxState=n);var h=function getEncryptionType(e,t){var r=null;e.byteLength>0&&null!=t&&null!=t.key&&null!==t.iv&&null!=t.method&&(r=t);return r}(o,t);if(h&&"AES-128"===h.method){var f=this.getDecrypter();if(!u.enableSoftwareAES)return this.decryptionPromise=f.webCryptoDecrypt(o,h.key.buffer,h.iv.buffer).then((function(e){var t=a.push(e,null,r);return a.decryptionPromise=null,t})),this.decryptionPromise;var v=f.softwareDecrypt(o,h.key.buffer,h.iv.buffer);if(!v)return s.executeEnd=i(),E(r);o=new Uint8Array(v)}var p=n||d,m=p.contiguous,y=p.discontinuity,T=p.trackSwitch,S=p.accurateTimeOffset,b=p.timeOffset,L=c.audioCodec,A=c.videoCodec,_=c.defaultInitPts,D=c.duration,k=c.initSegmentData;if((y||T)&&this.resetInitSegment(k,L,A,D),y&&this.resetInitialTimestamp(_),m||this.resetContiguity(),this.needsProbing(o,y,T)){if(l.dataLength){var C=l.flush();o=Object(g.appendUint8Array)(C,o)}this.configureTransmuxer(o,c)}var R=this.transmux(o,h,b,S,r),P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,s.executeEnd=i(),R},e.flush=function flush(e){var t=this,r=e.transmuxing;r.executeStart=i();var s=this.decrypter,o=this.cache,l=this.currentTransmuxState,u=this.decryptionPromise;if(u)return u.then((function(){return t.flush(e)}));var d=[],c=l.timeOffset;if(s){var h=s.flush();h&&d.push(this.push(h,null,e))}var f=o.dataLength;o.reset();var g=this.demuxer,v=this.remuxer;if(!g||!v)return f>=m&&this.observer.emit(n.Events.ERROR,n.Events.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=i(),[E(e)];var p=g.flush(c);return isPromise(p)?p.then((function(r){return t.flushRemux(d,r,e),d})):(this.flushRemux(d,p,e),d)},e.flushRemux=function flushRemux(e,t,r){var n=t.audioTrack,a=t.avcTrack,s=t.id3Track,o=t.textTrack,l=this.currentTransmuxState,u=l.accurateTimeOffset,d=l.timeOffset;v.logger.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var c=this.remuxer.remux(n,a,s,o,d,u,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=i()},e.resetInitialTimestamp=function resetInitialTimestamp(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},e.resetContiguity=function resetContiguity(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},e.resetInitSegment=function resetInitSegment(e,t,r,i){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(t,r,i),a.resetInitSegment(e,t,r))},e.destroy=function destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function transmux(e,t,r,i,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)},e.transmuxUnencrypted=function transmuxUnencrypted(e,t,r,i){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),a=n.audioTrack,s=n.avcTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,t,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function transmuxSampleAes(e,t,r,i,n){var a=this;return this.demuxer.demuxSampleAes(e,t,r).then((function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.avcTrack,e.id3Track,e.textTrack,r,i,!1,a.id),chunkMeta:n}}))},e.configureTransmuxer=function configureTransmuxer(e,t){for(var r,i=this.config,n=this.observer,a=this.typeSupported,s=this.vendor,o=t.audioCodec,u=t.defaultInitPts,d=t.duration,c=t.initSegmentData,f=t.videoCodec,g=0,m=p.length;g<m;g++)if(p[g].demux.probe(e)){r=p[g];break}r||(v.logger.warn("Failed to find demuxer by probing frag, treating as mp4 passthrough"),r={demux:l.default,remux:h.default});var y=this.demuxer,E=this.remuxer,T=r.remux,S=r.demux;E&&E instanceof T||(this.remuxer=new T(n,i,a,s)),y&&y instanceof S||(this.demuxer=new S(n,i,a),this.probe=S.probe),this.resetInitSegment(c,o,f,d),this.resetInitialTimestamp(u)},e.needsProbing=function needsProbing(e,t,r){return!this.demuxer||!this.remuxer||t||r},e.getDecrypter=function getDecrypter(){var e=this.decrypter;return e||(e=this.decrypter=new s.default(this.observer,this.config)),e},Transmuxer}();var E=function emptyResult(e){return{remuxResult:{},chunkMeta:e}};function isPromise(e){return"then"in e&&e.then instanceof Function}var T=function TransmuxConfig(e,t,r,i,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=r,this.duration=i,this.defaultInitPts=n},S=function TransmuxState(e,t,r,i,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=r,this.trackSwitch=i,this.timeOffset=n}},"./src/demux/tsdemuxer.ts":
174
- /*!********************************!*\
175
- !*** ./src/demux/tsdemuxer.ts ***!
176
- \********************************/
177
- /*! exports provided: discardEPB, default */function(e,t,r){"use strict";r.r(t),r.d(t,"discardEPB",(function(){return discardEPB}));var i=r(/*! ./adts */"./src/demux/adts.ts"),n=r(/*! ./mpegaudio */"./src/demux/mpegaudio.ts"),a=r(/*! ./exp-golomb */"./src/demux/exp-golomb.ts"),s=r(/*! ./id3 */"./src/demux/id3.ts"),o=r(/*! ./sample-aes */"./src/demux/sample-aes.ts"),l=r(/*! ../events */"./src/events.ts"),u=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),d=r(/*! ../utils/logger */"./src/utils/logger.ts"),c=r(/*! ../errors */"./src/errors.ts"),h={video:1,audio:2,id3:3,text:4},f=function(){function TSDemuxer(e,t,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this.aacLastPTS=null,this._initPTS=null,this._initDTS=null,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=r}TSDemuxer.probe=function probe(e){var t=TSDemuxer.syncOffset(e);return!(t<0)&&(t&&d.logger.warn("MPEG2-TS detected but first sync word found @ offset "+t+", junk ahead ?"),!0)},TSDemuxer.syncOffset=function syncOffset(e){for(var t=Math.min(1e3,e.length-564),r=0;r<t;){if(71===e[r]&&71===e[r+188]&&71===e[r+376])return r;r++}return-1},TSDemuxer.createTrack=function createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:h[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var e=TSDemuxer.prototype;return e.resetInitSegment=function resetInitSegment(e,t,r){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=TSDemuxer.createTrack("video",r),this._audioTrack=TSDemuxer.createTrack("audio",r),this._id3Track=TSDemuxer.createTrack("id3",r),this._txtTrack=TSDemuxer.createTrack("text",r),this._audioTrack.isAAC=!0,this.aacOverFlow=null,this.aacLastPTS=null,this.avcSample=null,this.audioCodec=e,this.videoCodec=t,this._duration=r},e.resetTimeStamp=function resetTimeStamp(){},e.resetContiguity=function resetContiguity(){var e=this._audioTrack,t=this._avcTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.aacLastPTS=null},e.demux=function demux(e,t,r,i){var n;void 0===r&&(r=!1),void 0===i&&(i=!1),r||(this.sampleAes=null);var a=this._avcTrack,s=this._audioTrack,o=this._id3Track,h=a.pid,f=a.pesData,g=s.pid,v=o.pid,p=s.pesData,m=o.pesData,y=!1,E=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(S=(e=Object(u.appendUint8Array)(this.remainderData,e)).length,this.remainderData=null),S<188&&!i)return this.remainderData=e,{audioTrack:s,avcTrack:a,id3Track:o,textTrack:this._txtTrack};var b=Math.max(0,TSDemuxer.syncOffset(e));(S-=(S+b)%188)<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));for(var L=b;L<S;L+=188)if(71===e[L]){var A=!!(64&e[L+1]),_=((31&e[L+1])<<8)+e[L+2],D=void 0;if((48&e[L+3])>>4>1){if((D=L+5+e[L+4])===L+188)continue}else D=L+4;switch(_){case h:A&&(f&&(n=parsePES(f))&&this.parseAVCPES(n,!1),f={data:[],size:0}),f&&(f.data.push(e.subarray(D,L+188)),f.size+=L+188-D);break;case g:A&&(p&&(n=parsePES(p))&&(s.isAAC?this.parseAACPES(n):this.parseMPEGPES(n)),p={data:[],size:0}),p&&(p.data.push(e.subarray(D,L+188)),p.size+=L+188-D);break;case v:A&&(m&&(n=parsePES(m))&&this.parseID3PES(n),m={data:[],size:0}),m&&(m.data.push(e.subarray(D,L+188)),m.size+=L+188-D);break;case 0:A&&(D+=e[D]+1),T=this._pmtId=parsePAT(e,D);break;case T:A&&(D+=e[D]+1);var k=parsePMT(e,D,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,r);(h=k.avc)>0&&(a.pid=h),(g=k.audio)>0&&(s.pid=g,s.isAAC=k.isAAC),(v=k.id3)>0&&(o.pid=v),y&&!E&&(d.logger.log("reparse from beginning"),y=!1,L=b-188),E=this.pmtParsed=!0;break;case 17:case 8191:break;default:y=!0}}else this.observer.emit(l.Events.ERROR,l.Events.ERROR,{type:c.ErrorTypes.MEDIA_ERROR,details:c.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});a.pesData=f,s.pesData=p,o.pesData=m;var C={audioTrack:s,avcTrack:a,id3Track:o,textTrack:this._txtTrack};return i&&this.extractRemainingSamples(C),C},e.flush=function flush(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{audioTrack:this._audioTrack,avcTrack:this._avcTrack,textTrack:this._txtTrack,id3Track:this._id3Track},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},e.extractRemainingSamples=function extractRemainingSamples(e){var t,r=e.audioTrack,i=e.avcTrack,n=e.id3Track,a=i.pesData,s=r.pesData,o=n.pesData;a&&(t=parsePES(a))?(this.parseAVCPES(t,!0),i.pesData=null):i.pesData=a,s&&(t=parsePES(s))?(r.isAAC?this.parseAACPES(t):this.parseMPEGPES(t),r.pesData=null):(null!=s&&s.size&&d.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=s),o&&(t=parsePES(o))?(this.parseID3PES(t),n.pesData=null):n.pesData=o},e.demuxSampleAes=function demuxSampleAes(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),n=this.sampleAes=new o.default(this.observer,this.config,t);return this.decrypt(i,n)},e.decrypt=function decrypt(e,t){return new Promise((function(r){var i=e.audioTrack,n=e.avcTrack;i.samples&&i.isAAC?t.decryptAacSamples(i.samples,0,(function(){n.samples?t.decryptAvcSamples(n.samples,0,0,(function(){r(e)})):r(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(function(){r(e)}))}))},e.destroy=function destroy(){this._initPTS=this._initDTS=null,this._duration=0},e.parseAVCPES=function parseAVCPES(e,t){var r,i=this,n=this._avcTrack,o=this.parseAVCNALu(e.data),l=this.avcSample,u=!1;e.data=null,l&&o.length&&!n.audFound&&(pushAccessUnit(l,n),l=this.avcSample=createAVCSample(!1,e.pts,e.dts,"")),o.forEach((function(t){switch(t.type){case 1:r=!0,l||(l=i.avcSample=createAVCSample(!0,e.pts,e.dts,"")),l.frame=!0;var o=t.data;if(u&&o.length>4){var d=new a.default(o).readSliceType();2!==d&&4!==d&&7!==d&&9!==d||(l.key=!0)}break;case 5:r=!0,l||(l=i.avcSample=createAVCSample(!0,e.pts,e.dts,"")),l.key=!0,l.frame=!0;break;case 6:r=!0;var c=new a.default(discardEPB(t.data));c.readUByte();for(var h=0,f=0,g=!1,v=0;!g&&c.bytesAvailable>1;){h=0;do{h+=v=c.readUByte()}while(255===v);f=0;do{f+=v=c.readUByte()}while(255===v);if(4===h&&0!==c.bytesAvailable){if(g=!0,181===c.readUByte())if(49===c.readUShort())if(1195456820===c.readUInt())if(3===c.readUByte()){for(var p=c.readUByte(),m=31&p,y=[p,c.readUByte()],E=0;E<m;E++)y.push(c.readUByte()),y.push(c.readUByte()),y.push(c.readUByte());insertSampleInOrder(i._txtTrack.samples,{type:3,pts:e.pts,bytes:y})}}else if(5===h&&0!==c.bytesAvailable){if(g=!0,f>16){for(var T=[],S=0;S<16;S++)T.push(c.readUByte().toString(16)),3!==S&&5!==S&&7!==S&&9!==S||T.push("-");for(var b=f-16,L=new Uint8Array(b),A=0;A<b;A++)L[A]=c.readUByte();insertSampleInOrder(i._txtTrack.samples,{pts:e.pts,payloadType:h,uuid:T.join(""),userData:Object(s.utf8ArrayToStr)(L),userDataBytes:L})}}else if(f<c.bytesAvailable)for(var _=0;_<f;_++)c.readUByte()}break;case 7:if(r=!0,u=!0,!n.sps){var D=new a.default(t.data).readSPS();n.width=D.width,n.height=D.height,n.pixelRatio=D.pixelRatio,n.sps=[t.data],n.duration=i._duration;for(var k=t.data.subarray(1,4),C="avc1.",R=0;R<3;R++){var P=k[R].toString(16);P.length<2&&(P="0"+P),C+=P}n.codec=C}break;case 8:r=!0,n.pps||(n.pps=[t.data]);break;case 9:r=!1,n.audFound=!0,l&&pushAccessUnit(l,n),l=i.avcSample=createAVCSample(!1,e.pts,e.dts,"");break;case 12:r=!1;break;default:r=!1,l&&(l.debug+="unknown NAL "+t.type+" ")}l&&r&&l.units.push(t)})),t&&l&&(pushAccessUnit(l,n),this.avcSample=null)},e.getLastNalUnit=function getLastNalUnit(){var e,t,r=this.avcSample;if(!r||0===r.units.length){var i=this._avcTrack.samples;r=i[i.length-1]}if(null!==(e=r)&&void 0!==e&&e.units){var n=r.units;t=n[n.length-1]}return t},e.parseAVCNALu=function parseAVCNALu(e){var t,r,i=e.byteLength,n=this._avcTrack,a=n.naluState||0,s=a,o=[],l=0,u=-1,d=0;for(-1===a&&(u=0,d=31&e[0],a=0,l=1);l<i;)if(t=e[l++],a)if(1!==a)if(t)if(1===t){if(u>=0){var c={data:e.subarray(u,l-a-1),type:d};o.push(c)}else{var h=this.getLastNalUnit();if(h&&(s&&l<=4-s&&h.state&&(h.data=h.data.subarray(0,h.data.byteLength-s)),(r=l-a-1)>0)){var f=new Uint8Array(h.data.byteLength+r);f.set(h.data,0),f.set(e.subarray(0,r),h.data.byteLength),h.data=f}}l<i?(u=l,d=31&e[l],a=0):a=-1}else a=0;else a=3;else a=t?0:2;else a=t?0:1;if(u>=0&&a>=0){var g={data:e.subarray(u,i),type:d,state:a};o.push(g)}if(0===o.length){var v=this.getLastNalUnit();if(v){var p=new Uint8Array(v.data.byteLength+e.byteLength);p.set(v.data,0),p.set(e,v.data.byteLength),v.data=p}}return n.naluState=a,o},e.parseAACPES=function parseAACPES(e){var t,r,n,a,s,o=0,u=this._audioTrack,h=this.aacOverFlow,f=e.data;if(h){this.aacOverFlow=null;var g=h.sample.unit.byteLength,v=Math.min(h.missing,g),p=g-v;h.sample.unit.set(f.subarray(0,v),p),u.samples.push(h.sample),o=h.missing}for(t=o,r=f.length;t<r-1&&!i.isHeader(f,t);t++);if(t!==o&&(t<r-1?(n="AAC PES did not start with ADTS header,offset:"+t,a=!1):(n="no ADTS header found in AAC PES",a=!0),d.logger.warn("parsing error:"+n),this.observer.emit(l.Events.ERROR,l.Events.ERROR,{type:c.ErrorTypes.MEDIA_ERROR,details:c.ErrorDetails.FRAG_PARSING_ERROR,fatal:a,reason:n}),a))return;if(i.initTrackConfig(u,this.observer,f,t,this.audioCodec),void 0!==e.pts)s=e.pts;else{if(!h)return void d.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var m=i.getFrameDuration(u.samplerate);s=h.sample.pts+m}for(var y=0;t<r;){if(i.isHeader(f,t)){if(t+5<r){var E=i.appendFrame(u,f,t,s,y);if(E){if(!E.missing){t+=E.length,y++;continue}this.aacOverFlow=E}}break}t++}},e.parseMPEGPES=function parseMPEGPES(e){var t=e.data,r=t.length,i=0,a=0,s=e.pts;if(void 0!==s)for(;a<r;)if(n.isHeader(t,a)){var o=n.appendFrame(this._audioTrack,t,a,s,i);if(!o)break;a+=o.length,i++}else a++;else d.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")},e.parseID3PES=function parseID3PES(e){void 0!==e.pts?this._id3Track.samples.push(e):d.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},TSDemuxer}();function createAVCSample(e,t,r,i){return{key:e,frame:!1,pts:t,dts:r,units:[],debug:i,length:0}}function parsePAT(e,t){return(31&e[t+10])<<8|e[t+11]}function parsePMT(e,t,r,i){var n={audio:-1,avc:-1,id3:-1,isAAC:!0},a=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<a;){var s=(31&e[t+1])<<8|e[t+2];switch(e[t]){case 207:if(!i){d.logger.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===n.audio&&(n.audio=s);break;case 21:-1===n.id3&&(n.id3=s);break;case 219:if(!i){d.logger.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===n.avc&&(n.avc=s);break;case 3:case 4:r?-1===n.audio&&(n.audio=s,n.isAAC=!1):d.logger.log("MPEG audio found, not supported in this browser");break;case 36:d.logger.warn("Unsupported HEVC stream type found")}t+=5+((15&e[t+3])<<8|e[t+4])}return n}function parsePES(e){var t,r,i,n,a,s=0,o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((t=o[0])[0]<<16)+(t[1]<<8)+t[2]){if((r=(t[4]<<8)+t[5])&&r>e.size-6)return null;var u=t[7];192&u&&(n=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&u?n-(a=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>54e5&&(d.logger.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var c=(i=t[8])+9;if(e.size<=c)return null;e.size-=c;for(var h=new Uint8Array(e.size),f=0,g=o.length;f<g;f++){var v=(t=o[f]).byteLength;if(c){if(c>v){c-=v;continue}t=t.subarray(c),v-=c,c=0}h.set(t,s),s+=v}return r&&(r-=i+3),{data:h,pts:n,dts:a,len:r}}return null}function pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}e.debug.length&&d.logger.log(e.pts+"/"+e.dts+":"+e.debug)}function insertSampleInOrder(e,t){var r=e.length;if(r>0){if(t.pts>=e[r-1].pts)e.push(t);else for(var i=r-1;i>=0;i--)if(t.pts<e[i].pts){e.splice(i,0,t);break}}else e.push(t)}function discardEPB(e){for(var t=e.byteLength,r=[],i=1;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return e;var n=t-r.length,a=new Uint8Array(n),s=0;for(i=0;i<n;s++,i++)s===r[0]&&(s++,r.shift()),a[i]=e[s];return a}f.minProbeByteLength=188,t.default=f},"./src/errors.ts":
178
- /*!***********************!*\
179
- !*** ./src/errors.ts ***!
180
- \***********************/
181
- /*! exports provided: ErrorTypes, ErrorDetails */function(e,t,r){"use strict";var i,n;r.r(t),r.d(t,"ErrorTypes",(function(){return i})),r.d(t,"ErrorDetails",(function(){return n})),function(e){e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError"}(i||(i={})),function(e){e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_NO_INIT_DATA="keySystemNoInitData",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.UNKNOWN="unknown"}(n||(n={}))},"./src/events.ts":
182
- /*!***********************!*\
183
- !*** ./src/events.ts ***!
184
- \***********************/
185
- /*! exports provided: Events */function(e,t,r){"use strict";var i;r.r(t),r.d(t,"Events",(function(){return i})),function(e){e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},"./src/hls.ts":
186
- /*!********************!*\
187
- !*** ./src/hls.ts ***!
188
- \********************/
189
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return m}));var i=r(/*! url-toolkit */"./node_modules/url-toolkit/src/url-toolkit.js"),n=r(/*! ./loader/playlist-loader */"./src/loader/playlist-loader.ts"),a=r(/*! ./loader/key-loader */"./src/loader/key-loader.ts"),s=r(/*! ./controller/id3-track-controller */"./src/controller/id3-track-controller.ts"),o=r(/*! ./controller/latency-controller */"./src/controller/latency-controller.ts"),l=r(/*! ./controller/level-controller */"./src/controller/level-controller.ts"),u=r(/*! ./controller/fragment-tracker */"./src/controller/fragment-tracker.ts"),d=r(/*! ./controller/stream-controller */"./src/controller/stream-controller.ts"),c=r(/*! ./is-supported */"./src/is-supported.ts"),h=r(/*! ./utils/logger */"./src/utils/logger.ts"),f=r(/*! ./config */"./src/config.ts"),g=r(/*! eventemitter3 */"./node_modules/eventemitter3/index.js"),v=r(/*! ./events */"./src/events.ts"),p=r(/*! ./errors */"./src/errors.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var m=function(){function Hls(e){void 0===e&&(e={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new g.EventEmitter,this._autoLevelCapping=void 0,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this._media=null,this.url=null;var t=this.config=Object(f.mergeConfig)(Hls.DefaultConfig,e);this.userConfig=e,Object(h.enableLogs)(t.debug),this._autoLevelCapping=-1,t.progressive&&Object(f.enableStreamingMode)(t);var r=t.abrController,i=t.bufferController,c=t.capLevelController,v=t.fpsController,p=this.abrController=new r(this),m=this.bufferController=new i(this),y=this.capLevelController=new c(this),E=new v(this),T=new n.default(this),S=new a.default(this),b=new s.default(this),L=this.levelController=new l.default(this),A=new u.FragmentTracker(this),_=this.streamController=new d.default(this,A);y.setStreamController(_),E.setStreamController(_);var D=[L,_];this.networkControllers=D;var k=[T,S,p,m,y,E,b,A];this.audioTrackController=this.createController(t.audioTrackController,null,D),this.createController(t.audioStreamController,A,D),this.subtitleTrackController=this.createController(t.subtitleTrackController,null,D),this.createController(t.subtitleStreamController,A,D),this.createController(t.timelineController,null,k),this.emeController=this.createController(t.emeController,null,k),this.latencyController=this.createController(o.default,null,k),this.coreComponents=k}Hls.isSupported=function isSupported(){return Object(c.isSupported)()};var e=Hls.prototype;return e.createController=function createController(e,t,r){if(e){var i=t?new e(this,t):new e(this);return r&&r.push(i),i}return null},e.on=function on(e,t,r){void 0===r&&(r=this),this._emitter.on(e,t,r)},e.once=function once(e,t,r){void 0===r&&(r=this),this._emitter.once(e,t,r)},e.removeAllListeners=function removeAllListeners(e){this._emitter.removeAllListeners(e)},e.off=function off(e,t,r,i){void 0===r&&(r=this),this._emitter.off(e,t,r,i)},e.listeners=function listeners(e){return this._emitter.listeners(e)},e.emit=function emit(e,t,r){return this._emitter.emit(e,t,r)},e.trigger=function trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){h.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(v.Events.ERROR,{type:p.ErrorTypes.OTHER_ERROR,details:p.ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1},e.listenerCount=function listenerCount(e){return this._emitter.listenerCount(e)},e.destroy=function destroy(){h.logger.log("destroy"),this.trigger(v.Events.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0},e.attachMedia=function attachMedia(e){h.logger.log("attachMedia"),this._media=e,this.trigger(v.Events.MEDIA_ATTACHING,{media:e})},e.detachMedia=function detachMedia(){h.logger.log("detachMedia"),this.trigger(v.Events.MEDIA_DETACHING,void 0),this._media=null},e.loadSource=function loadSource(e){this.stopLoad();var t=this.media,r=this.url,n=this.url=i.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});h.logger.log("loadSource:"+n),t&&r&&r!==n&&this.bufferController.hasSourceTypes()&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.Events.MANIFEST_LOADING,{url:e})},e.startLoad=function startLoad(e){void 0===e&&(e=-1),h.logger.log("startLoad("+e+")"),this.networkControllers.forEach((function(t){t.startLoad(e)}))},e.stopLoad=function stopLoad(){h.logger.log("stopLoad"),this.networkControllers.forEach((function(e){e.stopLoad()}))},e.swapAudioCodec=function swapAudioCodec(){h.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()},e.recoverMediaError=function recoverMediaError(){h.logger.log("recoverMediaError");var e=this._media;this.detachMedia(),e&&this.attachMedia(e)},e.removeLevel=function removeLevel(e,t){void 0===t&&(t=0),this.levelController.removeLevel(e,t)},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(Hls,[{key:"levels",get:function get(){var e=this.levelController.levels;return e||[]}},{key:"currentLevel",get:function get(){return this.streamController.currentLevel},set:function set(e){h.logger.log("set currentLevel:"+e),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function get(){return this.streamController.nextLevel},set:function set(e){h.logger.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function get(){return this.levelController.level},set:function set(e){h.logger.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function get(){return this.levelController.nextLoadLevel},set:function set(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function get(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function set(e){h.logger.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function get(){return this.levelController.startLevel},set:function set(e){h.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function get(){return this.config.capLevelToPlayerSize},set:function set(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function get(){return this._autoLevelCapping},set:function set(e){this._autoLevelCapping!==e&&(h.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e)}},{key:"bandwidthEstimate",get:function get(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN}},{key:"autoLevelEnabled",get:function get(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function get(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function get(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>t)return i;return 0}},{key:"maxAutoLevel",get:function get(){var e=this.levels,t=this.autoLevelCapping;return-1===t&&e&&e.length?e.length-1:t}},{key:"nextAutoLevel",get:function get(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function set(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}},{key:"audioTracks",get:function get(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function get(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function set(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"subtitleTracks",get:function get(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function get(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function set(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function get(){return this._media}},{key:"subtitleDisplay",get:function get(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function set(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function get(){return this.config.lowLatencyMode},set:function set(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function get(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function get(){return this.latencyController.latency}},{key:"maxLatency",get:function get(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function get(){return this.latencyController.targetLatency}},{key:"drift",get:function get(){return this.latencyController.drift}},{key:"forceStartLoad",get:function get(){return this.streamController.forceStartLoad}}],[{key:"version",get:function get(){}},{key:"Events",get:function get(){return v.Events}},{key:"ErrorTypes",get:function get(){return p.ErrorTypes}},{key:"ErrorDetails",get:function get(){return p.ErrorDetails}},{key:"DefaultConfig",get:function get(){return Hls.defaultConfig?Hls.defaultConfig:f.hlsDefaultConfig},set:function set(e){Hls.defaultConfig=e}}]),Hls}();m.defaultConfig=void 0},"./src/is-supported.ts":
190
- /*!*****************************!*\
191
- !*** ./src/is-supported.ts ***!
192
- \*****************************/
193
- /*! exports provided: isSupported, changeTypeSupported */function(e,t,r){"use strict";r.r(t),r.d(t,"isSupported",(function(){return isSupported})),r.d(t,"changeTypeSupported",(function(){return changeTypeSupported}));var i=r(/*! ./utils/mediasource-helper */"./src/utils/mediasource-helper.ts");function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isSupported(){var e=Object(i.getMediaSource)();if(!e)return!1;var t=getSourceBuffer(),r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),n=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!n}function changeTypeSupported(){var e,t=getSourceBuffer();return"function"==typeof(null==t?void 0:null===(e=t.prototype)||void 0===e?void 0:e.changeType)}},"./src/loader/fragment-loader.ts":
194
- /*!***************************************!*\
195
- !*** ./src/loader/fragment-loader.ts ***!
196
- \***************************************/
197
- /*! exports provided: default, LoadError */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return s})),r.d(t,"LoadError",(function(){return o}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../errors */"./src/errors.ts");function _wrapNativeSuper(e){var t="function"==typeof Map?new Map:void 0;return(_wrapNativeSuper=function _wrapNativeSuper(e){if(null===e||!function _isNativeFunction(e){return-1!==Function.toString.call(e).indexOf("[native code]")}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,Wrapper)}function Wrapper(){return _construct(e,arguments,_getPrototypeOf(this).constructor)}return Wrapper.prototype=Object.create(e.prototype,{constructor:{value:Wrapper,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(Wrapper,e)})(e)}function _construct(e,t,r){return(_construct=_isNativeReflectConstruct()?Reflect.construct:function _construct(e,t,r){var i=[null];i.push.apply(i,t);var n=new(Function.bind.apply(e,i));return r&&_setPrototypeOf(n,r.prototype),n}).apply(null,arguments)}function _isNativeReflectConstruct(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var a=Math.pow(2,17),s=function(){function FragmentLoader(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var e=FragmentLoader.prototype;return e.destroy=function destroy(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function abort(){this.loader&&this.loader.abort()},e.load=function load(e,t){var r=this,i=e.url;if(!i)return Promise.reject(new o({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var s=this.config,l=s.fLoader,u=s.loader;return new Promise((function(i,d){r.loader&&r.loader.destroy();var c=r.loader=e.loader=l?new l(s):new u(s),h=createLoaderContext(e),f={timeout:s.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:s.fragLoadingMaxRetryTimeout,highWaterMark:a};e.stats=c.stats,c.load(h,f,{onSuccess:function onSuccess(t,n,a,s){r.resetLoader(e,c),i({frag:e,part:null,payload:t.data,networkDetails:s})},onError:function onError(t,i,a){r.resetLoader(e,c),d(new o({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:t,networkDetails:a}))},onAbort:function onAbort(t,i,a){r.resetLoader(e,c),d(new o({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,networkDetails:a}))},onTimeout:function onTimeout(t,i,a){r.resetLoader(e,c),d(new o({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,networkDetails:a}))},onProgress:function onProgress(r,i,n,a){t&&t({frag:e,part:null,payload:n,networkDetails:a})}})}))},e.loadPart=function loadPart(e,t,r){var i=this;this.abort();var s=this.config,l=s.fLoader,u=s.loader;return new Promise((function(d,c){i.loader&&i.loader.destroy();var h=i.loader=e.loader=l?new l(s):new u(s),f=createLoaderContext(e,t),g={timeout:s.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:s.fragLoadingMaxRetryTimeout,highWaterMark:a};t.stats=h.stats,h.load(f,g,{onSuccess:function onSuccess(n,a,s,o){i.resetLoader(e,h),i.updateStatsFromPart(e,t);var l={frag:e,part:t,payload:n.data,networkDetails:o};r(l),d(l)},onError:function onError(r,a,s){i.resetLoader(e,h),c(new o({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:r,networkDetails:s}))},onAbort:function onAbort(r,a,s){e.stats.aborted=t.stats.aborted,i.resetLoader(e,h),c(new o({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,networkDetails:s}))},onTimeout:function onTimeout(r,a,s){i.resetLoader(e,h),c(new o({type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,networkDetails:s}))}})}))},e.updateStatsFromPart=function updateStatsFromPart(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},e.resetLoader=function resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},FragmentLoader}();function createLoaderContext(e,t){void 0===t&&(t=null);var r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,rangeStart:0,rangeEnd:0},a=r.byteRangeStartOffset,s=r.byteRangeEndOffset;return Object(i.isFiniteNumber)(a)&&Object(i.isFiniteNumber)(s)&&(n.rangeStart=a,n.rangeEnd=s),n}var o=function(e){function LoadError(t){for(var r,i=arguments.length,n=new Array(i>1?i-1:0),a=1;a<i;a++)n[a-1]=arguments[a];return(r=e.call.apply(e,[this].concat(n))||this).data=void 0,r.data=t,r}return function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(LoadError,e),LoadError}(_wrapNativeSuper(Error))},"./src/loader/fragment.ts":
198
- /*!********************************!*\
199
- !*** ./src/loader/fragment.ts ***!
200
- \********************************/
201
- /*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */function(e,t,r){"use strict";r.r(t),r.d(t,"ElementaryStreamTypes",(function(){return i})),r.d(t,"BaseSegment",(function(){return u})),r.d(t,"Fragment",(function(){return d})),r.d(t,"Part",(function(){return c}));var i,n=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),a=r(/*! url-toolkit */"./node_modules/url-toolkit/src/url-toolkit.js"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ./level-key */"./src/loader/level-key.ts"),l=r(/*! ./load-stats */"./src/loader/load-stats.ts");function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}!function(e){e.AUDIO="audio",e.VIDEO="video",e.AUDIOVIDEO="audiovideo"}(i||(i={}));var u=function(){function BaseSegment(e){var t;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=((t={})[i.AUDIO]=null,t[i.VIDEO]=null,t[i.AUDIOVIDEO]=null,t),this.baseurl=e}return BaseSegment.prototype.setByteRange=function setByteRange(e,t){var r=e.split("@",2),i=[];1===r.length?i[0]=t?t.byteRangeEndOffset:0:i[0]=parseInt(r[1]),i[1]=parseInt(r[0])+i[0],this._byteRange=i},_createClass(BaseSegment,[{key:"byteRange",get:function get(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function get(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function get(){return this.byteRange[1]}},{key:"url",get:function get(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Object(a.buildAbsoluteURL)(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function set(e){this._url=e}}]),BaseSegment}(),d=function(e){function Fragment(t,r){var i;return(i=e.call(this,r)||this)._decryptdata=null,i.rawProgramDateTime=null,i.programDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkey=void 0,i.type=void 0,i.loader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.appendedPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.stats=new l.LoadStats,i.urlId=0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.type=t,i}_inheritsLoose(Fragment,e);var t=Fragment.prototype;return t.createInitializationVector=function createInitializationVector(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t},t.setDecryptDataFromLevelKey=function setDecryptDataFromLevelKey(e,t){var r=e;return"AES-128"===(null==e?void 0:e.method)&&e.uri&&!e.iv&&((r=o.LevelKey.fromURI(e.uri)).method=e.method,r.iv=this.createInitializationVector(t),r.keyFormat="identity"),r},t.setElementaryStreamInfo=function setElementaryStreamInfo(e,t,r,i,n,a){void 0===a&&(a=!1);var s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:a}},t.clearElementaryStreamInfo=function clearElementaryStreamInfo(){var e=this.elementaryStreams;e[i.AUDIO]=null,e[i.VIDEO]=null,e[i.AUDIOVIDEO]=null},_createClass(Fragment,[{key:"decryptdata",get:function get(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var e=this.sn;"number"!=typeof e&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&s.logger.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),e=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,e)}return this._decryptdata}},{key:"end",get:function get(){return this.start+this.duration}},{key:"endProgramDateTime",get:function get(){if(null===this.programDateTime)return null;if(!Object(n.isFiniteNumber)(this.programDateTime))return null;var e=Object(n.isFiniteNumber)(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function get(){var e;return!(null===(e=this.decryptdata)||void 0===e||!e.keyFormat||!this.decryptdata.uri)}}]),Fragment}(u),c=function(e){function Part(t,r,i,n,a){var s;(s=e.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new l.LoadStats,s.duration=t.decimalFloatingPoint("DURATION"),s.gap=t.bool("GAP"),s.independent=t.bool("INDEPENDENT"),s.relurl=t.enumeratedString("URI"),s.fragment=r,s.index=n;var o=t.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return _inheritsLoose(Part,e),_createClass(Part,[{key:"start",get:function get(){return this.fragment.start+this.fragOffset}},{key:"end",get:function get(){return this.start+this.duration}},{key:"loaded",get:function get(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}]),Part}(u)},"./src/loader/key-loader.ts":
202
- /*!**********************************!*\
203
- !*** ./src/loader/key-loader.ts ***!
204
- \**********************************/
205
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return s}));var i=r(/*! ../events */"./src/events.ts"),n=r(/*! ../errors */"./src/errors.ts"),a=r(/*! ../utils/logger */"./src/utils/logger.ts"),s=function(){function KeyLoader(e){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=e,this._registerListeners()}var e=KeyLoader.prototype;return e._registerListeners=function _registerListeners(){this.hls.on(i.Events.KEY_LOADING,this.onKeyLoading,this)},e._unregisterListeners=function _unregisterListeners(){this.hls.off(i.Events.KEY_LOADING,this.onKeyLoading)},e.destroy=function destroy(){for(var e in this._unregisterListeners(),this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={}},e.onKeyLoading=function onKeyLoading(e,t){var r=t.frag,n=r.type,s=this.loaders[n];if(r.decryptdata){var o=r.decryptdata.uri;if(o!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(s&&(a.logger.warn("abort previous key loader for type:"+n),s.abort()),!o)return void a.logger.warn("key uri is falsy");var u=l.loader,d=r.loader=this.loaders[n]=new u(l);this.decrypturl=o,this.decryptkey=null;var c={url:o,frag:r,responseType:"arraybuffer"},h={timeout:l.fragLoadingTimeOut,maxRetry:0,retryDelay:l.fragLoadingRetryDelay,maxRetryDelay:l.fragLoadingMaxRetryTimeout,highWaterMark:0},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};d.load(c,h,f)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(i.Events.KEY_LOADED,{frag:r}))}else a.logger.warn("Missing decryption data on fragment in onKeyLoading")},e.loadsuccess=function loadsuccess(e,t,r){var n=r.frag;n.decryptdata?(this.decryptkey=n.decryptdata.key=new Uint8Array(e.data),n.loader=null,delete this.loaders[n.type],this.hls.trigger(i.Events.KEY_LOADED,{frag:n})):a.logger.error("after key load, decryptdata unset")},e.loaderror=function loaderror(e,t){var r=t.frag,a=r.loader;a&&a.abort(),delete this.loaders[r.type],this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},e.loadtimeout=function loadtimeout(e,t){var r=t.frag,a=r.loader;a&&a.abort(),delete this.loaders[r.type],this.hls.trigger(i.Events.ERROR,{type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},KeyLoader}()},"./src/loader/level-details.ts":
206
- /*!*************************************!*\
207
- !*** ./src/loader/level-details.ts ***!
208
- \*************************************/
209
- /*! exports provided: LevelDetails */function(e,t,r){"use strict";r.r(t),r.d(t,"LevelDetails",(function(){return n}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var n=function(){function LevelDetails(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.fragments=[],this.url=e}return LevelDetails.prototype.reloaded=function reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(LevelDetails,[{key:"hasProgramDateTime",get:function get(){return!!this.fragments.length&&Object(i.isFiniteNumber)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function get(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function get(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function get(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function get(){var e;return null!==(e=this.partList)&&void 0!==e&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function get(){var e;return null!==(e=this.fragments)&&void 0!==e&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function get(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function get(){var e;return null!==(e=this.partList)&&void 0!==e&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function get(){var e;return null!==(e=this.partList)&&void 0!==e&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),LevelDetails}()},"./src/loader/level-key.ts":
210
- /*!*********************************!*\
211
- !*** ./src/loader/level-key.ts ***!
212
- \*********************************/
213
- /*! exports provided: LevelKey */function(e,t,r){"use strict";r.r(t),r.d(t,"LevelKey",(function(){return n}));var i=r(/*! url-toolkit */"./node_modules/url-toolkit/src/url-toolkit.js");function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var n=function(){function LevelKey(e,t){this._uri=null,this.method=null,this.keyFormat=null,this.keyFormatVersions=null,this.keyID=null,this.key=null,this.iv=null,this._uri=t?Object(i.buildAbsoluteURL)(e,t,{alwaysNormalize:!0}):e}return LevelKey.fromURL=function fromURL(e,t){return new LevelKey(e,t)},LevelKey.fromURI=function fromURI(e){return new LevelKey(e)},function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(LevelKey,[{key:"uri",get:function get(){return this._uri}}]),LevelKey}()},"./src/loader/load-stats.ts":
214
- /*!**********************************!*\
215
- !*** ./src/loader/load-stats.ts ***!
216
- \**********************************/
217
- /*! exports provided: LoadStats */function(e,t,r){"use strict";r.r(t),r.d(t,"LoadStats",(function(){return i}));var i=function LoadStats(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},"./src/loader/m3u8-parser.ts":
218
- /*!***********************************!*\
219
- !*** ./src/loader/m3u8-parser.ts ***!
220
- \***********************************/
221
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return p}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! url-toolkit */"./node_modules/url-toolkit/src/url-toolkit.js"),a=r(/*! ./fragment */"./src/loader/fragment.ts"),s=r(/*! ./level-details */"./src/loader/level-details.ts"),o=r(/*! ./level-key */"./src/loader/level-key.ts"),l=r(/*! ../utils/attr-list */"./src/utils/attr-list.ts"),u=r(/*! ../utils/logger */"./src/utils/logger.ts"),d=r(/*! ../utils/codecs */"./src/utils/codecs.ts"),c=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,h=/#EXT-X-MEDIA:(.*)/g,f=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),g=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(PLAYLIST-TYPE):(.+)/.source,/#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source,/#EXT-X-(SKIP):(.+)/.source,/#EXT-X-(TARGETDURATION): *(\d+)/.source,/#EXT-X-(KEY):(.+)/.source,/#EXT-X-(START):(.+)/.source,/#EXT-X-(ENDLIST)/.source,/#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source,/#EXT-X-(DIS)CONTINUITY/.source,/#EXT-X-(VERSION):(\d+)/.source,/#EXT-X-(MAP):(.+)/.source,/#EXT-X-(SERVER-CONTROL):(.+)/.source,/#EXT-X-(PART-INF):(.+)/.source,/#EXT-X-(GAP)/.source,/#EXT-X-(BITRATE):\s*(\d+)/.source,/#EXT-X-(PART):(.+)/.source,/#EXT-X-(PRELOAD-HINT):(.+)/.source,/#EXT-X-(RENDITION-REPORT):(.+)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),v=/\.(mp4|m4s|m4v|m4a)$/i;var p=function(){function M3U8Parser(){}return M3U8Parser.findGroup=function findGroup(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}},M3U8Parser.convertAVC1ToAVCOTI=function convertAVC1ToAVCOTI(e){var t=e.split(".");if(t.length>2){var r=t.shift()+".";return r+=parseInt(t.shift()).toString(16),r+=("000"+parseInt(t.shift()).toString(16)).substr(-4)}return e},M3U8Parser.resolve=function resolve(e,t){return n.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},M3U8Parser.parseMasterPlaylist=function parseMasterPlaylist(e,t){var r,i=[],n={},a=!1;for(c.lastIndex=0;null!=(r=c.exec(e));)if(r[1]){var s=new l.AttrList(r[1]),o={attrs:s,bitrate:s.decimalInteger("AVERAGE-BANDWIDTH")||s.decimalInteger("BANDWIDTH"),name:s.NAME,url:M3U8Parser.resolve(r[2],t)},u=s.decimalResolution("RESOLUTION");u&&(o.width=u.width,o.height=u.height),setCodecs((s.CODECS||"").split(/[ ,]+/).filter((function(e){return e})),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=M3U8Parser.convertAVC1ToAVCOTI(o.videoCodec)),i.push(o)}else if(r[3]){var d=new l.AttrList(r[3]);d["DATA-ID"]&&(a=!0,n[d["DATA-ID"]]=d)}return{levels:i,sessionData:a?n:null}},M3U8Parser.parseMasterPlaylistMedia=function parseMasterPlaylistMedia(e,t,r,i){var n;void 0===i&&(i=[]);var a=[],s=0;for(h.lastIndex=0;null!==(n=h.exec(e));){var o=new l.AttrList(n[1]);if(o.TYPE===r){var u={attrs:o,bitrate:0,id:s++,groupId:o["GROUP-ID"],instreamId:o["INSTREAM-ID"],name:o.NAME||o.LANGUAGE||"",type:r,default:o.bool("DEFAULT"),autoselect:o.bool("AUTOSELECT"),forced:o.bool("FORCED"),lang:o.LANGUAGE,url:o.URI?M3U8Parser.resolve(o.URI,t):""};if(i.length){var d=M3U8Parser.findGroup(i,u.groupId)||i[0];assignCodec(u,d,"audioCodec"),assignCodec(u,d,"textCodec")}a.push(u)}}return a},M3U8Parser.parseLevelPlaylist=function parseLevelPlaylist(e,t,r,d,c){var h,p,m,y=new s.LevelDetails(t),E=y.fragments,T=null,S=0,b=0,L=0,A=0,_=null,D=new a.Fragment(d,t),k=-1,C=!1;for(f.lastIndex=0,y.m3u8=e;null!==(h=f.exec(e));){C&&(C=!1,(D=new a.Fragment(d,t)).start=L,D.sn=S,D.cc=A,D.level=r,T&&(D.initSegment=T,D.rawProgramDateTime=T.rawProgramDateTime));var R=h[1];if(R){D.duration=parseFloat(R);var P=(" "+h[2]).slice(1);D.title=P||null,D.tagList.push(P?["INF",R,P]:["INF",R])}else if(h[3])Object(i.isFiniteNumber)(D.duration)&&(D.start=L,m&&(D.levelkey=m),D.sn=S,D.level=r,D.cc=A,D.urlId=c,E.push(D),D.relurl=(" "+h[3]).slice(1),assignProgramDateTime(D,_),_=D,L+=D.duration,S++,b=0,C=!0);else if(h[4]){var I=(" "+h[4]).slice(1);_?D.setByteRange(I,_):D.setByteRange(I)}else if(h[5])D.rawProgramDateTime=(" "+h[5]).slice(1),D.tagList.push(["PROGRAM-DATE-TIME",D.rawProgramDateTime]),-1===k&&(k=E.length);else{if(!(h=h[0].match(g))){u.logger.warn("No matches on slow regex match for level playlist!");continue}for(p=1;p<h.length&&void 0===h[p];p++);var x=(" "+h[p]).slice(1),O=(" "+h[p+1]).slice(1),w=h[p+2]?(" "+h[p+2]).slice(1):"";switch(x){case"PLAYLIST-TYPE":y.type=O.toUpperCase();break;case"MEDIA-SEQUENCE":S=y.startSN=parseInt(O);break;case"SKIP":var F=new l.AttrList(O),M=F.decimalInteger("SKIPPED-SEGMENTS");if(Object(i.isFiniteNumber)(M)){y.skippedSegments=M;for(var N=M;N--;)E.unshift(null);S+=M}var B=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");B&&(y.recentlyRemovedDateranges=B.split("\t"));break;case"TARGETDURATION":y.targetduration=parseFloat(O);break;case"VERSION":y.version=parseInt(O);break;case"EXTM3U":break;case"ENDLIST":y.live=!1;break;case"#":(O||w)&&D.tagList.push(w?[O,w]:[O]);break;case"DIS":A++;case"GAP":D.tagList.push([x]);break;case"BITRATE":D.tagList.push([x,O]);break;case"DISCONTINUITY-SEQ":A=parseInt(O);break;case"KEY":var U,G=new l.AttrList(O),K=G.enumeratedString("METHOD"),j=G.URI,H=G.hexadecimalInteger("IV"),V=G.enumeratedString("KEYFORMATVERSIONS"),W=G.enumeratedString("KEYID"),q=null!=(U=G.enumeratedString("KEYFORMAT"))?U:"identity";if(["com.apple.streamingkeydelivery","com.microsoft.playready","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed","com.widevine"].indexOf(q)>-1){u.logger.warn("Keyformat "+q+" is not supported from the manifest");continue}if("identity"!==q)continue;K&&(m=o.LevelKey.fromURL(t,j),j&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(K)>=0&&(m.method=K,m.keyFormat=q,W&&(m.keyID=W),V&&(m.keyFormatVersions=V),m.iv=H));break;case"START":var Y=new l.AttrList(O).decimalFloatingPoint("TIME-OFFSET");Object(i.isFiniteNumber)(Y)&&(y.startTimeOffset=Y);break;case"MAP":var X=new l.AttrList(O);D.relurl=X.URI,X.BYTERANGE&&D.setByteRange(X.BYTERANGE),D.level=r,D.sn="initSegment",m&&(D.levelkey=m),D.initSegment=null,T=D,C=!0;break;case"SERVER-CONTROL":var z=new l.AttrList(O);y.canBlockReload=z.bool("CAN-BLOCK-RELOAD"),y.canSkipUntil=z.optionalFloat("CAN-SKIP-UNTIL",0),y.canSkipDateRanges=y.canSkipUntil>0&&z.bool("CAN-SKIP-DATERANGES"),y.partHoldBack=z.optionalFloat("PART-HOLD-BACK",0),y.holdBack=z.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var Q=new l.AttrList(O);y.partTarget=Q.decimalFloatingPoint("PART-TARGET");break;case"PART":var $=y.partList;$||($=y.partList=[]);var J=b>0?$[$.length-1]:void 0,Z=b++,ee=new a.Part(new l.AttrList(O),D,t,Z,J);$.push(ee),D.duration+=ee.duration;break;case"PRELOAD-HINT":var te=new l.AttrList(O);y.preloadHint=te;break;case"RENDITION-REPORT":var re=new l.AttrList(O);y.renditionReports=y.renditionReports||[],y.renditionReports.push(re);break;default:u.logger.warn("line parsed but not handled: "+h)}}}_&&!_.relurl?(E.pop(),L-=_.duration,y.partList&&(y.fragmentHint=_)):y.partList&&(assignProgramDateTime(D,_),D.cc=A,y.fragmentHint=D);var ie=E.length,ne=E[0],ae=E[ie-1];if((L+=y.skippedSegments*y.targetduration)>0&&ie&&ae){y.averagetargetduration=L/ie;var se=ae.sn;y.endSN="initSegment"!==se?se:0,ne&&(y.startCC=ne.cc,ne.initSegment||y.fragments.every((function(e){return e.relurl&&function isMP4Url(e){var t,r;return v.test(null!=(t=null===(r=n.parseURL(e))||void 0===r?void 0:r.path)?t:"")}(e.relurl)}))&&(u.logger.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(D=new a.Fragment(d,t)).relurl=ae.relurl,D.level=r,D.sn="initSegment",ne.initSegment=D,y.needSidxRanges=!0))}else y.endSN=0,y.startCC=0;return y.fragmentHint&&(L+=y.fragmentHint.duration),y.totalduration=L,y.endCC=A,k>0&&function backfillProgramDateTimes(e,t){for(var r=e[t],i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(E,k),y},M3U8Parser}();function setCodecs(e,t){["video","audio","text"].forEach((function(r){var i=e.filter((function(e){return Object(d.isCodecType)(e,r)}));if(i.length){var n=i.filter((function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)}));t[r+"Codec"]=n.length>0?n[0]:i[0],e=e.filter((function(e){return-1===i.indexOf(e)}))}})),t.unknownCodecs=e}function assignCodec(e,t,r){var i=t[r];i&&(e[r]=i)}function assignProgramDateTime(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Object(i.isFiniteNumber)(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}},"./src/loader/playlist-loader.ts":
222
- /*!***************************************!*\
223
- !*** ./src/loader/playlist-loader.ts ***!
224
- \***************************************/
225
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../events */"./src/events.ts"),a=r(/*! ../errors */"./src/errors.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),l=r(/*! ./m3u8-parser */"./src/loader/m3u8-parser.ts"),u=r(/*! ../types/loader */"./src/types/loader.ts"),d=r(/*! ../utils/attr-list */"./src/utils/attr-list.ts");function getResponseUrl(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var c=function(){function PlaylistLoader(e){this.hls=void 0,this.loaders=Object.create(null),this.hls=e,this.registerListeners()}var e=PlaylistLoader.prototype;return e.registerListeners=function registerListeners(){var e=this.hls;e.on(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(n.Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(n.Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(n.Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function unregisterListeners(){var e=this.hls;e.off(n.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(n.Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(n.Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(n.Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function createInternalLoader(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return e.loader=n,this.loaders[e.type]=n,n},e.getInternalLoader=function getInternalLoader(e){return this.loaders[e.type]},e.resetInternalLoader=function resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]},e.destroyInternalLoaders=function destroyInternalLoaders(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},e.destroy=function destroy(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function onManifestLoading(e,t){var r=t.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:u.PlaylistContextType.MANIFEST,url:r,deliveryDirectives:null})},e.onLevelLoading=function onLevelLoading(e,t){var r=t.id,i=t.level,n=t.url,a=t.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:u.PlaylistContextType.LEVEL,url:n,deliveryDirectives:a})},e.onAudioTrackLoading=function onAudioTrackLoading(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:u.PlaylistContextType.AUDIO_TRACK,url:n,deliveryDirectives:a})},e.onSubtitleTrackLoading=function onSubtitleTrackLoading(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:u.PlaylistContextType.SUBTITLE_TRACK,url:n,deliveryDirectives:a})},e.load=function load(e){var t,r,i,n,a,o,l=this.hls.config,d=this.getInternalLoader(e);if(d){var c=d.context;if(c&&c.url===e.url)return void s.logger.trace("[playlist-loader]: playlist request ongoing");s.logger.log("[playlist-loader]: aborting previous loader for type: "+e.type),d.abort()}switch(e.type){case u.PlaylistContextType.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,n=l.manifestLoadingRetryDelay,a=l.manifestLoadingMaxRetryTimeout;break;case u.PlaylistContextType.LEVEL:case u.PlaylistContextType.AUDIO_TRACK:case u.PlaylistContextType.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,n=l.levelLoadingRetryDelay,a=l.levelLoadingMaxRetryTimeout}if((d=this.createInternalLoader(e),null!==(t=e.deliveryDirectives)&&void 0!==t&&t.part)&&(e.type===u.PlaylistContextType.LEVEL&&null!==e.level?o=this.hls.levels[e.level].details:e.type===u.PlaylistContextType.AUDIO_TRACK&&null!==e.id?o=this.hls.audioTracks[e.id].details:e.type===u.PlaylistContextType.SUBTITLE_TRACK&&null!==e.id&&(o=this.hls.subtitleTracks[e.id].details),o)){var h=o.partTarget,f=o.targetduration;h&&f&&(i=Math.min(1e3*Math.max(3*h,.8*f),i))}var g={timeout:i,maxRetry:r,retryDelay:n,maxRetryDelay:a,highWaterMark:0},v={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};d.load(e,g,v)},e.loadsuccess=function loadsuccess(e,t,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(e,r),void this.handlePlaylistLoaded(e,t,r,i);this.resetInternalLoader(r.type);var n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),n.indexOf("#EXTINF:")>0||n.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(e,t,r,i):this.handleMasterPlaylist(e,t,r,i)):this.handleManifestParsingError(e,r,"no EXTM3U delimiter",i)},e.loaderror=function loaderror(e,t,r){void 0===r&&(r=null),this.handleNetworkError(t,r,!1,e)},e.loadtimeout=function loadtimeout(e,t,r){void 0===r&&(r=null),this.handleNetworkError(t,r,!0)},e.handleMasterPlaylist=function handleMasterPlaylist(e,t,r,i){var a=this.hls,o=e.data,u=getResponseUrl(e,r),c=l.default.parseMasterPlaylist(o,u),h=c.levels,f=c.sessionData;if(h.length){var g=h.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),v=h.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),p=l.default.parseMasterPlaylistMedia(o,u,"AUDIO",g),m=l.default.parseMasterPlaylistMedia(o,u,"SUBTITLES",v),y=l.default.parseMasterPlaylistMedia(o,u,"CLOSED-CAPTIONS");if(p.length)p.some((function(e){return!e.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(s.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new d.AttrList({}),bitrate:0,url:""}));a.trigger(n.Events.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:m,captions:y,url:u,stats:t,networkDetails:i,sessionData:f})}else this.handleManifestParsingError(e,r,"no level found in manifest",i)},e.handleTrackOrLevelPlaylist=function handleTrackOrLevelPlaylist(e,t,r,s){var o=this.hls,c=r.id,h=r.level,f=r.type,g=getResponseUrl(e,r),v=Object(i.isFiniteNumber)(c)?c:0,p=Object(i.isFiniteNumber)(h)?h:v,m=function mapContextToLevelType(e){switch(e.type){case u.PlaylistContextType.AUDIO_TRACK:return u.PlaylistLevelType.AUDIO;case u.PlaylistContextType.SUBTITLE_TRACK:return u.PlaylistLevelType.SUBTITLE;default:return u.PlaylistLevelType.MAIN}}(r),y=l.default.parseLevelPlaylist(e.data,g,p,m,v);if(y.fragments.length){if(f===u.PlaylistContextType.MANIFEST){var E={attrs:new d.AttrList({}),bitrate:0,details:y,name:"",url:g};o.trigger(n.Events.MANIFEST_LOADED,{levels:[E],audioTracks:[],url:g,stats:t,networkDetails:s,sessionData:null})}if(t.parsing.end=performance.now(),y.needSidxRanges){var T,S=null===(T=y.fragments[0].initSegment)||void 0===T?void 0:T.url;this.load({url:S,isSidxRequest:!0,type:f,level:h,levelDetails:y,id:c,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=y,this.handlePlaylistLoaded(e,t,r,s)}else o.trigger(n.Events.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:g,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},e.handleSidxRequest=function handleSidxRequest(e,t){var r=Object(o.parseSegmentIndex)(new Uint8Array(e.data));if(r){var i=r.references,n=t.levelDetails;i.forEach((function(e,t){var i=e.info,a=n.fragments[t];0===a.byteRange.length&&a.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),a.initSegment&&a.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}))}},e.handleManifestParsingError=function handleManifestParsingError(e,t,r,i){this.hls.trigger(n.Events.ERROR,{type:a.ErrorTypes.NETWORK_ERROR,details:a.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===u.PlaylistContextType.MANIFEST,url:e.url,reason:r,response:e,context:t,networkDetails:i})},e.handleNetworkError=function handleNetworkError(e,t,r,i){void 0===r&&(r=!1),s.logger.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+e.type+" level: "+e.level+" id: "+e.id+' group-id: "'+e.groupId+'"');var o=a.ErrorDetails.UNKNOWN,l=!1,d=this.getInternalLoader(e);switch(e.type){case u.PlaylistContextType.MANIFEST:o=r?a.ErrorDetails.MANIFEST_LOAD_TIMEOUT:a.ErrorDetails.MANIFEST_LOAD_ERROR,l=!0;break;case u.PlaylistContextType.LEVEL:o=r?a.ErrorDetails.LEVEL_LOAD_TIMEOUT:a.ErrorDetails.LEVEL_LOAD_ERROR,l=!1;break;case u.PlaylistContextType.AUDIO_TRACK:o=r?a.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:a.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case u.PlaylistContextType.SUBTITLE_TRACK:o=r?a.ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:a.ErrorDetails.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);var c={type:a.ErrorTypes.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,networkDetails:t};i&&(c.response=i),this.hls.trigger(n.Events.ERROR,c)},e.handlePlaylistLoaded=function handlePlaylistLoaded(e,t,r,i){var a=r.type,s=r.level,o=r.id,l=r.groupId,d=r.loader,c=r.levelDetails,h=r.deliveryDirectives;if(null!=c&&c.targetduration){if(d)switch(c.live&&(d.getCacheAge&&(c.ageHeader=d.getCacheAge()||0),d.getCacheAge&&!isNaN(c.ageHeader)||(c.ageHeader=0)),a){case u.PlaylistContextType.MANIFEST:case u.PlaylistContextType.LEVEL:this.hls.trigger(n.Events.LEVEL_LOADED,{details:c,level:s||0,id:o||0,stats:t,networkDetails:i,deliveryDirectives:h});break;case u.PlaylistContextType.AUDIO_TRACK:this.hls.trigger(n.Events.AUDIO_TRACK_LOADED,{details:c,id:o||0,groupId:l||"",stats:t,networkDetails:i,deliveryDirectives:h});break;case u.PlaylistContextType.SUBTITLE_TRACK:this.hls.trigger(n.Events.SUBTITLE_TRACK_LOADED,{details:c,id:o||0,groupId:l||"",stats:t,networkDetails:i,deliveryDirectives:h})}}else this.handleManifestParsingError(e,r,"invalid target duration",i)},PlaylistLoader}();t.default=c},"./src/polyfills/number.ts":
226
- /*!*********************************!*\
227
- !*** ./src/polyfills/number.ts ***!
228
- \*********************************/
229
- /*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */function(e,t,r){"use strict";r.r(t),r.d(t,"isFiniteNumber",(function(){return i})),r.d(t,"MAX_SAFE_INTEGER",(function(){return n}));var i=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},n=Number.MAX_SAFE_INTEGER||9007199254740991},"./src/remux/aac-helper.ts":
230
- /*!*********************************!*\
231
- !*** ./src/remux/aac-helper.ts ***!
232
- \*********************************/
233
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=function(){function AAC(){}return AAC.getSilentFrame=function getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)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===t)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===t)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===t)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===t)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])}},AAC}();t.default=i},"./src/remux/mp4-generator.ts":
234
- /*!************************************!*\
235
- !*** ./src/remux/mp4-generator.ts ***!
236
- \************************************/
237
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=Math.pow(2,32)-1,n=function(){function MP4(){}return MP4.init=function init(){var e;for(e in MP4.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:[]},MP4.types)MP4.types.hasOwnProperty(e)&&(MP4.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);var t=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]),r=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]);MP4.HDLR_TYPES={video:t,audio:r};var i=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]);MP4.STTS=MP4.STSC=MP4.STCO=n,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);MP4.FTYP=MP4.box(MP4.types.ftyp,a,o,a,s),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,i))},MP4.box=function box(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];for(var a=i.length,s=a;a--;)t+=i[a].byteLength;var o=new Uint8Array(t);for(o[0]=t>>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),a=0,t=8;a<s;a++)o.set(i[a],t),t+=i[a].byteLength;return o},MP4.hdlr=function hdlr(e){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[e])},MP4.mdat=function mdat(e){return MP4.box(MP4.types.mdat,e)},MP4.mdhd=function mdhd(e,t){t*=e;var r=Math.floor(t/(i+1)),n=Math.floor(t%(i+1));return MP4.box(MP4.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,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},MP4.mdia=function mdia(e){return MP4.box(MP4.types.mdia,MP4.mdhd(e.timescale,e.duration),MP4.hdlr(e.type),MP4.minf(e))},MP4.mfhd=function mfhd(e){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},MP4.minf=function minf(e){return"audio"===e.type?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(e)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(e))},MP4.moof=function moof(e,t,r){return MP4.box(MP4.types.moof,MP4.mfhd(e),MP4.traf(r,t))},MP4.moov=function moov(e){for(var t=e.length,r=[];t--;)r[t]=MP4.trak(e[t]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(e[0].timescale,e[0].duration)].concat(r).concat(MP4.mvex(e)))},MP4.mvex=function mvex(e){for(var t=e.length,r=[];t--;)r[t]=MP4.trex(e[t]);return MP4.box.apply(null,[MP4.types.mvex].concat(r))},MP4.mvhd=function mvhd(e,t){t*=e;var r=Math.floor(t/(i+1)),n=Math.floor(t%(i+1)),a=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,r>>24,r>>16&255,r>>8&255,255&r,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 MP4.box(MP4.types.mvhd,a)},MP4.sdtp=function sdtp(e){var t,r,i=e.samples||[],n=new Uint8Array(4+i.length);for(t=0;t<i.length;t++)r=i[t].flags,n[t+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return MP4.box(MP4.types.sdtp,n)},MP4.stbl=function stbl(e){return MP4.box(MP4.types.stbl,MP4.stsd(e),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(e){var t,r,i,n=[],a=[];for(t=0;t<e.sps.length;t++)i=(r=e.sps[t]).byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(r));for(t=0;t<e.pps.length;t++)i=(r=e.pps[t]).byteLength,a.push(i>>>8&255),a.push(255&i),a=a.concat(Array.prototype.slice.call(r));var s=MP4.box(MP4.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(a))),o=e.width,l=e.height,u=e.pixelRatio[0],d=e.pixelRatio[1];return MP4.box(MP4.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,o>>8&255,255&o,l>>8&255,255&l,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,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,d>>24,d>>16&255,d>>8&255,255&d])))},MP4.esds=function esds(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))},MP4.mp4a=function mp4a(e){var t=e.samplerate;return MP4.box(MP4.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,t>>8&255,255&t,0,0]),MP4.box(MP4.types.esds,MP4.esds(e)))},MP4.mp3=function mp3(e){var t=e.samplerate;return MP4.box(MP4.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,t>>8&255,255&t,0,0]))},MP4.stsd=function stsd(e){return"audio"===e.type?e.isAAC||"mp3"!==e.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(e)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(e)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(e))},MP4.tkhd=function tkhd(e){var t=e.id,r=e.duration*e.timescale,n=e.width,a=e.height,s=Math.floor(r/(i+1)),o=Math.floor(r%(i+1));return MP4.box(MP4.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,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,a>>8&255,255&a,0,0]))},MP4.traf=function traf(e,t){var r=MP4.sdtp(e),n=e.id,a=Math.floor(t/(i+1)),s=Math.floor(t%(i+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),MP4.trun(e,r.length+16+20+8+16+8+8),r)},MP4.trak=function trak(e){return e.duration=e.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(e),MP4.mdia(e))},MP4.trex=function trex(e){var t=e.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},MP4.trun=function trun(e,t){var r,i,n,a,s,o,l=e.samples||[],u=l.length,d=12+16*u,c=new Uint8Array(d);for(t+=8+d,c.set([0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),r=0;r<u;r++)n=(i=l[r]).duration,a=i.size,s=i.flags,o=i.cts,c.set([n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,s.isLeading<<2|s.dependsOn,s.isDependedOn<<6|s.hasRedundancy<<4|s.paddingValue<<1|s.isNonSync,61440&s.degradPrio,15&s.degradPrio,o>>>24&255,o>>>16&255,o>>>8&255,255&o],12+16*r);return MP4.box(MP4.types.trun,c)},MP4.initSegment=function initSegment(e){MP4.types||MP4.init();var t=MP4.moov(e),r=new Uint8Array(MP4.FTYP.byteLength+t.byteLength);return r.set(MP4.FTYP),r.set(t,MP4.FTYP.byteLength),r},MP4}();n.types=void 0,n.HDLR_TYPES=void 0,n.STTS=void 0,n.STSC=void 0,n.STCO=void 0,n.STSZ=void 0,n.VMHD=void 0,n.SMHD=void 0,n.STSD=void 0,n.FTYP=void 0,n.DINF=void 0,t.default=n},"./src/remux/mp4-remuxer.ts":
238
- /*!**********************************!*\
239
- !*** ./src/remux/mp4-remuxer.ts ***!
240
- \**********************************/
241
- /*! exports provided: default, normalizePts */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return g})),r.d(t,"normalizePts",(function(){return normalizePts}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./aac-helper */"./src/remux/aac-helper.ts"),a=r(/*! ./mp4-generator */"./src/remux/mp4-generator.ts"),s=r(/*! ../events */"./src/events.ts"),o=r(/*! ../errors */"./src/errors.ts"),l=r(/*! ../utils/logger */"./src/utils/logger.ts"),u=r(/*! ../types/loader */"./src/types/loader.ts"),d=r(/*! ../utils/timescale-conversion */"./src/utils/timescale-conversion.ts");function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e}).apply(this,arguments)}var c=null,h=null,f=!1,g=function(){function MP4Remuxer(e,t,r,i){if(void 0===i&&(i=""),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=void 0,this._initDTS=void 0,this.nextAvcDts=null,this.nextAudioPts=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===c){var n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);c=n?parseInt(n[1]):0}if(null===h){var a=navigator.userAgent.match(/Safari\/(\d+)/i);h=a?parseInt(a[1]):0}f=!!c&&c<75||!!h&&h<600}var e=MP4Remuxer.prototype;return e.destroy=function destroy(){},e.resetTimeStamp=function resetTimeStamp(e){l.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e},e.resetNextTimestamp=function resetNextTimestamp(){l.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},e.resetInitSegment=function resetInitSegment(){l.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1},e.getVideoStartPts=function getVideoStartPts(e){var t=!1,r=e.reduce((function(e,r){var i=r.pts-e;return i<-4294967296?(t=!0,normalizePts(e,r.pts)):i>0?e:r.pts}),e[0].pts);return t&&l.logger.debug("PTS rollover detected"),r},e.remux=function remux(e,t,r,i,n,a,s,o){var d,c,h,f,g,v,p=n,m=n,y=e.pid>-1,E=t.pid>-1,T=t.samples.length,S=e.samples.length>0,b=T>1;if((!y||S)&&(!E||b)||this.ISGenerated||s){this.ISGenerated||(h=this.generateIS(e,t,n));var L=this.isVideoContiguous,A=-1;if(b&&(A=function findKeyframeIndex(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!L&&this.config.forceKeyFrameOnDiscontinuity))if(v=!0,A>0){l.logger.warn("[mp4-remuxer]: Dropped "+A+" out of "+T+" video samples due to a missing keyframe");var _=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(A),t.dropped+=A,m+=(t.samples[0].pts-_)/(t.timescale||9e4)}else-1===A&&(l.logger.warn("[mp4-remuxer]: No keyframe found out of "+T+" video samples"),v=!1);if(this.ISGenerated){if(S&&b){var D=this.getVideoStartPts(t.samples),k=(normalizePts(e.samples[0].pts,D)-D)/t.inputTimeScale;p+=Math.max(0,k),m+=Math.max(0,-k)}if(S){if(e.samplerate||(l.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n)),c=this.remuxAudio(e,p,this.isAudioContiguous,a,E||b||o===u.PlaylistLevelType.AUDIO?m:void 0),b){var C=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(l.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,n)),d=this.remuxVideo(t,m,L,C)}}else b&&(d=this.remuxVideo(t,m,L,0));d&&(d.firstKeyFrame=A,d.independent=-1!==A)}}return this.ISGenerated&&(r.samples.length&&(g=this.remuxID3(r,n)),i.samples.length&&(f=this.remuxText(i,n))),{audio:c,video:d,initSegment:h,independent:v,text:f,id3:g}},e.generateIS=function generateIS(e,t,r){var n,s,o,l=e.samples,u=t.samples,d=this.typeSupported,c={},h=!Object(i.isFiniteNumber)(this._initPTS),f="audio/mp4";if(h&&(n=s=1/0),e.config&&l.length&&(e.timescale=e.samplerate,e.isAAC||(d.mpeg?(f="audio/mpeg",e.codec=""):d.mp3&&(e.codec="mp3")),c.audio={id:"audio",container:f,codec:e.codec,initSegment:!e.isAAC&&d.mpeg?new Uint8Array(0):a.default.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(o=e.inputTimeScale,n=s=l[0].pts-Math.round(o*r))),t.sps&&t.pps&&u.length&&(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:a.default.initSegment([t]),metadata:{width:t.width,height:t.height}},h)){o=t.inputTimeScale;var g=this.getVideoStartPts(u),v=Math.round(o*r);s=Math.min(s,normalizePts(u[0].dts,g)-v),n=Math.min(n,g-v)}if(Object.keys(c).length)return this.ISGenerated=!0,h&&(this._initPTS=n,this._initDTS=s),{tracks:c,initPTS:n,timescale:o}},e.remuxVideo=function remuxVideo(e,t,r,i){var n,u,h,g=e.inputTimeScale,p=e.samples,m=[],y=p.length,E=this._initPTS,T=this.nextAvcDts,S=8,b=Number.POSITIVE_INFINITY,L=Number.NEGATIVE_INFINITY,A=0,_=!1;r&&null!==T||(T=t*g-(p[0].pts-normalizePts(p[0].dts,p[0].pts)));for(var D=0;D<y;D++){var k=p[D];if(k.pts=normalizePts(k.pts-E,T),k.dts=normalizePts(k.dts-E,T),k.dts>k.pts){A=Math.max(Math.min(A,k.pts-k.dts),-18e3)}k.dts<p[D>0?D-1:D].dts&&(_=!0)}_&&p.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),u=p[0].dts,h=p[p.length-1].dts;var C=Math.round((h-u)/(y-1));if(A<0){if(A<-2*C){l.logger.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+Object(d.toMsFromMpegTsClock)(-C,!0)+" ms");for(var R=A,P=0;P<y;P++)p[P].dts=R=Math.max(R,p[P].pts-C),p[P].pts=Math.max(R,p[P].pts)}else{l.logger.warn("PTS < DTS detected in video samples, shifting DTS by "+Object(d.toMsFromMpegTsClock)(A,!0)+" ms to overcome this issue");for(var I=0;I<y;I++)p[I].dts=p[I].dts+A}u=p[0].dts}if(r){var x=u-T,O=x>C;if(O||x<-1){O?l.logger.warn("AVC: "+Object(d.toMsFromMpegTsClock)(x,!0)+" ms ("+x+"dts) hole between fragments detected, filling it"):l.logger.warn("AVC: "+Object(d.toMsFromMpegTsClock)(-x,!0)+" ms ("+x+"dts) overlapping between fragments detected"),u=T;var w=p[0].pts-x;p[0].dts=u,p[0].pts=w,l.logger.log("Video: First PTS/DTS adjusted: "+Object(d.toMsFromMpegTsClock)(w,!0)+"/"+Object(d.toMsFromMpegTsClock)(u,!0)+", delta: "+Object(d.toMsFromMpegTsClock)(x,!0)+" ms")}}f&&(u=Math.max(0,u));for(var F=0,M=0,N=0;N<y;N++){for(var B=p[N],U=B.units,G=U.length,K=0,j=0;j<G;j++)K+=U[j].data.length;M+=K,F+=G,B.length=K,B.dts=Math.max(B.dts,u),B.pts=Math.max(B.pts,B.dts,0),b=Math.min(B.pts,b),L=Math.max(B.pts,L)}h=p[y-1].dts;var H,V=M+4*F+8;try{H=new Uint8Array(V)}catch(e){return void this.observer.emit(s.Events.ERROR,s.Events.ERROR,{type:o.ErrorTypes.MUX_ERROR,details:o.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:V,reason:"fail allocating video mdat "+V})}var W=new DataView(H.buffer);W.setUint32(0,V),H.set(a.default.types.mdat,4);for(var q=0;q<y;q++){for(var Y=p[q],X=Y.units,z=0,Q=0,$=X.length;Q<$;Q++){var J=X[Q],Z=J.data,ee=J.data.byteLength;W.setUint32(S,ee),S+=4,H.set(Z,S),S+=ee,z+=4+ee}if(q<y-1)n=p[q+1].dts-Y.dts;else{var te=this.config,re=Y.dts-p[q>0?q-1:q].dts;if(te.stretchShortVideoTrack&&null!==this.nextAudioPts){var ie=Math.floor(te.maxBufferHole*g),ne=(i?b+i*g:this.nextAudioPts)-Y.pts;ne>ie?((n=ne-re)<0&&(n=re),l.logger.log("[mp4-remuxer]: It is approximately "+ne/90+" ms to the next segment; using duration "+n/90+" ms for the last video frame.")):n=re}else n=re}var ae=Math.round(Y.pts-Y.dts);m.push(new v(Y.key,n,z,ae))}if(m.length&&c&&c<70){var se=m[0].flags;se.dependsOn=2,se.isNonSync=0}console.assert(void 0!==n,"mp4SampleDuration must be computed"),this.nextAvcDts=T=h+n,this.isVideoContiguous=!0;var oe={data1:a.default.moof(e.sequenceNumber++,u,_extends({},e,{samples:m})),data2:H,startPTS:b/g,endPTS:(L+n)/g,startDTS:u/g,endDTS:T/g,type:"video",hasAudio:!1,hasVideo:!0,nb:m.length,dropped:e.dropped};return e.samples=[],e.dropped=0,console.assert(H.length,"MDAT length must not be zero"),oe},e.remuxAudio=function remuxAudio(e,t,r,i,u){var d=e.inputTimeScale,c=d/(e.samplerate?e.samplerate:d),h=e.isAAC?1024:1152,f=h*c,g=this._initPTS,p=!e.isAAC&&this.typeSupported.mpeg,m=[],y=e.samples,E=p?0:8,T=this.nextAudioPts||-1,S=t*d;if(this.isAudioContiguous=r=r||y.length&&T>0&&(i&&Math.abs(S-T)<9e3||Math.abs(normalizePts(y[0].pts-g,S)-T)<20*f),y.forEach((function(e){e.pts=normalizePts(e.pts-g,S)})),!r||T<0){if(!(y=y.filter((function(e){return e.pts>=0}))).length)return;T=0===u?0:i?Math.max(0,S):y[0].pts}if(e.isAAC)for(var b=void 0!==u,L=this.config.maxAudioFramesDrift,A=0,_=T;A<y.length;A++){var D=y[A],k=D.pts,C=k-_,R=Math.abs(1e3*C/d);if(C<=-L*f&&b)0===A&&(l.logger.warn("Audio frame @ "+(k/d).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*C/d)+" ms."),this.nextAudioPts=T=_=k);else if(C>=L*f&&R<1e4&&b){var P=Math.round(C/f);(_=k-P*f)<0&&(P--,_+=f),0===A&&(this.nextAudioPts=T=_),l.logger.warn("[mp4-remuxer]: Injecting "+P+" audio frame @ "+(_/d).toFixed(3)+"s due to "+Math.round(1e3*C/d)+" ms gap.");for(var I=0;I<P;I++){var x=Math.max(_,0),O=n.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);O||(l.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),O=D.unit.subarray()),y.splice(A,0,{unit:O,pts:x}),_+=f,A++}}D.pts=_,_+=f}for(var w,F=null,M=null,N=0,B=y.length;B--;)N+=y[B].unit.byteLength;for(var U=0,G=y.length;U<G;U++){var K=y[U],j=K.unit,H=K.pts;if(null!==M){m[U-1].duration=Math.round((H-M)/c)}else{if(r&&e.isAAC&&(H=T),F=H,!(N>0))return;N+=E;try{w=new Uint8Array(N)}catch(e){return void this.observer.emit(s.Events.ERROR,s.Events.ERROR,{type:o.ErrorTypes.MUX_ERROR,details:o.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:N,reason:"fail allocating audio mdat "+N})}p||(new DataView(w.buffer).setUint32(0,N),w.set(a.default.types.mdat,4))}w.set(j,E);var V=j.byteLength;E+=V,m.push(new v(!0,h,V,0)),M=H}var W=m.length;if(W){var q=m[m.length-1];this.nextAudioPts=T=M+c*q.duration;var Y=p?new Uint8Array(0):a.default.moof(e.sequenceNumber++,F/c,_extends({},e,{samples:m}));e.samples=[];var X=F/d,z=T/d,Q={data1:Y,data2:w,startPTS:X,endPTS:z,startDTS:X,endDTS:z,type:"audio",hasAudio:!0,hasVideo:!1,nb:W};return this.isAudioContiguous=!0,console.assert(w.length,"MDAT length must not be zero"),Q}},e.remuxEmptyAudio=function remuxEmptyAudio(e,t,r,i){var a=e.inputTimeScale,s=a/(e.samplerate?e.samplerate:a),o=this.nextAudioPts,u=(null!==o?o:i.startDTS*a)+this._initDTS,d=i.endDTS*a+this._initDTS,c=1024*s,h=Math.ceil((d-u)/c),f=n.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(l.logger.warn("[mp4-remuxer]: remux empty Audio"),f){for(var g=[],v=0;v<h;v++){var p=u+v*c;g.push({unit:f,pts:p,dts:p})}return e.samples=g,this.remuxAudio(e,t,r,!1)}l.logger.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec")},e.remuxID3=function remuxID3(e,t){var r=e.samples.length;if(r){for(var i=e.inputTimeScale,n=this._initPTS,a=this._initDTS,s=0;s<r;s++){var o=e.samples[s];o.pts=normalizePts(o.pts-n,t*i)/i,o.dts=normalizePts(o.dts-a,t*i)/i}var l=e.samples;return e.samples=[],{samples:l}}},e.remuxText=function remuxText(e,t){var r=e.samples.length;if(r){for(var i=e.inputTimeScale,n=this._initPTS,a=0;a<r;a++){var s=e.samples[a];s.pts=normalizePts(s.pts-n,t*i)/i}e.samples.sort((function(e,t){return e.pts-t.pts}));var o=e.samples;return e.samples=[],{samples:o}}},MP4Remuxer}();function normalizePts(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}var v=function Mp4Sample(e,t,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=r,this.cts=i,this.flags=new p(e)},p=function Mp4SampleFlags(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}},"./src/remux/passthrough-remuxer.ts":
242
- /*!******************************************!*\
243
- !*** ./src/remux/passthrough-remuxer.ts ***!
244
- \******************************************/
245
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../utils/mp4-tools */"./src/utils/mp4-tools.ts"),a=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),s=r(/*! ../utils/logger */"./src/utils/logger.ts"),o=function(){function PassThroughRemuxer(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=void 0,this.initTracks=void 0,this.lastEndDTS=null}var e=PassThroughRemuxer.prototype;return e.destroy=function destroy(){},e.resetTimeStamp=function resetTimeStamp(e){this.initPTS=e,this.lastEndDTS=null},e.resetNextTimestamp=function resetNextTimestamp(){this.lastEndDTS=null},e.resetInitSegment=function resetInitSegment(e,t,r){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e),this.emitInitSegment=!0},e.generateInitSegment=function generateInitSegment(e){var t=this.audioCodec,r=this.videoCodec;if(!e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=Object(n.parseInitSegment)(e);t||(t=getParsedTrackCodec(i.audio,a.ElementaryStreamTypes.AUDIO)),r||(r=getParsedTrackCodec(i.video,a.ElementaryStreamTypes.VIDEO));var o={};i.audio&&i.video?o.audiovideo={container:"video/mp4",codec:t+","+r,initSegment:e,id:"main"}:i.audio?o.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?o.video={container:"video/mp4",codec:r,initSegment:e,id:"main"}:s.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=o},e.remux=function remux(e,t,r,a,o){var u=this.initPTS,d=this.lastEndDTS,c={audio:void 0,video:void 0,text:a,id3:r,initSegment:void 0};Object(i.isFiniteNumber)(d)||(d=this.lastEndDTS=o||0);var h=t.samples;if(!h||!h.length)return c;var f={initPTS:void 0,timescale:1},g=this.initData;if(g&&g.length||(this.generateInitSegment(h),g=this.initData),!g||!g.length)return s.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1),Object(i.isFiniteNumber)(u)||(this.initPTS=f.initPTS=u=l(g,h,d));var v=Object(n.getDuration)(h,g),p=d,m=v+p;Object(n.offsetStartDTS)(g,h,u),v>0?this.lastEndDTS=m:(s.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var y=!!g.audio,E=!!g.video,T="";y&&(T+="audio"),E&&(T+="video");var S={data1:h,startPTS:p,startDTS:p,endPTS:m,endDTS:m,type:T,hasAudio:y,hasVideo:E,nb:1,dropped:0};return c.audio="audio"===S.type?S:void 0,c.video="audio"!==S.type?S:void 0,c.text=a,c.id3=r,c.initSegment=f,c},PassThroughRemuxer}(),l=function computeInitPTS(e,t,r){return Object(n.getStartDTS)(e,t)-r};function getParsedTrackCodec(e,t){var r=null==e?void 0:e.codec;return r&&r.length>4?r:"hvc1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||t===a.ElementaryStreamTypes.VIDEO?"avc1.42e01e":"mp4a.40.5"}t.default=o},"./src/task-loop.ts":
246
- /*!**************************!*\
247
- !*** ./src/task-loop.ts ***!
248
- \**************************/
249
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return i}));var i=function(){function TaskLoop(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=TaskLoop.prototype;return e.destroy=function destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function onHandlerDestroying(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function onHandlerDestroyed(){},e.hasInterval=function hasInterval(){return!!this._tickInterval},e.hasNextTick=function hasNextTick(){return!!this._tickTimer},e.setInterval=function setInterval(e){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,e),!0)},e.clearInterval=function clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function doTick(){},TaskLoop}()},"./src/types/level.ts":
250
- /*!****************************!*\
251
- !*** ./src/types/level.ts ***!
252
- \****************************/
253
- /*! exports provided: HlsSkip, getSkipValue, HlsUrlParameters, Level */function(e,t,r){"use strict";function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var i;function getSkipValue(e,t){var r=e.canSkipUntil,n=e.canSkipDateRanges,a=e.endSN;return r&&(void 0!==t?t-a:0)<r?n?i.v2:i.Yes:i.No}r.r(t),r.d(t,"HlsSkip",(function(){return i})),r.d(t,"getSkipValue",(function(){return getSkipValue})),r.d(t,"HlsUrlParameters",(function(){return n})),r.d(t,"Level",(function(){return a})),function(e){e.No="",e.Yes="YES",e.v2="v2"}(i||(i={}));var n=function(){function HlsUrlParameters(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}return HlsUrlParameters.prototype.addDirectives=function addDirectives(e){var t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.toString()},HlsUrlParameters}(),a=function(){function Level(e){this.attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[e.url],this.attrs=e.attrs,this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter((function(e){return e})).join(",").replace(/\.[^.,]+/g,"")}return function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(Level,[{key:"maxBitrate",get:function get(){return Math.max(this.realBitrate,this.bitrate)}},{key:"uri",get:function get(){return this.url[this._urlId]||""}},{key:"urlId",get:function get(){return this._urlId},set:function set(e){var t=e%this.url.length;this._urlId!==t&&(this.details=void 0,this._urlId=t)}}]),Level}()},"./src/types/loader.ts":
254
- /*!*****************************!*\
255
- !*** ./src/types/loader.ts ***!
256
- \*****************************/
257
- /*! exports provided: PlaylistContextType, PlaylistLevelType */function(e,t,r){"use strict";var i,n;r.r(t),r.d(t,"PlaylistContextType",(function(){return i})),r.d(t,"PlaylistLevelType",(function(){return n})),function(e){e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack"}(i||(i={})),function(e){e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle"}(n||(n={}))},"./src/types/transmuxer.ts":
258
- /*!*********************************!*\
259
- !*** ./src/types/transmuxer.ts ***!
260
- \*********************************/
261
- /*! exports provided: ChunkMetadata */function(e,t,r){"use strict";r.r(t),r.d(t,"ChunkMetadata",(function(){return i}));var i=function ChunkMetadata(e,t,r,i,n,a){void 0===i&&(i=0),void 0===n&&(n=-1),void 0===a&&(a=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=i,this.part=n,this.partial=a}},"./src/utils/attr-list.ts":
262
- /*!********************************!*\
263
- !*** ./src/utils/attr-list.ts ***!
264
- \********************************/
265
- /*! exports provided: AttrList */function(e,t,r){"use strict";r.r(t),r.d(t,"AttrList",(function(){return a}));var i=/^(\d+)x(\d+)$/,n=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,a=function(){function AttrList(e){for(var t in"string"==typeof e&&(e=AttrList.parseAttrList(e)),e)e.hasOwnProperty(t)&&(this[t]=e[t])}var e=AttrList.prototype;return e.decimalInteger=function decimalInteger(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},e.hexadecimalInteger=function hexadecimalInteger(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null},e.hexadecimalIntegerAsNumber=function hexadecimalIntegerAsNumber(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},e.decimalFloatingPoint=function decimalFloatingPoint(e){return parseFloat(this[e])},e.optionalFloat=function optionalFloat(e,t){var r=this[e];return r?parseFloat(r):t},e.enumeratedString=function enumeratedString(e){return this[e]},e.bool=function bool(e){return"YES"===this[e]},e.decimalResolution=function decimalResolution(e){var t=i.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},AttrList.parseAttrList=function parseAttrList(e){var t,r={};for(n.lastIndex=0;null!==(t=n.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r},AttrList}()},"./src/utils/binary-search.ts":
266
- /*!************************************!*\
267
- !*** ./src/utils/binary-search.ts ***!
268
- \************************************/
269
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);t.default={search:function search(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null}}},"./src/utils/buffer-helper.ts":
270
- /*!************************************!*\
271
- !*** ./src/utils/buffer-helper.ts ***!
272
- \************************************/
273
- /*! exports provided: BufferHelper */function(e,t,r){"use strict";r.r(t),r.d(t,"BufferHelper",(function(){return a}));var i=r(/*! ./logger */"./src/utils/logger.ts"),n={length:0,start:function start(){return 0},end:function end(){return 0}},a=function(){function BufferHelper(){}return BufferHelper.isBuffered=function isBuffered(e,t){try{if(e)for(var r=BufferHelper.getBuffered(e),i=0;i<r.length;i++)if(t>=r.start(i)&&t<=r.end(i))return!0}catch(e){}return!1},BufferHelper.bufferInfo=function bufferInfo(e,t,r){try{if(e){var i,n=BufferHelper.getBuffered(e),a=[];for(i=0;i<n.length;i++)a.push({start:n.start(i),end:n.end(i)});return this.bufferedInfo(a,t,r)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}},BufferHelper.bufferedInfo=function bufferedInfo(e,t,r){t=Math.max(0,t),e.sort((function(e,t){var r=e.start-t.start;return r||t.end-e.end}));var i=[];if(r)for(var n=0;n<e.length;n++){var a=i.length;if(a){var s=i[a-1].end;e[n].start-s<r?e[n].end>s&&(i[a-1].end=e[n].end):i.push(e[n])}else i.push(e[n])}else i=e;for(var o,l=0,u=t,d=t,c=0;c<i.length;c++){var h=i[c].start,f=i[c].end;if(t+r>=h&&t<f)u=h,l=(d=f)-t;else if(t+r<h){o=h;break}}return{len:l,start:u||0,end:d||0,nextStart:o}},BufferHelper.getBuffered=function getBuffered(e){try{return e.buffered}catch(e){return i.logger.log("failed to get media.buffered",e),n}},BufferHelper}()},"./src/utils/cea-608-parser.ts":
274
- /*!*************************************!*\
275
- !*** ./src/utils/cea-608-parser.ts ***!
276
- \*************************************/
277
- /*! exports provided: Row, CaptionScreen, default */function(e,t,r){"use strict";r.r(t),r.d(t,"Row",(function(){return p})),r.d(t,"CaptionScreen",(function(){return m}));var i,n=r(/*! ../utils/logger */"./src/utils/logger.ts"),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},s=function getCharForByte(e){var t=e;return a.hasOwnProperty(e)&&(t=a[e]),String.fromCharCode(t)},o={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},l={17:2,18:4,21:6,22:8,23:10,19:13,20:15},u={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},d={25:2,26:4,29:6,30:8,31:10,27:13,28:15},c=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];!function(e){e[e.ERROR=0]="ERROR",e[e.TEXT=1]="TEXT",e[e.WARNING=2]="WARNING",e[e.INFO=2]="INFO",e[e.DEBUG=3]="DEBUG",e[e.DATA=3]="DATA"}(i||(i={}));var h=function(){function CaptionsLogger(){this.time=null,this.verboseLevel=i.ERROR}return CaptionsLogger.prototype.log=function log(e,t){this.verboseLevel>=e&&n.logger.log(this.time+" ["+e+"] "+t)},CaptionsLogger}(),f=function numArrayToHexArray(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},g=function(){function PenState(e,t,r,i,n){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=r||!1,this.background=i||"black",this.flash=n||!1}var e=PenState.prototype;return e.reset=function reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},e.setStyles=function setStyles(e){for(var t=["foreground","underline","italics","background","flash"],r=0;r<t.length;r++){var i=t[r];e.hasOwnProperty(i)&&(this[i]=e[i])}},e.isDefault=function isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},e.equals=function equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash},e.copy=function copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash},e.toString=function toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},PenState}(),v=function(){function StyledUnicodeChar(e,t,r,i,n,a){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new g(t,r,i,n,a)}var e=StyledUnicodeChar.prototype;return e.reset=function reset(){this.uchar=" ",this.penState.reset()},e.setChar=function setChar(e,t){this.uchar=e,this.penState.copy(t)},e.setPenState=function setPenState(e){this.penState.copy(e)},e.equals=function equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)},e.copy=function copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)},e.isEmpty=function isEmpty(){return" "===this.uchar&&this.penState.isDefault()},StyledUnicodeChar}(),p=function(){function Row(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(var t=0;t<100;t++)this.chars.push(new v);this.logger=e,this.pos=0,this.currPenState=new g}var e=Row.prototype;return e.equals=function equals(e){for(var t=!0,r=0;r<100;r++)if(!this.chars[r].equals(e.chars[r])){t=!1;break}return t},e.copy=function copy(e){for(var t=0;t<100;t++)this.chars[t].copy(e.chars[t])},e.isEmpty=function isEmpty(){for(var e=!0,t=0;t<100;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e},e.setCursor=function setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(i.DEBUG,"Negative cursor position "+this.pos),this.pos=0):this.pos>100&&(this.logger.log(i.DEBUG,"Too large cursor position "+this.pos),this.pos=100)},e.moveCursor=function moveCursor(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)},e.backSpace=function backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},e.insertChar=function insertChar(e){e>=144&&this.backSpace();var t=s(e);this.pos>=100?this.logger.log(i.ERROR,"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))},e.clearFromPos=function clearFromPos(e){var t;for(t=e;t<100;t++)this.chars[t].reset()},e.clear=function clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.clearToEndOfRow=function clearToEndOfRow(){this.clearFromPos(this.pos)},e.getTextString=function getTextString(){for(var e=[],t=!0,r=0;r<100;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")},e.setPenStyles=function setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},Row}(),m=function(){function CaptionScreen(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(var t=0;t<15;t++)this.rows.push(new p(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}var e=CaptionScreen.prototype;return e.reset=function reset(){for(var e=0;e<15;e++)this.rows[e].clear();this.currRow=14},e.equals=function equals(e){for(var t=!0,r=0;r<15;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t},e.copy=function copy(e){for(var t=0;t<15;t++)this.rows[t].copy(e.rows[t])},e.isEmpty=function isEmpty(){for(var e=!0,t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},e.backSpace=function backSpace(){this.rows[this.currRow].backSpace()},e.clearToEndOfRow=function clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()},e.insertChar=function insertChar(e){this.rows[this.currRow].insertChar(e)},e.setPen=function setPen(e){this.rows[this.currRow].setPenStyles(e)},e.moveCursor=function moveCursor(e){this.rows[this.currRow].moveCursor(e)},e.setCursor=function setCursor(e){this.logger.log(i.INFO,"setCursor: "+e),this.rows[this.currRow].setCursor(e)},e.setPAC=function setPAC(e){this.logger.log(i.INFO,"pacData = "+JSON.stringify(e));var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<15;r++)this.rows[r].clear();var n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){var s=a.rows[n].cueStartTime,o=this.logger.time;if(s&&null!==o&&s<o)for(var l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(a.rows[n+l])}}this.currRow=t;var u=this.rows[this.currRow];if(null!==e.indent){var d=e.indent,c=Math.max(d-1,0);u.setCursor(e.indent),e.color=u.chars[c].penState.foreground}var h={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(h)},e.setBkgData=function setBkgData(e){this.logger.log(i.INFO,"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)},e.setRollUpRows=function setRollUpRows(e){this.nrRollUpRows=e},e.rollUp=function rollUp(){if(null!==this.nrRollUpRows){this.logger.log(i.TEXT,this.getDisplayText());var e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(i.INFO,"Rolling up")}else this.logger.log(i.DEBUG,"roll_up but nrRollUpRows not set yet")},e.getDisplayText=function getDisplayText(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<15;n++){var a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},e.getTextAndFormat=function getTextAndFormat(){return this.rows},CaptionScreen}(),y=function(){function Cea608Channel(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new m(r),this.nonDisplayedMemory=new m(r),this.lastOutputScreen=new m(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var e=Cea608Channel.prototype;return e.reset=function reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},e.getHandler=function getHandler(){return this.outputFilter},e.setHandler=function setHandler(e){this.outputFilter=e},e.setPAC=function setPAC(e){this.writeScreen.setPAC(e)},e.setBkgData=function setBkgData(e){this.writeScreen.setBkgData(e)},e.setMode=function setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(i.INFO,"MODE="+e),"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=e)},e.insertChars=function insertChars(e){for(var t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(i.INFO,r+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(i.TEXT,"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())},e.ccRCL=function ccRCL(){this.logger.log(i.INFO,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},e.ccBS=function ccBS(){this.logger.log(i.INFO,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},e.ccAOF=function ccAOF(){},e.ccAON=function ccAON(){},e.ccDER=function ccDER(){this.logger.log(i.INFO,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},e.ccRU=function ccRU(e){this.logger.log(i.INFO,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)},e.ccFON=function ccFON(){this.logger.log(i.INFO,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},e.ccRDC=function ccRDC(){this.logger.log(i.INFO,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},e.ccTR=function ccTR(){this.logger.log(i.INFO,"TR"),this.setMode("MODE_TEXT")},e.ccRTD=function ccRTD(){this.logger.log(i.INFO,"RTD"),this.setMode("MODE_TEXT")},e.ccEDM=function ccEDM(){this.logger.log(i.INFO,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},e.ccCR=function ccCR(){this.logger.log(i.INFO,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},e.ccENM=function ccENM(){this.logger.log(i.INFO,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},e.ccEOC=function ccEOC(){if(this.logger.log(i.INFO,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(i.TEXT,"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)},e.ccTO=function ccTO(e){this.logger.log(i.INFO,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)},e.ccMIDROW=function ccMIDROW(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(i.INFO,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)},e.outputDataUpdate=function outputDataUpdate(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},e.cueSplitAtTime=function cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},Cea608Channel}(),E=function(){function Cea608Parser(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new h;this.channels=[null,new y(e,t,i),new y(e+1,r,i)],this.cmdHistory={a:null,b:null},this.logger=i}var e=Cea608Parser.prototype;return e.getHandler=function getHandler(e){return this.channels[e].getHandler()},e.setHandler=function setHandler(e,t){this.channels[e].setHandler(t)},e.addData=function addData(e,t){var r,n,a,s=!1;this.logger.time=e;for(var o=0;o<t.length;o+=2)if(n=127&t[o],a=127&t[o+1],0!==n||0!==a){if(this.logger.log(i.DATA,"["+f([t[o],t[o+1]])+"] -> ("+f([n,a])+")"),(r=this.parseCmd(n,a))||(r=this.parseMidrow(n,a)),r||(r=this.parsePAC(n,a)),r||(r=this.parseBackgroundAttributes(n,a)),!r&&(s=this.parseChars(n,a))){var l=this.currentChannel;if(l&&l>0)this.channels[l].insertChars(s);else this.logger.log(i.WARNING,"No channel found yet. TEXT-MODE?")}r||s||this.logger.log(i.WARNING,"Couldn't parse cleaned data "+f([n,a])+" orig: "+f([t[o],t[o+1]]))}},e.parseCmd=function parseCmd(e,t){var r=this.cmdHistory;if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;if(hasCmdRepeated(e,t,r))return setLastCmd(null,null,r),this.logger.log(i.DEBUG,"Repeated command ("+f([e,t])+") is dropped"),!0;var n=20===e||21===e||23===e?1:2,a=this.channels[n];return 20===e||21===e||28===e||29===e?32===t?a.ccRCL():33===t?a.ccBS():34===t?a.ccAOF():35===t?a.ccAON():36===t?a.ccDER():37===t?a.ccRU(2):38===t?a.ccRU(3):39===t?a.ccRU(4):40===t?a.ccFON():41===t?a.ccRDC():42===t?a.ccTR():43===t?a.ccRTD():44===t?a.ccEDM():45===t?a.ccCR():46===t?a.ccENM():47===t&&a.ccEOC():a.ccTO(t-32),setLastCmd(e,t,r),this.currentChannel=n,!0},e.parseMidrow=function parseMidrow(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(i.ERROR,"Mismatch channel in midrow parsing"),!1;var n=this.channels[r];return!!n&&(n.ccMIDROW(t),this.logger.log(i.DEBUG,"MIDROW ("+f([e,t])+")"),!0)}return!1},e.parsePAC=function parsePAC(e,t){var r,i=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;if(hasCmdRepeated(e,t,i))return setLastCmd(null,null,i),!0;var n=e<=23?1:2;r=t>=64&&t<=95?1===n?o[e]:u[e]:1===n?l[e]:d[e];var a=this.channels[n];return!!a&&(a.setPAC(this.interpretPAC(r,t)),setLastCmd(e,t,i),this.currentChannel=n,!0)},e.interpretPAC=function interpretPAC(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-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},e.parseChars=function parseChars(e,t){var r,n,a=null,o=null;(e>=25?(r=2,o=e-8):(r=1,o=e),o>=17&&o<=19)?(n=17===o?t+80:18===o?t+112:t+144,this.logger.log(i.INFO,"Special char '"+s(n)+"' in channel "+r),a=[n]):e>=32&&e<=127&&(a=0===t?[e]:[e,t]);if(a){var l=f(a);this.logger.log(i.DEBUG,"Char codes = "+l.join(",")),setLastCmd(e,t,this.cmdHistory)}return a},e.parseBackgroundAttributes=function parseBackgroundAttributes(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=c[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(i),setLastCmd(e,t,this.cmdHistory),!0},e.reset=function reset(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}this.cmdHistory={a:null,b:null}},e.cueSplitAtTime=function cueSplitAtTime(e){for(var t=0;t<this.channels.length;t++){var r=this.channels[t];r&&r.cueSplitAtTime(e)}},Cea608Parser}();function setLastCmd(e,t,r){r.a=e,r.b=t}function hasCmdRepeated(e,t,r){return r.a===e&&r.b===t}t.default=E},"./src/utils/codecs.ts":
278
- /*!*****************************!*\
279
- !*** ./src/utils/codecs.ts ***!
280
- \*****************************/
281
- /*! exports provided: isCodecType, isCodecSupportedInMp4 */function(e,t,r){"use strict";r.r(t),r.d(t,"isCodecType",(function(){return isCodecType})),r.d(t,"isCodecSupportedInMp4",(function(){return isCodecSupportedInMp4}));var i={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,av01:!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},text:{stpp:!0,wvtt:!0}};function isCodecType(e,t){var r=i[t];return!!r&&!0===r[e.slice(0,4)]}function isCodecSupportedInMp4(e,t){return MediaSource.isTypeSupported((t||"video")+'/mp4;codecs="'+e+'"')}},"./src/utils/cues.ts":
282
- /*!***************************!*\
283
- !*** ./src/utils/cues.ts ***!
284
- \***************************/
285
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ./vttparser */"./src/utils/vttparser.ts"),n=r(/*! ./webvtt-parser */"./src/utils/webvtt-parser.ts"),a=r(/*! ./texttrack-utils */"./src/utils/texttrack-utils.ts"),s=/\s/,o={newCue:function newCue(e,t,r,o){for(var l,u,d,c,h,f=[],g=self.VTTCue||self.TextTrackCue,v=0;v<o.rows.length;v++)if(d=!0,c=0,h="",!(l=o.rows[v]).isEmpty()){for(var p=0;p<l.chars.length;p++)s.test(l.chars[p].uchar)&&d?c++:(h+=l.chars[p].uchar,d=!1);l.cueStartTime=t,t===r&&(r+=1e-4),c>=16?c--:c++;var m=Object(i.fixLineBreaks)(h.trim()),y=Object(n.generateCueId)(t,r,m);e&&e.cues&&e.cues.getCueById(y)||((u=new g(t,r,m)).id=y,u.line=v+1,u.align="left",u.position=10+Math.min(80,10*Math.floor(8*c/32)),f.push(u))}return e&&f.length&&(f.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),f.forEach((function(t){return Object(a.addCueToTrack)(e,t)}))),f}};t.default=o},"./src/utils/discontinuities.ts":
286
- /*!**************************************!*\
287
- !*** ./src/utils/discontinuities.ts ***!
288
- \**************************************/
289
- /*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT */function(e,t,r){"use strict";r.r(t),r.d(t,"findFirstFragWithCC",(function(){return findFirstFragWithCC})),r.d(t,"shouldAlignOnDiscontinuities",(function(){return shouldAlignOnDiscontinuities})),r.d(t,"findDiscontinuousReferenceFrag",(function(){return findDiscontinuousReferenceFrag})),r.d(t,"adjustSlidingStart",(function(){return adjustSlidingStart})),r.d(t,"alignStream",(function(){return alignStream})),r.d(t,"alignPDT",(function(){return alignPDT}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./logger */"./src/utils/logger.ts"),a=r(/*! ../controller/level-helper */"./src/controller/level-helper.ts");function findFirstFragWithCC(e,t){for(var r=null,i=0,n=e.length;i<n;i++){var a=e[i];if(a&&a.cc===t){r=a;break}}return r}function shouldAlignOnDiscontinuities(e,t,r){return!(!t.details||!(r.endCC>r.startCC||e&&e.cc<r.startCC))}function findDiscontinuousReferenceFrag(e,t){var r=e.fragments,i=t.fragments;if(i.length&&r.length){var a=findFirstFragWithCC(r,i[0].cc);if(a&&(!a||a.startPTS))return a;n.logger.log("No frag in previous level to align on")}else n.logger.log("No fragments to align")}function adjustFragmentStart(e,t){if(e){var r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}function adjustSlidingStart(e,t){for(var r=t.fragments,i=0,n=r.length;i<n;i++)adjustFragmentStart(r[i],e);t.fragmentHint&&adjustFragmentStart(t.fragmentHint,e),t.alignedSliding=!0}function alignStream(e,t,r){t&&(!function alignDiscontinuities(e,t,r){if(shouldAlignOnDiscontinuities(e,r,t)){var a=findDiscontinuousReferenceFrag(r.details,t);a&&Object(i.isFiniteNumber)(a.start)&&(n.logger.log("Adjusting PTS using last level due to CC increase within current level "+t.url),adjustSlidingStart(a.start,t))}}(e,r,t),!r.alignedSliding&&t.details&&alignPDT(r,t.details),r.alignedSliding||!t.details||r.skippedSegments||Object(a.adjustSliding)(t.details,r))}function alignPDT(e,t){if(t.fragments.length&&e.hasProgramDateTime&&t.hasProgramDateTime){var r=t.fragments[0].programDateTime,a=e.fragments[0].programDateTime,s=(a-r)/1e3+t.fragments[0].start;s&&Object(i.isFiniteNumber)(s)&&(n.logger.log("Adjusting PTS using programDateTime delta "+(a-r)+"ms, sliding:"+s.toFixed(3)+" "+e.url+" "),adjustSlidingStart(s,e))}}},"./src/utils/ewma-bandwidth-estimator.ts":
290
- /*!***********************************************!*\
291
- !*** ./src/utils/ewma-bandwidth-estimator.ts ***!
292
- \***********************************************/
293
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../utils/ewma */"./src/utils/ewma.ts"),n=function(){function EwmaBandWidthEstimator(e,t,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new i.default(e),this.fast_=new i.default(t)}var e=EwmaBandWidthEstimator.prototype;return e.update=function update(e,t){var r=this.slow_,n=this.fast_;this.slow_.halfLife!==e&&(this.slow_=new i.default(e,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==t&&(this.fast_=new i.default(t,n.getEstimate(),n.getTotalWeight()))},e.sample=function sample(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.canEstimate=function canEstimate(){var e=this.fast_;return e&&e.getTotalWeight()>=this.minWeight_},e.getEstimate=function getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.destroy=function destroy(){},EwmaBandWidthEstimator}();t.default=n},"./src/utils/ewma.ts":
294
- /*!***************************!*\
295
- !*** ./src/utils/ewma.ts ***!
296
- \***************************/
297
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=function(){function EWMA(e,t,r){void 0===t&&(t=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}var e=EWMA.prototype;return e.sample=function sample(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},e.getTotalWeight=function getTotalWeight(){return this.totalWeight_},e.getEstimate=function getEstimate(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},EWMA}();t.default=i},"./src/utils/fetch-loader.ts":
298
- /*!***********************************!*\
299
- !*** ./src/utils/fetch-loader.ts ***!
300
- \***********************************/
301
- /*! exports provided: fetchSupported, default */function(e,t,r){"use strict";r.r(t),r.d(t,"fetchSupported",(function(){return fetchSupported}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ../loader/load-stats */"./src/loader/load-stats.ts"),a=r(/*! ../demux/chunk-cache */"./src/demux/chunk-cache.ts");function _wrapNativeSuper(e){var t="function"==typeof Map?new Map:void 0;return(_wrapNativeSuper=function _wrapNativeSuper(e){if(null===e||!function _isNativeFunction(e){return-1!==Function.toString.call(e).indexOf("[native code]")}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,Wrapper)}function Wrapper(){return _construct(e,arguments,_getPrototypeOf(this).constructor)}return Wrapper.prototype=Object.create(e.prototype,{constructor:{value:Wrapper,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(Wrapper,e)})(e)}function _construct(e,t,r){return(_construct=_isNativeReflectConstruct()?Reflect.construct:function _construct(e,t,r){var i=[null];i.push.apply(i,t);var n=new(Function.bind.apply(e,i));return r&&_setPrototypeOf(n,r.prototype),n}).apply(null,arguments)}function _isNativeReflectConstruct(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(e,t){return e.__proto__=t,e})(e,t)}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}var s=function(){function FetchLoader(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||getRequest,this.controller=new self.AbortController,this.stats=new n.LoadStats}var e=FetchLoader.prototype;return e.destroy=function destroy(){this.loader=this.callbacks=null,this.abortInternal()},e.abortInternal=function abortInternal(){var e=this.response;e&&e.ok||(this.stats.aborted=!0,this.controller.abort())},e.abort=function abort(){var e;this.abortInternal(),null!==(e=this.callbacks)&&void 0!==e&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function load(e,t,r){var n=this,a=this.stats;if(a.loading.start)throw new Error("Loader can only be used once.");a.loading.start=self.performance.now();var s=function getRequestParameters(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t};e.rangeEnd&&(r.headers=new self.Headers({Range:"bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)}));return r}(e,this.controller.signal),l=r.onProgress,u="arraybuffer"===e.responseType,d=u?"byteLength":"length";this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout((function(){n.abortInternal(),r.onTimeout(a,e,n.response)}),t.timeout),self.fetch(this.request).then((function(r){if(n.response=n.loader=r,!r.ok){var s=r.status,d=r.statusText;throw new o(d||"fetch, bad network response",s,r)}return a.loading.first=Math.max(self.performance.now(),a.loading.start),a.total=parseInt(r.headers.get("Content-Length")||"0"),l&&Object(i.isFiniteNumber)(t.highWaterMark)?n.loadProgressively(r,a,e,t.highWaterMark,l):u?r.arrayBuffer():r.text()})).then((function(s){var o=n.response;self.clearTimeout(n.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first),a.loaded=a.total=s[d];var u={url:o.url,data:s};l&&!Object(i.isFiniteNumber)(t.highWaterMark)&&l(a,e,s,o),r.onSuccess(u,a,e,o)})).catch((function(t){if(self.clearTimeout(n.requestTimeout),!a.aborted){var i=t.code||0;r.onError({code:i,text:t.message},e,t.details)}}))},e.getCacheAge=function getCacheAge(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},e.loadProgressively=function loadProgressively(e,t,r,i,n){void 0===i&&(i=0);var s=new a.default,o=e.body.getReader();return function pump(){return o.read().then((function(a){if(a.done)return s.dataLength&&n(t,r,s.flush(),e),Promise.resolve(new ArrayBuffer(0));var o=a.value,l=o.length;return t.loaded+=l,l<i||s.dataLength?(s.push(o),s.dataLength>=i&&n(t,r,s.flush(),e)):n(t,r,o,e),pump()})).catch((function(){return Promise.reject()}))}()},FetchLoader}();function getRequest(e,t){return new self.Request(e.url,t)}var o=function(e){function FetchError(t,r,i){var n;return(n=e.call(this,t)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}(FetchError,e),FetchError}(_wrapNativeSuper(Error));t.default=s},"./src/utils/imsc1-ttml-parser.ts":
302
- /*!****************************************!*\
303
- !*** ./src/utils/imsc1-ttml-parser.ts ***!
304
- \****************************************/
305
- /*! exports provided: IMSC1_CODEC, parseIMSC1 */function(e,t,r){"use strict";r.r(t),r.d(t,"IMSC1_CODEC",(function(){return u})),r.d(t,"parseIMSC1",(function(){return parseIMSC1}));var i=r(/*! ./mp4-tools */"./src/utils/mp4-tools.ts"),n=r(/*! ./vttparser */"./src/utils/vttparser.ts"),a=r(/*! ./vttcue */"./src/utils/vttcue.ts"),s=r(/*! ../demux/id3 */"./src/demux/id3.ts"),o=r(/*! ./timescale-conversion */"./src/utils/timescale-conversion.ts"),l=r(/*! ./webvtt-parser */"./src/utils/webvtt-parser.ts");function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e}).apply(this,arguments)}var u="stpp.ttml.im1t",d=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,c=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,h={left:"start",center:"center",right:"end",start:"start",end:"end"};function parseIMSC1(e,t,r,n,u){var d=Object(i.findBox)(new Uint8Array(e),["mdat"]);if(0!==d.length){var c=d[0],f=Object(s.utf8ArrayToStr)(new Uint8Array(e,c.start,c.end-c.start)),g=Object(o.toTimescaleFromScale)(t,1,r);try{n(function parseTTML(e,t){var r=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");var i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(i).reduce((function(e,t){return e[t]=r.getAttribute("ttp:"+t)||i[t],e}),{}),s="preserve"!==r.getAttribute("xml:space"),o=collectionToDictionary(getElementCollection(r,"styling","style")),u=collectionToDictionary(getElementCollection(r,"layout","region")),d=getElementCollection(r,"body","[begin]");return[].map.call(d,(function(e){var r=function getTextContent(e,t){return[].slice.call(e.childNodes).reduce((function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!==(n=r.childNodes)&&void 0!==n&&n.length?getTextContent(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=parseTtmlTime(e.getAttribute("begin"),n),d=parseTtmlTime(e.getAttribute("dur"),n),c=parseTtmlTime(e.getAttribute("end"),n);if(null===i)throw timestampParsingError(e);if(null===c){if(null===d)throw timestampParsingError(e);c=i+d}var f=new a.default(i-t,c-t,r);f.id=Object(l.generateCueId)(f.startTime,f.endTime,f.text);var g=u[e.getAttribute("region")],v=o[e.getAttribute("style")];f.position=10,f.size=80;var p=function getTtmlStyles(e,t){var r="http://www.w3.org/ns/ttml#styling";return["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((function(i,n){var a=getAttributeNS(t,r,n)||getAttributeNS(e,r,n);return a&&(i[n]=a),i}),{})}(g,v),m=p.textAlign;if(m){var y=h[m];y&&(f.lineAlign=y),f.align=m}return _extends(f,p),f})).filter((function(e){return null!==e}))}(f,g))}catch(e){u(e)}}else u(new Error("Could not parse IMSC1 mdat"))}function getElementCollection(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function collectionToDictionary(e){return e.reduce((function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function getAttributeNS(e,t,r){return e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function timestampParsingError(e){return new Error("Could not parse ttml timestamp "+e)}function parseTtmlTime(e,t){if(!e)return null;var r=Object(n.parseTimeStamp)(e);return null===r&&(d.test(e)?r=function parseHoursMinutesSecondsFrames(e,t){var r=d.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):c.test(e)&&(r=function parseTimeUnits(e,t){var r=c.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}},"./src/utils/logger.ts":
306
- /*!*****************************!*\
307
- !*** ./src/utils/logger.ts ***!
308
- \*****************************/
309
- /*! exports provided: enableLogs, logger */function(e,t,r){"use strict";r.r(t),r.d(t,"enableLogs",(function(){return enableLogs})),r.d(t,"logger",(function(){return s}));var i=function noop(){},n={trace:i,debug:i,log:i,warn:i,info:i,error:i},a=n;function consolePrintFn(e){var t=self.console[e];return t?t.bind(self.console,"["+e+"] >"):i}function enableLogs(e){if(self.console&&!0===e||"object"==typeof e){!function exportLoggerFunctions(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];r.forEach((function(t){a[t]=e[t]?e[t].bind(e):consolePrintFn(t)}))}(e,"debug","log","info","warn","error");try{a.log()}catch(e){a=n}}else a=n}var s=n},"./src/utils/mediakeys-helper.ts":
310
- /*!***************************************!*\
311
- !*** ./src/utils/mediakeys-helper.ts ***!
312
- \***************************************/
313
- /*! exports provided: KeySystems, requestMediaKeySystemAccess */function(e,t,r){"use strict";var i;r.r(t),r.d(t,"KeySystems",(function(){return i})),r.d(t,"requestMediaKeySystemAccess",(function(){return n})),function(e){e.WIDEVINE="com.widevine.alpha",e.PLAYREADY="com.microsoft.playready"}(i||(i={}));var n="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null},"./src/utils/mediasource-helper.ts":
314
- /*!*****************************************!*\
315
- !*** ./src/utils/mediasource-helper.ts ***!
316
- \*****************************************/
317
- /*! exports provided: getMediaSource */function(e,t,r){"use strict";function getMediaSource(){return self.MediaSource||self.WebKitMediaSource}r.r(t),r.d(t,"getMediaSource",(function(){return getMediaSource}))},"./src/utils/mp4-tools.ts":
318
- /*!********************************!*\
319
- !*** ./src/utils/mp4-tools.ts ***!
320
- \********************************/
321
- /*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */function(e,t,r){"use strict";r.r(t),r.d(t,"bin2str",(function(){return bin2str})),r.d(t,"readUint16",(function(){return readUint16})),r.d(t,"readUint32",(function(){return readUint32})),r.d(t,"writeUint32",(function(){return writeUint32})),r.d(t,"findBox",(function(){return findBox})),r.d(t,"parseSegmentIndex",(function(){return parseSegmentIndex})),r.d(t,"parseInitSegment",(function(){return parseInitSegment})),r.d(t,"getStartDTS",(function(){return getStartDTS})),r.d(t,"getDuration",(function(){return getDuration})),r.d(t,"computeRawDurationFromSamples",(function(){return computeRawDurationFromSamples})),r.d(t,"offsetStartDTS",(function(){return offsetStartDTS})),r.d(t,"segmentValidRange",(function(){return segmentValidRange})),r.d(t,"appendUint8Array",(function(){return appendUint8Array}));var i=r(/*! ./typed-array */"./src/utils/typed-array.ts"),n=r(/*! ../loader/fragment */"./src/loader/fragment.ts"),a=Math.pow(2,32)-1,s=[].push;function bin2str(e){return String.fromCharCode.apply(null,e)}function readUint16(e,t){"data"in e&&(t+=e.start,e=e.data);var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function readUint32(e,t){"data"in e&&(t+=e.start,e=e.data);var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r}function writeUint32(e,t,r){"data"in e&&(t+=e.start,e=e.data),e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function findBox(e,t){var r,i,n,a=[];if(!t.length)return a;"data"in e?(r=e.data,i=e.start,n=e.end):(i=0,n=(r=e).byteLength);for(var o=i;o<n;){var l=readUint32(r,o),u=l>1?o+l:n;if(bin2str(r.subarray(o+4,o+8))===t[0])if(1===t.length)a.push({data:r,start:o+8,end:u});else{var d=findBox({data:r,start:o+8,end:u},t.slice(1));d.length&&s.apply(a,d)}o=u}return a}function parseSegmentIndex(e){var t=findBox(e,["moov"])[0],r=t?t.end:null,i=findBox(e,["sidx"]);if(!i||!i[0])return null;var n=[],a=i[0],s=a.data[0],o=0===s?8:16,l=readUint32(a,o);o+=4;o+=0===s?8:16,o+=2;var u=a.end+0,d=readUint16(a,o);o+=2;for(var c=0;c<d;c++){var h=o,f=readUint32(a,h);h+=4;var g=2147483647&f;if(1===(2147483648&f)>>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var v=readUint32(a,h);h+=4,n.push({referenceSize:g,subsegmentDuration:v,info:{duration:v/l,start:u,end:u+g-1}}),u+=g,o=h+=4}return{earliestPresentationTime:0,timescale:l,version:s,referencesCount:d,references:n,moovEndOffset:r}}function parseInitSegment(e){for(var t=[],r=findBox(e,["moov","trak"]),i=0;i<r.length;i++){var a=r[i],s=findBox(a,["tkhd"])[0];if(s){var o=s.data[s.start],l=0===o?12:20,u=readUint32(s,l),d=findBox(a,["mdia","mdhd"])[0];if(d){var c=readUint32(d,l=0===(o=d.data[d.start])?12:20),h=findBox(a,["mdia","hdlr"])[0];if(h){var f=bin2str(h.data.subarray(h.start+8,h.start+12)),g={soun:n.ElementaryStreamTypes.AUDIO,vide:n.ElementaryStreamTypes.VIDEO}[f];if(g){var v=findBox(a,["mdia","minf","stbl","stsd"])[0],p=void 0;v&&(p=bin2str(v.data.subarray(v.start+12,v.start+16))),t[u]={timescale:c,type:g},t[g]={timescale:c,id:u,codec:p}}}}}}return findBox(e,["moov","mvex","trex"]).forEach((function(e){var r=readUint32(e,4),i=t[r];i&&(i.default={duration:readUint32(e,12),flags:readUint32(e,20)})})),t}function getStartDTS(e,t){return findBox(t,["moof","traf"]).reduce((function(t,r){var i=findBox(r,["tfdt"])[0],n=i.data[i.start],a=findBox(r,["tfhd"]).reduce((function(t,r){var a=readUint32(r,4),s=e[a];if(s){var o=readUint32(i,4);1===n&&(o*=Math.pow(2,32),o+=readUint32(i,8));var l=o/(s.timescale||9e4);if(isFinite(l)&&(null===t||l<t))return l}return t}),null);return null!==a&&isFinite(a)&&(null===t||a<t)?a:t}),null)||0}function getDuration(e,t){for(var r=0,i=0,a=0,s=findBox(e,["moof","traf"]),o=0;o<s.length;o++){var l=s[o],u=findBox(l,["tfhd"])[0],d=t[readUint32(u,4)];if(d){var c=d.default,h=readUint32(u,0)|(null==c?void 0:c.flags),f=null==c?void 0:c.duration;8&h&&(f=readUint32(u,2&h?12:8));for(var g=d.timescale||9e4,v=findBox(l,["trun"]),p=0;p<v.length;p++){if(f)r=f*readUint32(v[p],4);else r=computeRawDurationFromSamples(v[p]);d.type===n.ElementaryStreamTypes.VIDEO?i+=r/g:d.type===n.ElementaryStreamTypes.AUDIO&&(a+=r/g)}}}if(0===i&&0===a){var m=parseSegmentIndex(e);if(null!=m&&m.references)return m.references.reduce((function(e,t){return e+t.info.duration||0}),0)}return i||a}function computeRawDurationFromSamples(e){var t=readUint32(e,0),r=8;1&t&&(r+=4),4&t&&(r+=4);for(var i=0,n=readUint32(e,4),a=0;a<n;a++){if(256&t)i+=readUint32(e,r),r+=4;512&t&&(r+=4),1024&t&&(r+=4),2048&t&&(r+=4)}return i}function offsetStartDTS(e,t,r){findBox(t,["moof","traf"]).forEach((function(t){findBox(t,["tfhd"]).forEach((function(i){var n=readUint32(i,4),s=e[n];if(s){var o=s.timescale||9e4;findBox(t,["tfdt"]).forEach((function(e){var t=e.data[e.start],i=readUint32(e,4);if(0===t)writeUint32(e,4,i-r*o);else{i*=Math.pow(2,32),i+=readUint32(e,8),i-=r*o,i=Math.max(i,0);var n=Math.floor(i/(a+1)),s=Math.floor(i%(a+1));writeUint32(e,4,n),writeUint32(e,8,s)}}))}}))}))}function segmentValidRange(e){var t={valid:null,remainder:null},r=findBox(e,["moof"]);if(!r)return t;if(r.length<2)return t.remainder=e,t;var n=r[r.length-1];return t.valid=Object(i.sliceUint8)(e,0,n.start-8),t.remainder=Object(i.sliceUint8)(e,n.start-8),t}function appendUint8Array(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}},"./src/utils/output-filter.ts":
322
- /*!************************************!*\
323
- !*** ./src/utils/output-filter.ts ***!
324
- \************************************/
325
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return i}));var i=function(){function OutputFilter(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}var e=OutputFilter.prototype;return e.dispatchCue=function dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},e.newCue=function newCue(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function reset(){this.cueRanges=[]},OutputFilter}()},"./src/utils/texttrack-utils.ts":
326
- /*!**************************************!*\
327
- !*** ./src/utils/texttrack-utils.ts ***!
328
- \**************************************/
329
- /*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */function(e,t,r){"use strict";r.r(t),r.d(t,"sendAddTrackEvent",(function(){return sendAddTrackEvent})),r.d(t,"addCueToTrack",(function(){return addCueToTrack})),r.d(t,"clearCurrentCues",(function(){return clearCurrentCues})),r.d(t,"removeCuesInRange",(function(){return removeCuesInRange})),r.d(t,"getCuesInRange",(function(){return getCuesInRange}));var i=r(/*! ./logger */"./src/utils/logger.ts");function sendAddTrackEvent(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function addCueToTrack(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(r){i.logger.debug("[texttrack-utils]: "+r);var n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}"disabled"===r&&(e.mode=r)}function clearCurrentCues(e){var t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)e.removeCue(e.cues[r]);"disabled"===t&&(e.mode=t)}function removeCuesInRange(e,t,r){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var n=getCuesInRange(e.cues,t,r),a=0;a<n.length;a++)e.removeCue(n[a]);"disabled"===i&&(e.mode=i)}function getCuesInRange(e,t,r){var i=[],n=function getFirstCueIndexAfterTime(e,t){if(t<e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;for(var i=0,n=r;i<=n;){var a=Math.floor((n+i)/2);if(t<e[a].startTime)n=a-1;else{if(!(t>e[a].startTime&&i<r))return a;i=a+1}}return e[i].startTime-t<t-e[n].startTime?i:n}(e,t);if(n>-1)for(var a=n,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}},"./src/utils/time-ranges.ts":
330
- /*!**********************************!*\
331
- !*** ./src/utils/time-ranges.ts ***!
332
- \**********************************/
333
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);t.default={toString:function toString(e){for(var t="",r=e.length,i=0;i<r;i++)t+="["+e.start(i).toFixed(3)+","+e.end(i).toFixed(3)+"]";return t}}},"./src/utils/timescale-conversion.ts":
334
- /*!*******************************************!*\
335
- !*** ./src/utils/timescale-conversion.ts ***!
336
- \*******************************************/
337
- /*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */function(e,t,r){"use strict";r.r(t),r.d(t,"toTimescaleFromBase",(function(){return toTimescaleFromBase})),r.d(t,"toTimescaleFromScale",(function(){return toTimescaleFromScale})),r.d(t,"toMsFromMpegTsClock",(function(){return toMsFromMpegTsClock})),r.d(t,"toMpegTsClockFromTimescale",(function(){return toMpegTsClockFromTimescale}));function toTimescaleFromBase(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=e*t*r;return i?Math.round(n):n}function toTimescaleFromScale(e,t,r,i){return void 0===r&&(r=1),void 0===i&&(i=!1),toTimescaleFromBase(e,t,1/r,i)}function toMsFromMpegTsClock(e,t){return void 0===t&&(t=!1),toTimescaleFromBase(e,1e3,1/9e4,t)}function toMpegTsClockFromTimescale(e,t){return void 0===t&&(t=1),toTimescaleFromBase(e,9e4,1/t)}},"./src/utils/typed-array.ts":
338
- /*!**********************************!*\
339
- !*** ./src/utils/typed-array.ts ***!
340
- \**********************************/
341
- /*! exports provided: sliceUint8 */function(e,t,r){"use strict";function sliceUint8(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}r.r(t),r.d(t,"sliceUint8",(function(){return sliceUint8}))},"./src/utils/vttcue.ts":
342
- /*!*****************************!*\
343
- !*** ./src/utils/vttcue.ts ***!
344
- \*****************************/
345
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t),t.default=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function isAllowedValue(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function findAlignSetting(e){return isAllowedValue(t,e)}function extend(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var s in a)e[s]=a[s]}return e}function VTTCue(t,r,i){var n=this,a={enumerable:!0};n.hasBeenReset=!1;var s="",o=!1,l=t,u=r,d=i,c=null,h="",f=!0,g="auto",v="start",p=50,m="middle",y=50,E="middle";Object.defineProperty(n,"id",extend({},a,{get:function get(){return s},set:function set(e){s=""+e}})),Object.defineProperty(n,"pauseOnExit",extend({},a,{get:function get(){return o},set:function set(e){o=!!e}})),Object.defineProperty(n,"startTime",extend({},a,{get:function get(){return l},set:function set(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");l=e,this.hasBeenReset=!0}})),Object.defineProperty(n,"endTime",extend({},a,{get:function get(){return u},set:function set(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(n,"text",extend({},a,{get:function get(){return d},set:function set(e){d=""+e,this.hasBeenReset=!0}})),Object.defineProperty(n,"region",extend({},a,{get:function get(){return c},set:function set(e){c=e,this.hasBeenReset=!0}})),Object.defineProperty(n,"vertical",extend({},a,{get:function get(){return h},set:function set(t){var r=function findDirectionSetting(t){return isAllowedValue(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");h=r,this.hasBeenReset=!0}})),Object.defineProperty(n,"snapToLines",extend({},a,{get:function get(){return f},set:function set(e){f=!!e,this.hasBeenReset=!0}})),Object.defineProperty(n,"line",extend({},a,{get:function get(){return g},set:function set(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");g=e,this.hasBeenReset=!0}})),Object.defineProperty(n,"lineAlign",extend({},a,{get:function get(){return v},set:function set(e){var t=findAlignSetting(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(n,"position",extend({},a,{get:function get(){return p},set:function set(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(n,"positionAlign",extend({},a,{get:function get(){return m},set:function set(e){var t=findAlignSetting(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");m=t,this.hasBeenReset=!0}})),Object.defineProperty(n,"size",extend({},a,{get:function get(){return y},set:function set(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(n,"align",extend({},a,{get:function get(){return E},set:function set(e){var t=findAlignSetting(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),n.displayState=void 0}return VTTCue.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},VTTCue}()},"./src/utils/vttparser.ts":
346
- /*!********************************!*\
347
- !*** ./src/utils/vttparser.ts ***!
348
- \********************************/
349
- /*! exports provided: parseTimeStamp, fixLineBreaks, VTTParser */function(e,t,r){"use strict";r.r(t),r.d(t,"parseTimeStamp",(function(){return parseTimeStamp})),r.d(t,"fixLineBreaks",(function(){return fixLineBreaks})),r.d(t,"VTTParser",(function(){return l}));var i=r(/*! ./vttcue */"./src/utils/vttcue.ts"),n=function(){function StringDecoder(){}return StringDecoder.prototype.decode=function decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},StringDecoder}();function parseTimeStamp(e){function computeSeconds(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var t=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?computeSeconds(t[2],t[3],0,t[4]):computeSeconds(t[1],t[2],t[3],t[4]):null}var a=function(){function Settings(){this.values=Object.create(null)}var e=Settings.prototype;return e.set=function set(e,t){this.get(e)||""===t||(this.values[e]=t)},e.get=function get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},e.has=function has(e){return e in this.values},e.alt=function alt(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}},e.integer=function integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))},e.percent=function percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var percent=parseFloat(t);if(percent>=0&&percent<=100)return this.set(e,percent),!0}return!1},Settings}();function parseOptions(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);if(2===s.length)t(s[0],s[1])}}var s=new i.default(0,0,""),o="middle"===s.align?"middle":"center";function parseCue(e,t,r){var i=e;function consumeTimeStamp(){var t=parseTimeStamp(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function skipWhitespace(){e=e.replace(/^\s+/,"")}if(skipWhitespace(),t.startTime=consumeTimeStamp(),skipWhitespace(),"--\x3e"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.substr(3),skipWhitespace(),t.endTime=consumeTimeStamp(),skipWhitespace(),function consumeCueSettings(e,t){var i=new a;parseOptions(e,(function(e,t){var n;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",o,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",o,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",o,"end","left","right"])}}),/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===s.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",o);var l=i.get("position","auto");"auto"===l&&50===s.position&&(l="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=l}(e,t)}function fixLineBreaks(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var l=function(){function VTTParser(){this.state="INITIAL",this.buffer="",this.decoder=new n,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=VTTParser.prototype;return e.parse=function parse(e){var t=this;function collectNextLine(){var e=t.buffer,r=0;for(e=fixLineBreaks(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.substr(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.substr(r),i}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var r="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var n=(r=collectNextLine()).match(/^()?WEBVTT([ \t].*)?$/);if(!n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var a=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=collectNextLine(),t.state){case"HEADER":/:/.test(r)?parseOptions(r,(function(e,t){}),/:/):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new i.default(0,0,""),t.state="CUE",-1===r.indexOf("--\x3e")){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{parseCue(r,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var s=-1!==r.indexOf("--\x3e");if(!r||s&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=r;continue;case"BADCUE":r||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},e.flush=function flush(){try{if((this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state||"BADWEBVTT"===this.state)throw new Error("Malformed WebVTT signature.")}catch(e){this.onparsingerror&&this.onparsingerror(e)}return this.onflush&&this.onflush(),this},VTTParser}()},"./src/utils/webvtt-parser.ts":
350
- /*!************************************!*\
351
- !*** ./src/utils/webvtt-parser.ts ***!
352
- \************************************/
353
- /*! exports provided: generateCueId, parseWebVTT */function(e,t,r){"use strict";r.r(t),r.d(t,"generateCueId",(function(){return generateCueId})),r.d(t,"parseWebVTT",(function(){return parseWebVTT}));var i=r(/*! ./src/polyfills/number */"./src/polyfills/number.ts"),n=r(/*! ./vttparser */"./src/utils/vttparser.ts"),a=r(/*! ../demux/id3 */"./src/demux/id3.ts"),s=r(/*! ./timescale-conversion */"./src/utils/timescale-conversion.ts"),o=r(/*! ../remux/mp4-remuxer */"./src/remux/mp4-remuxer.ts"),l=/\r\n|\n\r|\n|\r/g,u=function startsWith(e,t,r){return void 0===r&&(r=0),e.substr(r,t.length)===t},d=function hash(e){for(var hash=5381,t=e.length;t;)hash=33*hash^e.charCodeAt(--t);return(hash>>>0).toString()};function generateCueId(e,t,r){return d(e.toString())+d(t.toString())+d(r)}function parseWebVTT(e,t,r,d,c,h,f,g){var v,p=new n.VTTParser,m=Object(a.utf8ArrayToStr)(new Uint8Array(e)).trim().replace(l,"\n").split("\n"),y=[],E=Object(s.toMpegTsClockFromTimescale)(t,r),T="00:00.000",S=0,b=0,L=!0,A=!1;p.oncue=function(e){var t=d[c],r=d.ccOffset,i=(S-E)/9e4;if(null!=t&&t.new&&(void 0!==b?r=d.ccOffset=t.start:function calculateOffset(e,t,r){var i=e[t],n=e[i.prevCC];if(!n||!n.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!==(a=n)&&void 0!==a&&a.new;){var a;e.ccOffset+=i.start-n.start,i.new=!1,n=e[(i=n).prevCC]}e.presentationOffset=r}(d,c,i)),i&&(r=i-d.presentationOffset),A){var n=e.endTime-e.startTime,a=Object(o.normalizePts)(9e4*(e.startTime+r-b),9e4*h)/9e4;e.startTime=a,e.endTime=a+n}var s=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(s)),e.id||(e.id=generateCueId(e.startTime,e.endTime,s)),e.endTime>0&&y.push(e)},p.onparsingerror=function(e){v=e},p.onflush=function(){v?g(v):f(y)},m.forEach((function(e){if(L){if(u(e,"X-TIMESTAMP-MAP=")){L=!1,A=!0,e.substr(16).split(",").forEach((function(e){u(e,"LOCAL:")?T=e.substr(6):u(e,"MPEGTS:")&&(S=parseInt(e.substr(7)))}));try{b=function cueString2millis(e){var t=parseInt(e.substr(-3)),r=parseInt(e.substr(-6,2)),n=parseInt(e.substr(-9,2)),a=e.length>9?parseInt(e.substr(0,e.indexOf(":"))):0;if(!(Object(i.isFiniteNumber)(t)&&Object(i.isFiniteNumber)(r)&&Object(i.isFiniteNumber)(n)&&Object(i.isFiniteNumber)(a)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*r,t+=6e4*n,t+=36e5*a}(T)/1e3}catch(e){A=!1,v=e}return}""===e&&(L=!1)}p.parse(e+"\n")})),p.flush()}},"./src/utils/xhr-loader.ts":
354
- /*!*********************************!*\
355
- !*** ./src/utils/xhr-loader.ts ***!
356
- \*********************************/
357
- /*! exports provided: default */function(e,t,r){"use strict";r.r(t);var i=r(/*! ../utils/logger */"./src/utils/logger.ts"),n=r(/*! ../loader/load-stats */"./src/loader/load-stats.ts"),a=/^age:\s*[\d.]+\s*$/m,s=function(){function XhrLoader(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e?e.xhrSetup:null,this.stats=new n.LoadStats,this.retryDelay=0}var e=XhrLoader.prototype;return e.destroy=function destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},e.abortInternal=function abortInternal(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},e.abort=function abort(){var e;this.abortInternal(),null!==(e=this.callbacks)&&void 0!==e&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.retryDelay=t.retryDelay,this.loadInternal()},e.loadInternal=function loadInternal(){var e=this.config,t=this.context;if(e){var r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;var n=this.xhrSetup;try{if(n)try{n(r,t.url)}catch(e){r.open("GET",t.url,!0),n(r,t.url)}r.readyState||r.open("GET",t.url,!0)}catch(e){return void this.callbacks.onError({code:r.status,text:e.message},t,r)}t.rangeEnd&&r.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),r.onreadystatechange=this.readystatechange.bind(this),r.onprogress=this.loadprogress.bind(this),r.responseType=t.responseType,self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),e.timeout),r.send()}},e.readystatechange=function readystatechange(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var n=t.readyState,a=this.config;if(!r.aborted&&n>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===n){t.onreadystatechange=null,t.onprogress=null;var s=t.status;if(s>=200&&s<300){var o,l;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),l="arraybuffer"===e.responseType?(o=t.response).byteLength:(o=t.responseText).length,r.loaded=r.total=l,!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,e,o,t),!this.callbacks)return;var d={url:t.responseURL,data:o};this.callbacks.onSuccess(d,r,e,t)}else r.retry>=a.maxRetry||s>=400&&s<499?(i.logger.error(s+" while loading "+e.url),this.callbacks.onError({code:s,text:t.statusText},e,t)):(i.logger.warn(s+" while loading "+e.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,a.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.timeout)}},e.loadtimeout=function loadtimeout(){i.logger.warn("timeout while loading "+this.context.url);var e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))},e.loadprogress=function loadprogress(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},e.getCacheAge=function getCacheAge(){var e=null;if(this.loader&&a.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},XhrLoader}();t.default=s}}).default}))}}]);