!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(self,(()=>(()=>{var e={204:e=>{"use strict";var t,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function n(){n.init.call(this)}e.exports=n,e.exports.once=function(e,t){return new Promise((function(r,i){function s(r){e.removeListener(t,n),i(r)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",s),r([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&p(e,"error",t,r)}(e,s,{once:!0})}))},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function h(e,t,r,i){var s,n,a,h;if(o(r),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),a=n[t]),void 0===a)a=n[t]=r,++e._eventsCount;else if("function"==typeof a?a=n[t]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),(s=l(e))>0&&a.length>s&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,h=u,console&&console.warn&&console.warn(h)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function c(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},s=u.bind(i);return s.listener=r,i.wrapFn=s,s}function d(e,t,r){var i=e._events;if(void 0===i)return[];var s=i[t];return void 0===s?[]:"function"==typeof s?r?[s.listener||s]:[s]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var l=n[e];if(void 0===l)return!1;if("function"==typeof l)i(l,this,t);else{var h=l.length,u=g(l,h);for(r=0;r=0;n--)if(r[n]===t||r[n].listener===t){a=r[n].listener,s=n;break}if(s<0)return this;0===s?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},n.prototype.listeners=function(e){return d(this,e,!0)},n.prototype.rawListeners=function(e){return d(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},n.prototype.listenerCount=f,n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},305:function(e){var t;"undefined"!=typeof window&&(t=function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var s=t[i]={i,l:!1,exports:{}};return e[i].call(s.exports,s,s.exports,r),s.l=!0,s.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)r.d(i,s,function(t){return e[t]}.bind(null,s));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/dist/",r(r.s="./src/hls.ts")}({"./node_modules/eventemitter3/index.js":function(e,t,r){"use strict";var i=Object.prototype.hasOwnProperty,s="~";function n(){}function a(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,r,i,n){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new a(r,i||e,n),l=s?s+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function l(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function h(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(s=!1)),h.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(s?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},h.prototype.listeners=function(e){var t=s?s+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,n=r.length,a=new Array(n);i0}),!1)}e.exports=function(e,t){t=t||{};var s={main:r.m},n=t.all?{main:Object.keys(s.main)}:function(e,t){for(var r={main:[t]},i={main:[]},s={main:{}};l(r);)for(var n=Object.keys(r),a=0;a=2*c/f||E<=T)){var b,_=Number.POSITIVE_INFINITY;for(b=e.level-1;b>p&&!((_=c*g[b].maxBitrate/(6.4*y))=E)){var L=this.bwEstimator.getEstimate();h.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)(L)?(L/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: "+_.toFixed(3)+" s\n Time to underbuffer: "+T.toFixed(3)+" s"),r.nextLoadLevel=b,this.bwEstimator.sample(d,u.loaded),this.clearTimer(),e.loader&&(this.fragCurrent=this.partCurrent=null,e.loader.abort()),r.trigger(n.Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:u})}}}}}},d.onFragLoaded=function(e,t){var r=t.frag,s=t.part;if(r.type===l.PlaylistLevelType.MAIN&&Object(i.isFiniteNumber)(r.sn)){var a=s?s.stats:r.stats,o=s?s.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var h=this.hls.levels[r.level],u=(h.loaded?h.loaded.bytes:0)+a.loaded,c=(h.loaded?h.loaded.duration:0)+o;h.loaded={bytes:u,duration:c},h.realBitrate=Math.round(8*u/c)}if(r.bitrateTest){var d={stats:a,frag:r,part:s,id:r.type};this.onFragBuffered(n.Events.FRAG_BUFFERED,d),r.bitrateTest=!1}}},d.onFragBuffered=function(e,t){var r=t.frag,i=t.part,s=i?i.stats:r.stats;if(!s.aborted&&r.type===l.PlaylistLevelType.MAIN&&"initSegment"!==r.sn){var n=s.parsing.end-s.loading.start;this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},d.onError=function(e,t){switch(t.details){case o.ErrorDetails.FRAG_LOAD_ERROR:case o.ErrorDetails.FRAG_LOAD_TIMEOUT:this.clearTimer()}},d.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},d.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls,i=r.maxAutoLevel,s=r.config,n=r.minAutoLevel,o=r.media,l=t?t.duration:e?e.duration:0,u=o?o.currentTime:0,c=o&&0!==o.playbackRate?Math.abs(o.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,f=(a.BufferHelper.bufferInfo(o,u,s.maxBufferHole).end-u)/c,g=this.findBestLevel(d,n,i,f,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(g>=0)return g;h.logger.trace((f?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var p=l?Math.min(l,s.maxStarvationDelay):s.maxStarvationDelay,v=s.abrBandWidthFactor,m=s.abrBandWidthUpFactor;if(!f){var y=this.bitrateTestDelay;y&&(p=(l?Math.min(l,s.maxLoadingDelay):s.maxLoadingDelay)-y,h.logger.trace("bitrate test took "+Math.round(1e3*y)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*p)+" ms"),v=m=1)}return g=this.findBestLevel(d,n,i,f+p,v,m),Math.max(g,0)},d.findBestLevel=function(e,t,r,i,s,n){for(var a,o=this.fragCurrent,l=this.partCurrent,u=this.lastLoadedFragLevel,c=this.hls.levels,d=c[u],f=!(null==d||null===(a=d.details)||void 0===a||!a.live),g=null==d?void 0:d.codecSet,p=l?l.duration:o?o.duration:0,v=r;v>=t;v--){var m=c[v];if(m&&(!g||m.codecSet===g)){var y=m.details,E=(l?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||p,S=void 0;S=v<=u?s*e:n*e;var T=c[v].maxBitrate,b=T*E/S;if(h.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+v+"/"+Math.round(S)+"/"+T+"/"+E+"/"+i+"/"+b),S>T&&(!b||f&&!this.bitrateTestDelay||b0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=s.State.IDLE):(this.loadedmetadata=!1,this.state=s.State.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()},T.doTick=function(){switch(this.state){case s.State.IDLE:this.doTickIdle();break;case s.State.WAITING_TRACK:var t,r=this.levels,i=this.trackId,n=null==r||null===(t=r[i])||void 0===t?void 0:t.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=s.State.WAITING_INIT_PTS}break;case s.State.FRAG_LOADING_WAITING_RETRY:var o,l=performance.now(),h=this.retryDate;(!h||l>=h||null!==(o=this.media)&&void 0!==o&&o.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.state=s.State.IDLE);break;case s.State.WAITING_INIT_PTS:var u=this.waitingData;if(u){var c=u.frag,d=u.part,f=u.cache,p=u.complete;if(void 0!==this.initPTS[c.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=s.State.FRAG_LOADING;var v={frag:c,part:d,payload:f.flush(),networkDetails:null};this._handleFragmentLoadProgress(v),p&&e.prototype._handleFragmentLoadComplete.call(this,v)}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=a.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=s.State.IDLE}this.onTickEnd()},T.clearWaitingFragment=function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=s.State.IDLE)},T.onTickEnd=function(){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(){var e,t,r=this.hls,i=this.levels,a=this.media,o=this.trackId,l=r.config;if(i&&i[o]&&(a||!this.startFragRequested&&l.startFragPrefetch)){var c=i[o].details;if(!c||c.live&&this.levelLastLoaded!==o||this.waitForCdnTuneIn(c))this.state=s.State.WAITING_TRACK;else{this.bufferFlushed&&(this.bufferFlushed=!1,this.afterBufferFlushed(this.mediaBuffer?this.mediaBuffer:this.media,u.ElementaryStreamTypes.AUDIO,h.PlaylistLevelType.AUDIO));var d=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,h.PlaylistLevelType.AUDIO);if(null!==d){var f=d.len,g=this.getMaxBufferLength(),p=this.audioSwitch;if(!(f>=g)||p){if(!p&&this._streamEnded(d,c))return r.trigger(n.Events.BUFFER_EOS,{type:"audio"}),void(this.state=s.State.ENDED);var v=c.fragments[0].start,m=d.end;if(p){var y=this.getLoadPosition();m=y,c.PTSKnown&&yv||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=v+.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(){var t=e.prototype.getMaxBufferLength.call(this),r=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,h.PlaylistLevelType.MAIN);return null===r?t:Math.max(t,r.len)},T.onMediaDetaching=function(){this.videoBuffer=null,e.prototype.onMediaDetaching.call(this)},T.onAudioTracksUpdated=function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(e){return new l.Level(e)}))},T.onAudioTrackSwitching=function(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=s.State.IDLE):this.state=s.State.STOPPED,this.tick()},T.onManifestLoading=function(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1},T.onLevelLoaded=function(e,t){this.mainDetails=t.details},T.onAudioTrackLoaded=function(e,t){var r,i=this.levels,n=t.details,a=t.id;if(i){this.log("Track "+a+" loaded ["+n.startSN+","+n.endSN+"],duration:"+n.totalduration);var o=i[a],l=0;if(n.live||null!==(r=o.details)&&void 0!==r&&r.live){var h=this.mainDetails;if(n.fragments[0]||(n.deltaUpdateFailed=!0),n.deltaUpdateFailed||!h)return;!o.details&&n.hasProgramDateTime&&h.hasProgramDateTime?(Object(p.alignMediaPlaylistByPDT)(n,h),l=n.fragments[0].start):l=this.alignPlaylists(n,o.details)}o.details=n,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(o.details,l),this.state!==s.State.WAITING_TRACK||this.waitForCdnTuneIn(n)||(this.state=s.State.IDLE),this.tick()}else this.warn("Audio tracks were reset while loading level "+a)},T._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,o=this.trackId,l=this.levels;if(l){var u=l[o];console.assert(u,"Audio track is defined on fragment load progress");var g=u.details;console.assert(g,"Audio track details are defined on fragment load progress");var p=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2",v=this.transmuxer;v||(v=this.transmuxer=new d.default(this.hls,h.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 S=i?i.index:-1,T=-1!==S,b=new f.ChunkMetadata(r.level,r.sn,r.stats.chunkCount,n.byteLength,S,T);v.push(n,E,p,"",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(n)),this.waitingVideoCC=this.videoTrackCC,this.state=s.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(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},T.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},T.onBufferCreated=function(e,t){var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer)},T.onFragBuffered=function(e,t){var r=t.frag,i=t.part;r.type===h.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(n.Events.AUDIO_TRACK_SWITCHED,{id:this.trackId}))),this.fragBufferedComplete(r,i)))},T.onError=function(t,r){switch(r.details){case v.ErrorDetails.FRAG_LOAD_ERROR:case v.ErrorDetails.FRAG_LOAD_TIMEOUT:case v.ErrorDetails.KEY_LOAD_ERROR:case v.ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(h.PlaylistLevelType.AUDIO,r);break;case v.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case v.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:this.state!==s.State.ERROR&&this.state!==s.State.STOPPED&&(this.state=r.fatal?s.State.ERROR:s.State.IDLE,this.warn(r.details+" while loading frag, switching to "+this.state+" state"));break;case v.ErrorDetails.BUFFER_FULL_ERROR:if("audio"===r.parent&&(this.state===s.State.PARSING||this.state===s.State.PARSED)){var i=!0,n=this.getFwdBufferInfo(this.mediaBuffer,h.PlaylistLevelType.AUDIO);n&&n.len>.5&&(i=!this.reduceMaxBufferLength(n.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(e,t){t.type===u.ElementaryStreamTypes.AUDIO&&(this.bufferFlushed=!0)},T._handleTransmuxComplete=function(e){var t,r="audio",i=this.hls,a=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 h=l.frag,c=l.part,d=a.audio,f=a.text,g=a.id3,p=a.initSegment;if(!this.fragContextChanged(h)){if(this.state=s.State.PARSING,this.audioSwitch&&d&&this.completeAudioSwitch(),null!=p&&p.tracks&&(this._bufferInitSegment(p.tracks,h,o),i.trigger(n.Events.FRAG_PARSING_INIT_SEGMENT,{frag:h,id:r,tracks:p.tracks})),d){var v=d.startPTS,m=d.endPTS,E=d.startDTS,S=d.endDTS;c&&(c.elementaryStreams[u.ElementaryStreamTypes.AUDIO]={startPTS:v,endPTS:m,startDTS:E,endDTS:S}),h.setElementaryStreamInfo(u.ElementaryStreamTypes.AUDIO,v,m,E,S),this.bufferFragmentData(d,h,c,o)}if(null!=g&&null!==(t=g.samples)&&void 0!==t&&t.length){var T=y({frag:h,id:r},g);i.trigger(n.Events.FRAG_PARSING_METADATA,T)}if(f){var b=y({frag:h,id:r},f);i.trigger(n.Events.FRAG_PARSING_USERDATA,b)}}},T._bufferInitSegment=function(e,t,r){if(this.state===s.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(n.Events.BUFFER_CODECS,e);var a=i.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:t,part:null,chunkMeta:r,parent:t.type,data:a};this.hls.trigger(n.Events.BUFFER_APPENDING,o)}this.tick()}}},T.loadFragment=function(t,r,n){var a=this.fragmentTracker.getState(t);this.fragCurrent=t,(this.audioSwitch||a===o.FragmentState.NOT_LOADED||a===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=s.State.WAITING_INIT_PTS):(this.startFragRequested=!0,e.prototype.loadFragment.call(this,t,r,n)))},T.completeAudioSwitch=function(){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(n.Events.AUDIO_TRACK_SWITCHED,{id:i})},S}(s.default);t.default=S},"./src/controller/audio-track-controller.ts":function(e,t,r){"use strict";r.r(t);var i=r("./src/events.ts"),s=r("./src/errors.ts"),n=r("./src/controller/base-playlist-controller.ts"),a=r("./src/types/loader.ts");function o(e,t){for(var r=0;r=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 s=t[e],n=s.id,a=s.groupId,o=void 0===a?"":a,l=s.name,h=s.type,u=s.url;if(this.trackId=e,this.trackName=l,this.selectDefaultTrack=!1,this.hls.trigger(i.Events.AUDIO_TRACK_SWITCHING,{id:n,groupId:o,name:l,type:h,url:u}),!s.details||s.details.live){var c=this.switchParams(s.url,null==r?void 0:r.details);this.loadPlaylist(c)}}},d.selectInitialTrack=function(){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:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))},d.findTrackId=function(e){for(var t=this.tracksInGroup,r=0;rt.partTarget&&(h+=1)}if(Object(i.isFiniteNumber)(l))return new s.HlsUrlParameters(l,Object(i.isFiniteNumber)(h)?h:void 0,s.HlsSkip.No)}}},t.loadPlaylist=function(e){},t.shouldLoadTrack=function(e){return this.canLoad&&e&&!!e.url&&(!e.details||e.details.live)},t.playlistLoaded=function(e,t,r){var i=this,s=t.details,a=t.stats,o=a.loading.end?Math.max(0,self.performance.now()-a.loading.end):0;if(s.advancedDateTime=Date.now()-o,s.live||null!=r&&r.live){if(s.reloaded(r),r&&this.log("live playlist "+e+" "+(s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:"MISSED")),r&&s.fragments.length>0&&Object(n.mergeDetails)(r,s),!this.canLoad||!s.live)return;var l,h=void 0,u=void 0;if(s.canBlockReload&&s.endSN&&s.advanced){var c=this.hls.config.lowLatencyMode,d=s.lastPartSn,f=s.endSN,g=s.lastPartIndex,p=d===f;-1!==g?(h=p?f+1:d,u=p?c?0:g:g+1):h=f+1;var v=s.age,m=v+s.ageHeader,y=Math.min(m-s.partTarget,1.5*s.targetduration);if(y>0){if(r&&y>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+y+" with playlist age: "+s.age),y=0;else{var E=Math.floor(y/s.targetduration);h+=E,void 0!==u&&(u+=Math.round(y%s.targetduration/s.partTarget)),this.log("CDN Tune-in age: "+s.ageHeader+"s last advanced "+v.toFixed(2)+"s goal: "+y+" skip sn "+E+" to part "+u)}s.tuneInGoal=y}if(l=this.getDeliveryDirectives(s,t.deliveryDirectives,h,u),c||!p)return void this.loadPlaylist(l)}else l=this.getDeliveryDirectives(s,t.deliveryDirectives,h,u);var S=Object(n.computeReloadInterval)(s,a);void 0!==h&&s.canBlockReload&&(S-=s.partTarget||1),this.log("reload live playlist "+e+" in "+Math.round(S)+" ms"),this.timer=self.setTimeout((function(){return i.loadPlaylist(l)}),S)}else this.clearTimer()},t.getDeliveryDirectives=function(e,t,r,i){var n=Object(s.getSkipValue)(e,r);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=s.HlsSkip.No),new s.HlsUrlParameters(r,i,n)},t.retryLoadingOrFail=function(e){var t,r=this,i=this.hls.config,s=this.retryCount-1&&null!==(t=e.context)&&void 0!==t&&t.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+e.details+'"'),this.loadPlaylist();else{var n=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),n),this.warn("retry playlist loading #"+this.retryCount+" in "+n+' ms after "'+e.details+'"')}else this.warn('cannot recover from error "'+e.details+'"'),this.clearTimer(),e.fatal=!0;return s},e}()},"./src/controller/base-stream-controller.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"State",(function(){return T})),r.d(t,"default",(function(){return b}));var i=r("./src/polyfills/number.ts"),s=r("./src/task-loop.ts"),n=r("./src/controller/fragment-tracker.ts"),a=r("./src/utils/buffer-helper.ts"),o=r("./src/utils/logger.ts"),l=r("./src/events.ts"),h=r("./src/errors.ts"),u=r("./src/types/transmuxer.ts"),c=r("./src/utils/mp4-tools.ts"),d=r("./src/utils/discontinuities.ts"),f=r("./src/controller/fragment-finders.ts"),g=r("./src/controller/level-helper.ts"),p=r("./src/loader/fragment-loader.ts"),v=r("./src/crypt/decrypter.ts"),m=r("./src/utils/time-ranges.ts"),y=r("./src/types/loader.ts");function E(e,t){for(var r=0;r=t.endSN&&!e.nextStart){var s=t.partList;if(null!=s&&s.length){var o=s[s.length-1];return a.BufferHelper.isBuffered(this.media,o.start+o.duration/2)}var l=i.getState(r);return l===n.FragmentState.PARTIAL||l===n.FragmentState.OK}return!1},A.onMediaAttached=function(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===T.STOPPED&&this.startLoad(i.startPosition)},A.onMediaDetaching=function(){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()},A.onMediaSeeking=function(){var e=this.config,t=this.fragCurrent,r=this.media,s=this.mediaBuffer,n=this.state,o=r?r.currentTime:0,l=a.BufferHelper.bufferInfo(s||r,o,e.maxBufferHole);if(this.log("media seeking to "+(Object(i.isFiniteNumber)(o)?o.toFixed(3):o)+", state: "+n),n===T.ENDED)this.resetLoadingState();else if(t&&!l.len){var h=e.maxFragLookUpTolerance,u=t.start-h,c=o>t.start+t.duration+h;(o0&&n&&n.key&&n.iv&&"AES-128"===n.method){var a=self.performance.now();return t.decrypter.webCryptoDecrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer).then((function(t){var s=self.performance.now();return i.trigger(l.Events.FRAG_DECRYPTED,{frag:e,payload:t,stats:{tstart:a,tdecrypt:s}}),r.payload=t,r}))}return r})).then((function(r){var i=t.fragCurrent,s=t.hls,n=t.levels;if(!n)throw new Error("init load aborted, missing levels");var a=n[e.level].details;console.assert(a,"Level details are defined when init segment is loaded");var o=e.stats;t.state=T.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&&s.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)}))},A.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId},A.fragBufferedComplete=function(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(a.BufferHelper.getBuffered(r))),this.state=T.IDLE,this.tick()},A._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,s=e.partsLoaded,n=!s||0===s.length||s.some((function(e){return!e})),a=new u.ChunkMetadata(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}},A._handleFragmentLoadProgress=function(e){},A._doFragLoad=function(e,t,r,s){var n=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 a=t.partList;if(a&&s){r>e.end&&t.fragmentHint&&(e=t.fragmentHint);var o=this.getNextPart(a,e,r);if(o>-1){var h=a[o];return this.log("Loading part sn: "+e.sn+" p: "+h.index+" cc: "+e.cc+" of playlist ["+t.startSN+"-"+t.endSN+"] parts [0-"+o+"-"+(a.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=h.start+h.duration,this.state=T.FRAG_LOADING,this.hls.trigger(l.Events.FRAG_LOADING,{frag:e,part:a[o],targetBufferTime:r}),this.doFragPartsLoad(e,a,o,s).catch((function(e){return n.handleFragLoadError(e)}))}if(!e.url||this.loadedEndOfParts(a,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=T.FRAG_LOADING,this.hls.trigger(l.Events.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragmentLoader.load(e,s).catch((function(e){return n.handleFragLoadError(e)}))},A.doFragPartsLoad=function(e,t,r,i){var s=this;return new Promise((function(n,a){var o=[];!function r(h){var u=t[h];s.fragmentLoader.loadPart(e,u,i).then((function(i){o[u.index]=i;var a=i.part;s.hls.trigger(l.Events.FRAG_LOADED,i);var c=t[h+1];if(!c||c.fragment!==e)return n({frag:e,part:a,partsLoaded:o});r(h+1)})).catch(a)}(r)}))},A.handleFragLoadError=function(e){var t=e.data;return t&&t.details===h.ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(l.Events.ERROR,t),null},A._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===T.PARSING){var r=t.frag,i=t.part,s=t.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(r,i,s,e.partial)}else this.fragCurrent||(this.state=T.IDLE)},A.getCurrentContext=function(e){var t=this.levels,r=e.level,i=e.sn,s=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 n=t[r],a=s>-1?Object(g.getPartWith)(n,i,s):null,o=a?a.fragment:Object(g.getFragmentWithSN)(n,i,this.fragCurrent);return o?{frag:o,part:a,level:n}:null},A.bufferFragmentData=function(e,t,r,i){if(e&&this.state===T.PARSING){var s=e.data1,n=e.data2,a=s;if(s&&n&&(a=Object(c.appendUint8Array)(s,n)),a&&a.length){var o={type:e.type,frag:t,part:r,chunkMeta:i,parent:t.type,data:a};this.hls.trigger(l.Events.BUFFER_APPENDING,o),e.dropped&&e.independent&&!r&&this.flushBufferGap(t)}}},A.flushBufferGap=function(e){var t=this.media;if(t)if(a.BufferHelper.isBuffered(t,t.currentTime)){var r=t.currentTime,i=a.BufferHelper.bufferInfo(t,r,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),o=Math.max(Math.min(e.start-n,i.end-n),r+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}else this.flushMainBuffer(0,e.start)},A.getFwdBufferInfo=function(e,t){var r=this.config,s=this.getLoadPosition();if(!Object(i.isFiniteNumber)(s))return null;var n=a.BufferHelper.bufferInfo(e,s,r.maxBufferHole);if(0===n.len&&void 0!==n.nextStart){var o=this.fragmentTracker.getBufferedFrag(s,t);if(o&&n.nextStart=r&&(t.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+t.maxMaxBufferLength+"s"),!0)},A.getNextFragment=function(e,t){var r,i,s=t.fragments,n=s.length;if(!n)return null;var a,o=this.config,l=s[0].start;if(t.live){var h=o.initialLiveManifestSize;if(n-1&&rr.start&&r.loaded},A.getInitialLiveFragment=function(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 s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){var n=t[s-e.startSN];r.cc===n.cc&&(i=n,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 a=this.hls.liveSyncPosition;null!==a&&(i=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},A.getFragmentAtPosition=function(e,t,r){var i,s=this.config,a=this.fragPrevious,o=r.fragments,l=r.endSN,h=r.fragmentHint,u=s.maxFragLookUpTolerance,c=!!(s.lowLatencyMode&&r.partList&&h);if(c&&h&&!this.bitrateTest&&(o=o.concat(h),l=h.sn),et-u?0:u;i=Object(f.findFragmentByPTS)(a,o,e,d)}else i=o[o.length-1];if(i){var g=i.sn-r.startSN,p=a&&i.level===a.level,v=o[g+1];if(this.fragmentTracker.getState(i)===n.FragmentState.BACKTRACKED){i=null;for(var m=g;o[m]&&this.fragmentTracker.getState(o[m])===n.FragmentState.BACKTRACKED;)i=a?o[m--]:o[--m];i||(i=v)}else a&&i.sn===a.sn&&!c&&p&&(i.sn=n-t.maxFragLookUpTolerance&&s<=a;if(null!==i&&r.duration>i&&(s"+e.startSN+" prev-sn: "+(n?n.sn:"na")+" fragments: "+o),c}return l},A.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},A.setStartPosition=function(e,t){var r=this.startPosition;if(r"+e))}}])&&E(b.prototype,_),L&&E(b,L),s}(s.default)},"./src/controller/buffer-controller.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return f}));var i=r("./src/polyfills/number.ts"),s=r("./src/events.ts"),n=r("./src/utils/logger.ts"),a=r("./src/errors.ts"),o=r("./src/utils/buffer-helper.ts"),l=r("./src/utils/mediasource-helper.ts"),h=r("./src/loader/fragment.ts"),u=r("./src/controller/buffer-operation-queue.ts"),c=Object(l.getMediaSource)(),d=/([ha]vc.)(?:\.[^.,]+)+/,f=function(){function e(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;n.logger.log("[buffer-controller]: Media source opened"),r&&(t.updateMediaElementDuration(),e.trigger(s.Events.MEDIA_ATTACHED,{media:r})),i&&i.removeEventListener("sourceopen",t._onMediaSourceOpen),t.checkPendingTracks()},this._onMediaSourceClose=function(){n.logger.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=function(){n.logger.log("[buffer-controller]: Media source ended")},this.hls=e,this._initSourceBuffer(),this.registerListeners()}var t=e.prototype;return t.hasSourceTypes=function(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},t.destroy=function(){this.unregisterListeners(),this.details=null},t.registerListeners=function(){var e=this.hls;e.on(s.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(s.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(s.Events.BUFFER_RESET,this.onBufferReset,this),e.on(s.Events.BUFFER_APPENDING,this.onBufferAppending,this),e.on(s.Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(s.Events.BUFFER_EOS,this.onBufferEos,this),e.on(s.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(s.Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(s.Events.FRAG_PARSED,this.onFragParsed,this),e.on(s.Events.FRAG_CHANGED,this.onFragChanged,this)},t.unregisterListeners=function(){var e=this.hls;e.off(s.Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(s.Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(s.Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(s.Events.BUFFER_RESET,this.onBufferReset,this),e.off(s.Events.BUFFER_APPENDING,this.onBufferAppending,this),e.off(s.Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(s.Events.BUFFER_EOS,this.onBufferEos,this),e.off(s.Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(s.Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(s.Events.FRAG_PARSED,this.onFragParsed,this),e.off(s.Events.FRAG_CHANGED,this.onFragChanged,this)},t._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new u.default(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},t.onManifestParsed=function(e,t){var r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,n.logger.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},t.onMediaAttaching=function(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}},t.onMediaDetaching=function(){var e=this.media,t=this.mediaSource,r=this._objectUrl;if(t){if(n.logger.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){n.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()):n.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(s.Events.MEDIA_DETACHED,void 0)},t.onBufferReset=function(){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){n.logger.warn("[buffer-controller]: Failed to reset the "+t+" buffer",e)}})),this._initSourceBuffer()},t.onBufferCodecs=function(e,t){var r=this,i=this.getSourceBufferTypes().length;Object.keys(t).forEach((function(e){if(i){var s=r.tracks[e];if(s&&"function"==typeof s.buffer.changeType){var n=t[e],a=n.codec,o=n.levelCodec,l=n.container;if((s.levelCodec||s.codec).replace(d,"$1")!==(o||a).replace(d,"$1")){var h=l+";codecs="+(o||a);r.appendChangeType(e,h)}}}else r.pendingTracks[e]=t[e]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},t.appendChangeType=function(e,t){var r=this,i=this.operationQueue,s={execute:function(){var s=r.sourceBuffer[e];s&&(n.logger.log("[buffer-controller]: changing "+e+" sourceBuffer type to "+t),s.changeType(t)),i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){n.logger.warn("[buffer-controller]: Failed to change "+e+" SourceBuffer type",t)}};i.append(s,e)},t.onBufferAppending=function(e,t){var r=this,i=this.hls,l=this.operationQueue,h=this.tracks,u=t.data,c=t.type,d=t.frag,f=t.part,g=t.chunkMeta,p=g.buffering[c],v=self.performance.now();p.start=v;var m=d.stats.buffering,y=f?f.stats.buffering:null;0===m.start&&(m.start=v),y&&0===y.start&&(y.start=v);var E=h.audio,S="audio"===c&&1===g.id&&"audio/mpeg"===(null==E?void 0:E.container),T={execute:function(){if(p.executeStart=self.performance.now(),S){var e=r.sourceBuffer[c];if(e){var t=d.start-e.timestampOffset;Math.abs(t)>=.1&&(n.logger.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+d.start+" (delta: "+t+") sn: "+d.sn+")"),e.timestampOffset=d.start)}}r.appendExecutor(u,c)},onStart:function(){},onComplete:function(){var e=self.performance.now();p.executeEnd=p.end=e,0===m.first&&(m.first=e),y&&0===y.first&&(y.first=e);var t=r.sourceBuffer,i={};for(var n in t)i[n]=o.BufferHelper.getBuffered(t[n]);r.appendError=0,r.hls.trigger(s.Events.BUFFER_APPENDED,{type:c,frag:d,part:f,chunkMeta:g,parent:d.type,timeRanges:i})},onError:function(e){n.logger.error("[buffer-controller]: Error encountered while trying to append to the "+c+" SourceBuffer",e);var t={type:a.ErrorTypes.MEDIA_ERROR,parent:d.type,details:a.ErrorDetails.BUFFER_APPEND_ERROR,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=a.ErrorDetails.BUFFER_FULL_ERROR:(r.appendError++,t.details=a.ErrorDetails.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(n.logger.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),t.fatal=!0)),i.trigger(s.Events.ERROR,t)}};l.append(T,c)},t.onBufferFlushing=function(e,t){var r=this,i=this.operationQueue,a=function(e){return{execute:r.removeExecutor.bind(r,e,t.startOffset,t.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(s.Events.BUFFER_FLUSHED,{type:e})},onError:function(t){n.logger.warn("[buffer-controller]: Failed to remove from "+e+" SourceBuffer",t)}}};t.type?i.append(a(t.type),t.type):this.getSourceBufferTypes().forEach((function(e){i.append(a(e),e)}))},t.onFragParsed=function(e,t){var r=this,i=t.frag,a=t.part,o=[],l=a?a.elementaryStreams:i.elementaryStreams;l[h.ElementaryStreamTypes.AUDIOVIDEO]?o.push("audiovideo"):(l[h.ElementaryStreamTypes.AUDIO]&&o.push("audio"),l[h.ElementaryStreamTypes.VIDEO]&&o.push("video")),0===o.length&&n.logger.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,a&&(a.stats.buffering.end=e);var t=a?a.stats:i.stats;r.hls.trigger(s.Events.FRAG_BUFFERED,{frag:i,part:a,stats:t,id:i.type})}),o)},t.onFragChanged=function(e,t){this.flushBackBuffer()},t.onBufferEos=function(e,t){var r=this;this.getSourceBufferTypes().reduce((function(e,i){var s=r.sourceBuffer[i];return t.type&&t.type!==i||s&&!s.ended&&(s.ended=!0,n.logger.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),e&&!(s&&!s.ended)}),!0)&&this.blockBuffers((function(){var e=r.mediaSource;e&&"open"===e.readyState&&e.endOfStream()}))},t.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},t.flushBackBuffer=function(){var e=this.hls,t=this.details,r=this.media,n=this.sourceBuffer;if(r&&null!==t){var a=this.getSourceBufferTypes();if(a.length){var l=t.live&&null!==e.config.liveBackBufferLength?e.config.liveBackBufferLength:e.config.backBufferLength;if(Object(i.isFiniteNumber)(l)&&!(l<0)){var h=r.currentTime,u=t.levelTargetDuration,c=Math.max(l,u),d=Math.floor(h/u)*u-c;a.forEach((function(r){var i=n[r];if(i){var a=o.BufferHelper.getBuffered(i);a.length>0&&d>a.start(0)&&(e.trigger(s.Events.BACK_BUFFER_REACHED,{bufferEnd:d}),t.live&&e.trigger(s.Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d}),e.trigger(s.Events.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:r}))}}))}}}},t.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var e=this.details,t=this.hls,r=this.media,s=this.mediaSource,a=e.fragments[0].start+e.totalduration,o=r.duration,l=Object(i.isFiniteNumber)(s.duration)?s.duration:0;e.live&&t.config.liveDurationInfinity?(n.logger.log("[buffer-controller]: Media Source duration is set to Infinity"),s.duration=1/0,this.updateSeekableRange(e)):(a>l&&a>o||!Object(i.isFiniteNumber)(o))&&(n.logger.log("[buffer-controller]: Updating Media Source duration to "+a.toFixed(3)),s.duration=a)}},t.updateSeekableRange=function(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),s=Math.max(i,i+e.totalduration);t.setLiveSeekableRange(i,s)}},t.checkPendingTracks=function(){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 n=this.getSourceBufferTypes();if(0===n.length)return void this.hls.trigger(s.Events.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});n.forEach((function(e){t.executeNext(e)}))}},t.createSourceBuffers=function(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 h=l.levelCodec||l.codec,u=l.container+";codecs="+h;n.logger.log("[buffer-controller]: creating sourceBuffer("+u+")");try{var c=t[o]=r.addSourceBuffer(u),d=o;this.addBufferListener(d,"updatestart",this._onSBUpdateStart),this.addBufferListener(d,"updateend",this._onSBUpdateEnd),this.addBufferListener(d,"error",this._onSBUpdateError),this.tracks[o]={buffer:c,codec:h,container:l.container,levelCodec:l.levelCodec,id:l.id},i++}catch(e){n.logger.error("[buffer-controller]: error while trying to add sourceBuffer: "+e.message),this.hls.trigger(s.Events.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:u})}}i&&this.hls.trigger(s.Events.BUFFER_CREATED,{tracks:this.tracks})},t._onSBUpdateStart=function(e){this.operationQueue.current(e).onStart()},t._onSBUpdateEnd=function(e){var t=this.operationQueue;t.current(e).onComplete(),t.shiftAndExecuteNext(e)},t._onSBUpdateError=function(e,t){n.logger.error("[buffer-controller]: "+e+" SourceBuffer error",t),this.hls.trigger(s.Events.ERROR,{type:a.ErrorTypes.MEDIA_ERROR,details:a.ErrorDetails.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(e);r&&r.onError(t)},t.removeExecutor=function(e,t,r){var s=this.media,a=this.mediaSource,o=this.operationQueue,l=this.sourceBuffer[e];if(!s||!a||!l)return n.logger.warn("[buffer-controller]: Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void o.shiftAndExecuteNext(e);var h=Object(i.isFiniteNumber)(s.duration)?s.duration:1/0,u=Object(i.isFiniteNumber)(a.duration)?a.duration:1/0,c=Math.max(0,t),d=Math.min(r,h,u);d>c?(n.logger.log("[buffer-controller]: Removing ["+c+","+d+"] from the "+e+" SourceBuffer"),console.assert(!l.updating,e+" sourceBuffer must not be updating"),l.remove(c,d)):o.shiftAndExecuteNext(e)},t.appendExecutor=function(e,t){var r=this.operationQueue,i=this.sourceBuffer[t];if(!i)return n.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)},t.blockBuffers=function(e,t){var r=this;if(void 0===t&&(t=this.getSourceBufferTypes()),!t.length)return n.logger.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve(e);var i=this.operationQueue,s=t.map((function(e){return i.appendBlocker(e)}));Promise.all(s).then((function(){e(),t.forEach((function(e){var t=r.sourceBuffer[e];t&&t.updating||i.shiftAndExecuteNext(e)}))}))},t.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},t.addBufferListener=function(e,t,r){var i=this.sourceBuffer[e];if(i){var s=r.bind(this,e);this.listeners[e].push({event:t,listener:s}),i.addEventListener(t,s)}},t.removeBufferListeners=function(e){var t=this.sourceBuffer[e];t&&this.listeners[e].forEach((function(e){t.removeEventListener(e.event,e.listener)}))},e}()},"./src/controller/buffer-operation-queue.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return s}));var i=r("./src/utils/logger.ts"),s=function(){function e(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}var t=e.prototype;return t.append=function(e,t){var r=this.queues[t];r.push(e),1===r.length&&this.buffers[t]&&this.executeNext(t)},t.insertAbort=function(e,t){this.queues[t].unshift(e),this.executeNext(t)},t.appendBlocker=function(e){var t,r=new Promise((function(e){t=e})),i={execute:t,onStart:function(){},onComplete:function(){},onError:function(){}};return this.append(i,e),r},t.executeNext=function(e){var t=this.buffers,r=this.queues,s=t[e],n=r[e];if(n.length){var a=n[0];try{a.execute()}catch(t){i.logger.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),a.onError(t),s&&s.updating||(n.shift(),this.executeNext(e))}}},t.shiftAndExecuteNext=function(e){this.queues[e].shift(),this.executeNext(e)},t.current=function(e){return this.queues[e][0]},e}()},"./src/controller/cap-level-controller.ts":function(e,t,r){"use strict";r.r(t);var i=r("./src/events.ts");function s(e,t){for(var r=0;r0&&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}}},a.getMaxLevel=function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var s=i.filter((function(i,s){return e.isLevelAllowed(s,r.restrictedLevels)&&s<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)},a.startCapping=function(){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())},a.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},a.getDimensions=function(){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},e.isLevelAllowed=function(e,t){return void 0===t&&(t=[]),-1===t.indexOf(e)},e.getMaxLevelByMediaSize=function(e,t,r){if(!e||!e.length)return-1;for(var i,s,n=e.length-1,a=0;a=t||o.height>=r)&&(i=o,!(s=e[a+1])||i.width!==s.width||i.height!==s.height)){n=a;break}}return n},t=e,n=[{key:"contentScaleFactor",get:function(){var e=1;try{e=self.devicePixelRatio}catch(e){}return e}}],(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*e.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*e.contentScaleFactor}}])&&s(t.prototype,r),n&&s(t,n),e}();t.default=n},"./src/controller/cmcd-controller.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return d}));var i=r("./src/events.ts"),s=r("./src/types/cmcd.ts"),n=r("./src/utils/buffer-helper.ts"),a=r("./src/utils/logger.ts");function o(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=new Array(t);r-1?n+1:i.levels.length;t=i.levels.slice(0,a)}for(var o,l=h(t);!(o=l()).done;){var u=o.value;u.bitrate>r&&(r=u.bitrate)}return r>0?r:NaN},t.getBufferLength=function(e){var t=this.hls.media,r=e===s.CMCDObjectType.AUDIO?this.audioBuffer:this.videoBuffer;return r&&t?1e3*n.BufferHelper.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len:NaN},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new r(e)}var i=e.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(e,r,i){t(e),this.loader.load(e,r,i)},l(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),e}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,r=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new r(e)}var i=e.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(e,r,i){t(e),this.loader.load(e,r,i)},l(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),e}()},e.uuid=function(){var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.substr(t.lastIndexOf("/")+1)},e.serialize=function(e){for(var t,r=[],i=function(e){return!Number.isNaN(e)&&null!=e&&""!==e&&!1!==e},s=function(e){return Math.round(e)},n=function(e){return 100*s(e/100)},a={br:s,d:s,bl:n,dl:n,mtp:n,nor:function(e){return encodeURIComponent(e)},rtp:n,tb:s},o=h(Object.keys(e||{}).sort());!(t=o()).done;){var l=t.value,u=e[l];if(i(u)&&!("v"===l&&1===u||"pr"==l&&1===u)){var c=a[l];c&&(u=c(u));var d=typeof u,f=void 0;f="ot"===l||"sf"===l||"st"===l?l+"="+u:"boolean"===d?l:"number"===d?l+"="+u:l+"="+JSON.stringify(u),r.push(f)}}return r.join(",")},e.toHeaders=function(t){for(var r={},i=["Object","Request","Session","Status"],s=[{},{},{},{}],n={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3},a=0,o=Object.keys(t);a3)return void this.hls.trigger(i.Events.ERROR,{type:s.ErrorTypes.KEY_SYSTEM_ERROR,details:s.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0});var h=3-this._requestLicenseFailureCount+1;n.logger.warn("Retrying license request, "+h+" attempts left"),this._requestLicense(r,a)}},h._generateLicenseRequestChallenge=function(e,t){if(e.mediaKeySystemDomain===a.KeySystems.WIDEVINE)return t;throw new Error("unsupported key-system: "+e.mediaKeySystemDomain)},h._requestLicense=function(e,t){n.logger.log("Requesting content license for key-system");var r=this._mediaKeysList[0];if(!r)return n.logger.error("Fatal error: Media is encrypted but no key-system access has been obtained yet"),void this.hls.trigger(i.Events.ERROR,{type:s.ErrorTypes.KEY_SYSTEM_ERROR,details:s.ErrorDetails.KEY_SYSTEM_NO_ACCESS,fatal:!0});try{var a=this.getLicenseServerUrl(r.mediaKeySystemDomain),o=this._createLicenseXhr(a,e,t);n.logger.log("Sending license request to URL: "+a);var l=this._generateLicenseRequestChallenge(r,e);o.send(l)}catch(e){n.logger.error("Failure requesting DRM license: "+e),this.hls.trigger(i.Events.ERROR,{type:s.ErrorTypes.KEY_SYSTEM_ERROR,details:s.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}},h.onMediaAttached=function(e,t){if(this._emeEnabled){var r=t.media;this._media=r,r.addEventListener("encrypted",this._onMediaEncrypted)}},h.onMediaDetached=function(){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(){})))},h.onManifestParsed=function(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(a.KeySystems.WIDEVINE,r,i)}},t=e,(r=[{key:"requestMediaKeySystemAccess",get:function(){if(!this._requestMediaKeySystemAccess)throw new Error("No requestMediaKeySystemAccess function configured");return this._requestMediaKeySystemAccess}}])&&o(t.prototype,r),l&&o(t,l),e}();t.default=l},"./src/controller/fps-controller.ts":function(e,t,r){"use strict";r.r(t);var i=r("./src/events.ts"),s=r("./src/utils/logger.ts"),n=function(){function e(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 t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(i.Events.MEDIA_ATTACHING,this.onMediaAttaching,this)},t.unregisterListeners=function(){this.hls.off(i.Events.MEDIA_ATTACHING,this.onMediaAttaching)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(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)}},t.checkFPS=function(e,t,r){var n=performance.now();if(t){if(this.lastTime){var a=n-this.lastTime,o=r-this.lastDroppedFrames,l=t-this.lastDecodedFrames,h=1e3*o/a,u=this.hls;if(u.trigger(i.Events.FPS_DROP,{currentDropped:o,currentDecoded:l,totalDroppedFrames:r}),h>0&&o>u.config.fpsDroppedMonitoringThreshold*l){var c=u.currentLevel;s.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(-1===u.autoLevelCapping||u.autoLevelCapping>=c)&&(c-=1,u.trigger(i.Events.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:u.currentLevel}),u.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){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)},e}();t.default=n},"./src/controller/fragment-finders.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"findFragmentByPDT",(function(){return n})),r.d(t,"findFragmentByPTS",(function(){return a})),r.d(t,"fragmentWithinToleranceTest",(function(){return o})),r.d(t,"pdtWithinToleranceTest",(function(){return l})),r.d(t,"findFragWithCC",(function(){return h}));var i=r("./src/polyfills/number.ts"),s=r("./src/utils/binary-search.ts");function n(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 s=0;se&&r.start?-1:0}function l(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function h(e,t){return s.default.search(e,(function(e){return e.cct?-1:0}))}},"./src/controller/fragment-tracker.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"FragmentState",(function(){return i})),r.d(t,"FragmentTracker",(function(){return a}));var i,s=r("./src/events.ts"),n=r("./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 a=function(){function e(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 t=e.prototype;return t._registerListeners=function(){var e=this.hls;e.on(s.Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(s.Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(s.Events.FRAG_LOADED,this.onFragLoaded,this)},t._unregisterListeners=function(){var e=this.hls;e.off(s.Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(s.Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(s.Events.FRAG_LOADED,this.onFragLoaded,this)},t.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){if(t===n.PlaylistLevelType.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var s=i.length;s--;){var a=i[s],o=a?a.end:r.appendedPTS;if(a.start<=e&&void 0!==o&&e<=o)return s>9&&(this.activeParts=i.slice(s-9)),a}else if(r.start<=e&&void 0!==r.appendedPTS&&e<=r.appendedPTS)return r}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){for(var r=this.fragments,i=Object.keys(r),s=i.length;s--;){var n=r[i[s]];if((null==n?void 0:n.body.type)===t&&n.buffered){var a=n.body;if(a.start<=e&&e<=a.end)return a}}return null},t.detectEvictedFragments=function(e,t,r){var i=this;Object.keys(this.fragments).forEach((function(s){var n=i.fragments[s];if(n)if(n.buffered){var a=n.range[e];a&&a.time.some((function(e){var r=!i.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&i.removeFragment(n.body),r}))}else n.body.type===r&&i.removeFragment(n.body)}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges,i=e.frag,s=e.part;if(r&&"initSegment"!==i.sn){var n=l(i),a=this.fragments[n];a&&(Object.keys(r).forEach((function(e){var n=i.elementaryStreams[e];if(n){var o=r[e],l=null!==s||!0===n.partial;a.range[e]=t.getBufferedTimes(i,s,l,o)}})),a.backtrack=a.loaded=null,Object.keys(a.range).length?a.buffered=!0:this.removeFragment(a.body))}},t.fragBuffered=function(e){var t=l(e),r=this.fragments[t];r&&(r.backtrack=r.loaded=null,r.buffered=!0)},t.getBufferedTimes=function(e,t,r,i){for(var s={time:[],partial:r},n=t?t.start:e.start,a=t?t.end:e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n,h=0;h=u&&o<=c){s.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(a,i.end(h))});break}if(nu)s.partial=!0,s.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(a,i.end(h))});else if(a<=u)break}return s},t.getPartialFragment=function(e){var t,r,i,s=null,n=0,a=this.bufferPadding,l=this.fragments;return Object.keys(l).forEach((function(h){var u=l[h];u&&o(u)&&(r=u.body.start-a,i=u.body.end+a,e>=r&&e<=i&&(t=Math.min(e-r,i-e),n<=t&&(s=u.body,n=t)))})),s},t.getState=function(e){var t=l(e),r=this.fragments[t];return r?r.buffered?o(r)?i.PARTIAL:i.OK:r.backtrack?i.BACKTRACKED:i.APPENDING:i.NOT_LOADED},t.backtrack=function(e,t){var r=l(e),i=this.fragments[r];if(!i||i.backtrack)return null;var s=i.backtrack=t||i.loaded;return i.loaded=null,s},t.getBacktrackData=function(e){var t=l(e),r=this.fragments[t];if(r){var i,s=r.backtrack;if(null!=s&&null!==(i=s.payload)&&void 0!==i&&i.byteLength)return s;this.removeFragment(e)}return null},t.isTimeBuffered=function(e,t,r){for(var i,s,n=0;n=i&&t<=s)return!0;if(t<=i)return!1}return!1},t.onFragLoaded=function(e,t){var r=t.frag,i=t.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var s=l(r);this.fragments[s]={body:r,loaded:t,backtrack:null,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=this,i=t.frag,s=t.part,a=t.timeRanges;if(i.type===n.PlaylistLevelType.MAIN)if(this.activeFragment=i,s){var o=this.activeParts;o||(this.activeParts=o=[]),o.push(s)}else this.activeParts=null;this.timeRanges=a,Object.keys(a).forEach((function(e){var t=a[e];if(r.detectEvictedFragments(e,t),!s)for(var n=0;ne&&i.removeFragment(a)}}))},t.removeFragment=function(e){var t=l(e);e.stats.loaded=0,e.clearElementaryStreamInfo(),delete this.fragments[t]},t.removeAllFragments=function(){this.fragments=Object.create(null),this.activeFragment=null,this.activeParts=null},e}();function o(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 l(e){return e.type+"_"+e.level+"_"+e.urlId+"_"+e.sn}},"./src/controller/gap-controller.ts":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 h})),r.d(t,"SKIP_BUFFER_RANGE_START",(function(){return u})),r.d(t,"default",(function(){return c}));var i=r("./src/utils/buffer-helper.ts"),s=r("./src/errors.ts"),n=r("./src/events.ts"),a=r("./src/utils/logger.ts"),o=250,l=2,h=.1,u=.05,c=function(){function e(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 t=e.prototype;return t.destroy=function(){this.hls=this.fragmentTracker=this.media=null},t.poll=function(e){var t=this.config,r=this.media,s=this.stalled,n=r.currentTime,h=r.seeking,u=this.seeking&&!h,c=!this.seeking&&h;if(this.seeking=h,n===e){if((c||u)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&&i.BufferHelper.getBuffered(r).length){var d=i.BufferHelper.bufferInfo(r,n,0),f=d.len>0,g=d.nextStart||0;if(f||g){if(h){var p=d.len>l,v=!g||g-n>l&&!this.fragmentTracker.getPartialFragment(n);if(p||v)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var m,y=Math.max(g,d.start||0)-n,E=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,S=(null==E||null===(m=E.details)||void 0===m?void 0:m.live)?2*E.details.targetduration:l;if(y>0&&y<=S)return void this._trySkipBufferHole(null)}var T=self.performance.now();if(null!==s){var b=T-s;!h&&b>=o&&this._reportStall(d.len);var _=i.BufferHelper.bufferInfo(r,n,t.maxBufferHole);this._tryFixBufferStall(_,b)}else this.stalled=T}}}else if(this.moved=!0,null!==s){if(this.stallReported){var L=self.performance.now()-s;a.logger.warn("playback not stuck anymore @"+n+", after "+Math.round(L)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},t._tryFixBufferStall=function(e,t){var r=this.config,i=this.fragmentTracker,s=this.media.currentTime,n=i.getPartialFragment(s);n&&this._trySkipBufferHole(n)||e.len>r.maxBufferHole&&t>1e3*r.highBufferWatchdogPeriod&&(a.logger.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},t._reportStall=function(e){var t=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,a.logger.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+e+")"),t.trigger(n.Events.ERROR,{type:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,buffer:e}))},t._trySkipBufferHole=function(e){for(var t=this.config,r=this.hls,o=this.media,l=o.currentTime,c=0,d=i.BufferHelper.getBuffered(o),f=0;f=c&&l.05&&this.forwardBufferLength>1){var h=Math.min(2,Math.max(1,n)),u=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(h,Math.max(1,u))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}}}}},l.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},l.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},t=e,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config,t=this.levelDetails;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,s=this.config,n=s.liveSyncDuration,a=s.liveSyncDurationCount,o=s.lowLatencyMode,l=this.hls.userConfig,h=o&&r||t;(l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*i);var u=i;return h+Math.min(1*this.stallCount,u)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(null===e||null===t||null===r)return null;var i=r.edge,s=e-t-this.edgeStalled,n=i-r.totalduration,a=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,s),a)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){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(){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}}])&&a(t.prototype,r),o&&a(t,o),e}()},"./src/controller/level-controller.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return g}));var i=r("./src/types/level.ts"),s=r("./src/events.ts"),n=r("./src/errors.ts"),a=r("./src/utils/codecs.ts"),o=r("./src/controller/level-helper.ts"),l=r("./src/controller/base-playlist-controller.ts"),h=r("./src/types/loader.ts");function u(){return u=Object.assign||function(e){for(var t=1;t0){r=h[0].bitrate,h.sort((function(e,t){return e.bitrate-t.bitrate})),this._levels=h;for(var m=0;mthis.hls.config.fragLoadingMaxRetry&&(a=r.frag.level)):a=r.frag.level}break;case n.ErrorDetails.LEVEL_LOAD_ERROR:case n.ErrorDetails.LEVEL_LOAD_TIMEOUT:i&&(i.deliveryDirectives&&(l=!1),a=i.level),o=!0;break;case n.ErrorDetails.REMUX_ALLOC_ERROR:a=r.level,o=!0}void 0!==a&&this.recoverLevel(r,a,o,l)}}},m.recoverLevel=function(e,t,r,i){var s=e.details,n=this._levels[t];if(n.loadError++,r){if(!this.retryLoadingOrFail(e))return void(this.currentLevelIndex=-1);e.levelRetry=!0}if(i){var a=n.url.length;if(a>1&&n.loadError1){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}},m.onFragLoaded=function(e,t){var r=t.frag;if(void 0!==r&&r.type===h.PlaylistLevelType.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},m.onLevelLoaded=function(e,t){var r,i,s=t.level,n=t.details,a=this._levels[s];if(!a)return this.warn("Invalid level index "+s),void(null!==(i=t.deliveryDirectives)&&void 0!==i&&i.skip&&(n.deltaUpdateFailed=!0));s===this.currentLevelIndex?(0===a.fragmentError&&(a.loadError=0,this.retryCount=0),this.playlistLoaded(s,t,a.details)):null!==(r=t.deliveryDirectives)&&void 0!==r&&r.skip&&(n.deltaUpdateFailed=!0)},m.onAudioTrackSwitched=function(e,t){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,s=this.hls.audioTracks[t.id].groupId,n=0;n0){var i=r.urlId,n=r.url[i];if(e)try{n=e.addDirectives(n)}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+" "+n),this.clearTimer(),this.hls.trigger(s.Events.LEVEL_LOADING,{url:n,level:t,id:i,deliveryDirectives:e||null})}},m.removeLevel=function(e,t){var r=function(e,r){return r!==t},i=this._levels.filter((function(i,s){return s!==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(s.Events.LEVELS_UPDATED,{levels:i})},g=l,(p=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(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(s.Events.ERROR,{type:n.ErrorTypes.OTHER_ERROR,details:n.ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:i,reason:"invalid level idx"}),i)return;e=Math.min(e,r.length-1)}this.clearTimer();var a=this.currentLevelIndex,o=r[a],l=r[e];this.log("switching to level "+e+" from "+a),this.currentLevelIndex=e;var h=u({},l,{level:e,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete h._urlId,this.hls.trigger(s.Events.LEVEL_SWITCHING,h);var c=l.details;if(!c||c.live){var d=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(d)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])&&c(g.prototype,p),v&&c(g,v),l}(l.default)},"./src/controller/level-helper.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"addGroupId",(function(){return n})),r.d(t,"assignTrackIdsByGroup",(function(){return a})),r.d(t,"updatePTS",(function(){return o})),r.d(t,"updateFragPTSDTS",(function(){return h})),r.d(t,"mergeDetails",(function(){return u})),r.d(t,"mapPartIntersection",(function(){return c})),r.d(t,"mapFragmentIntersection",(function(){return d})),r.d(t,"adjustSliding",(function(){return f})),r.d(t,"addSliding",(function(){return g})),r.d(t,"computeReloadInterval",(function(){return p})),r.d(t,"getFragmentWithSN",(function(){return v})),r.d(t,"getPartWith",(function(){return m}));var i=r("./src/polyfills/number.ts"),s=r("./src/utils/logger.ts");function n(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 a(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}function o(e,t,r){l(e[t],e[r])}function l(e,t){var r=t.startPTS;if(Object(i.isFiniteNumber)(r)){var s,n=0;t.sn>e.sn?(n=r-e.start,s=e):(n=e.start-r,s=t),s.duration!==n&&(s.duration=n)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration:t.start=Math.max(e.start-t.duration,0)}function h(e,t,r,n,a,o){n-r<=0&&(s.logger.warn("Fragment should have a positive duration",t),n=r+t.duration,o=a+t.duration);var h=r,u=n,c=t.startPTS,d=t.endPTS;if(Object(i.isFiniteNumber)(c)){var f=Math.abs(c-r);Object(i.isFiniteNumber)(t.deltaPTS)?t.deltaPTS=Math.max(f,t.deltaPTS):t.deltaPTS=f,h=Math.max(r,c),r=Math.min(r,c),a=Math.min(a,t.startDTS),u=Math.min(n,d),n=Math.max(n,d),o=Math.max(o,t.endDTS)}t.duration=n-r;var g=r-t.start;t.appendedPTS=n,t.start=t.startPTS=r,t.maxStartPTS=h,t.startDTS=a,t.endPTS=n,t.minEndPTS=u,t.endDTS=o;var p,v=t.sn;if(!e||ve.endSN)return 0;var m=v-e.startSN,y=e.fragments;for(y[m]=t,p=m;p>0;p--)l(y[p],y[p-1]);for(p=m;p=0;a--){var o=n[a].initSegment;if(o){r=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;var l,u=0;if(d(e,t,(function(e,s){e.relurl&&(u=e.cc-s.cc),Object(i.isFiniteNumber)(e.startPTS)&&Object(i.isFiniteNumber)(e.endPTS)&&(s.start=s.startPTS=e.startPTS,s.startDTS=e.startDTS,s.appendedPTS=e.appendedPTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.duration=e.endPTS-e.startPTS,s.duration&&(l=s),t.PTSKnown=t.alignedSliding=!0),s.elementaryStreams=e.elementaryStreams,s.loader=e.loader,s.stats=e.stats,s.urlId=e.urlId,e.initSegment&&(s.initSegment=e.initSegment,r=e.initSegment)})),r&&(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((function(e){var t;e.initSegment&&e.initSegment.relurl!==(null===(t=r)||void 0===t?void 0:t.relurl)||(e.initSegment=r)})),t.skippedSegments&&(t.deltaUpdateFailed=t.fragments.some((function(e){return!e})),t.deltaUpdateFailed)){s.logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var g=t.skippedSegments;g--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}var p=t.fragments;if(u){s.logger.warn("discontinuity sliding from playlist, take drift into account");for(var v=0;v=i.length||g(t,i[r].start)}function g(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i0&&n<3*i,o=t.loading.end-t.loading.start,l=e.availabilityDelay;if(!1===e.updated)if(a){var h=333*e.misses;r=Math.max(Math.min(s,2*o),h),e.availabilityDelay=(e.availabilityDelay||0)+r}else r=s;else a?(l=Math.min(l||i/2,n),e.availabilityDelay=l,r=l+i-n):r=i-o;return Math.round(r)}function v(e,t,r){if(!e||!e.details)return null;var i=e.details,s=i.fragments[t-i.startSN];return s||((s=i.fragmentHint)&&s.sn===t?s:t0&&-1===e&&(this.log("Override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=s.State.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=s.State.STOPPED},b.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},b.doTick=function(){switch(this.state){case s.State.IDLE:this.doTickIdle();break;case s.State.WAITING_LEVEL:var e,t=this.levels,r=this.level,i=null==t||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=s.State.IDLE;break}break;case s.State.FRAG_LOADING_WAITING_RETRY:var n,a=self.performance.now(),o=this.retryDate;(!o||a>=o||null!==(n=this.media)&&void 0!==n&&n.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.state=s.State.IDLE)}this.onTickEnd()},b.onTickEnd=function(){e.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},b.doTickIdle=function(){var e,t,r=this.hls,i=this.levelLastLoaded,n=this.levels,o=this.media,c=r.config,d=r.nextLoadLevel;if(null!==i&&(o||!this.startFragRequested&&c.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&n&&n[d]){var f=n[d];this.level=r.nextLoadLevel=d;var g=f.details;if(!g||this.state===s.State.WAITING_LEVEL||g.live&&this.levelLastLoaded!==d)this.state=s.State.WAITING_LEVEL;else{var p=this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:o,h.PlaylistLevelType.MAIN);if(null!==p&&!(p.len>=this.getMaxBufferLength(f.maxBitrate))){if(this._streamEnded(p,g)){var v={};return this.altAudio&&(v.type="video"),this.hls.trigger(a.Events.BUFFER_EOS,v),void(this.state=s.State.ENDED)}var m=p.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 S=this.audioOnly&&!this.altAudio?u.ElementaryStreamTypes.AUDIO:u.ElementaryStreamTypes.VIDEO;this.afterBufferFlushed(o,S,h.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))}}}},b.loadFragment=function(t,r,i){var s,n=this.fragmentTracker.getState(t);if(this.fragCurrent=t,n===l.FragmentState.BACKTRACKED){var a=this.fragmentTracker.getBacktrackData(t);if(a)return this._handleFragmentLoadProgress(a),void this._handleFragmentLoadComplete(a);n=l.FragmentState.NOT_LOADED}n===l.FragmentState.NOT_LOADED||n===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)):n===l.FragmentState.APPENDING?this.reduceMaxBufferLength(t.duration)&&this.fragmentTracker.removeFragment(t):0===(null===(s=this.media)||void 0===s?void 0:s.buffered.length)&&this.fragmentTracker.removeAllFragments()},b.getAppendedFrag=function(e){var t=this.fragmentTracker.getAppendedFrag(e,h.PlaylistLevelType.MAIN);return t&&"fragment"in t?t.fragment:t},b.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,h.PlaylistLevelType.MAIN)},b.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},b.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},b.nextLevelSwitch=function(){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 s=e[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*n)+1:0}else r=0;var a=this.getBufferedFrag(t.currentTime+r);if(a){var o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,h=o.duration,u=Math.max(a.end,l+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,.5*h),.75*h));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}},b.abortCurrentFrag=function(){var e=this.fragCurrent;this.fragCurrent=null,null!=e&&e.loader&&e.loader.abort(),this.state===s.State.KEY_LOADING&&(this.state=s.State.IDLE),this.nextLoadPosition=this.getLoadPosition()},b.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,this.altAudio?"video":null)},b.onMediaAttached=function(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)},b.onMediaDetaching=function(){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)},b.onMediaPlaying=function(){this.tick()},b.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:null;Object(i.isFiniteNumber)(t)&&this.log("Media seeked to "+t.toFixed(3)),this.tick()},b.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(a.Events.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=this.stalled=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null},b.onManifestParsed=function(e,t){var r,i=!1,s=!1;t.levels.forEach((function(e){(r=e.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(i=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=i&&s&&!Object(n.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},b.onLevelLoading=function(e,t){var r=this.levels;if(r&&this.state===s.State.IDLE){var i=r[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(i.details))&&(this.state=s.State.WAITING_LEVEL)}},b.onLevelLoaded=function(e,t){var r,i=this.levels,n=t.level,o=t.details,l=o.totalduration;if(i){this.log("Level "+n+" loaded ["+o.startSN+","+o.endSN+"], cc ["+o.startCC+", "+o.endCC+"] duration:"+l);var h=this.fragCurrent;!h||this.state!==s.State.FRAG_LOADING&&this.state!==s.State.FRAG_LOADING_WAITING_RETRY||h.level!==t.level&&h.loader&&(this.state=s.State.IDLE,h.loader.abort());var u=i[n],c=0;if(o.live||null!==(r=u.details)&&void 0!==r&&r.live){if(o.fragments[0]||(o.deltaUpdateFailed=!0),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,u.details)}if(u.details=o,this.levelLastLoaded=n,this.hls.trigger(a.Events.LEVEL_UPDATED,{details:o,level:n}),this.state===s.State.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=s.State.IDLE}this.startFragRequested?o.live&&this.synchronizeToLiveEdge(o):this.setStartPosition(o,c),this.tick()}else this.warn("Levels were reset while loading level "+n)},b._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,s=e.payload,n=this.levels;if(n){var a=n[r.level],o=a.details;if(o){var l=a.videoCodec,u=o.PTSKnown||!o.live,f=null===(t=r.initSegment)||void 0===t?void 0:t.data,g=this._getAudioCodec(a),p=this.transmuxer=this.transmuxer||new c.default(this.hls,h.PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),v=i?i.index:-1,m=-1!==v,y=new d.ChunkMetadata(r.level,r.sn,r.stats.chunkCount,s.byteLength,v,m),E=this.initPTS[r.cc];p.push(s,f,g,l,r,i,o.totalduration,u,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")},b.onAudioTrackSwitching=function(e,t){var r=this.altAudio,i=!!t.url,s=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 n=this.fragCurrent;null!=n&&n.loader&&(this.log("Switching to main audio track, cancel main fragment load"),n.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(a.Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(a.Events.AUDIO_TRACK_SWITCHED,{id:s})}},b.onAudioTrackSwitched=function(e,t){var r=t.id,i=!!this.hls.audioTracks[r].url;if(i){var s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i,this.tick()},b.onBufferCreated=function(e,t){var r,i,s=t.tracks,n=!1;for(var a in s){var o=s[a];if("main"===o.id){if(i=a,r=o,"video"===a){var l=s[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},b.onFragBuffered=function(e,t){var r=t.frag,i=t.part;if(!r||r.type===h.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===s.State.PARSED&&(this.state=s.State.IDLE));var n=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},b.onError=function(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(h.PlaylistLevelType.MAIN,t);break;case g.ErrorDetails.LEVEL_LOAD_ERROR:case g.ErrorDetails.LEVEL_LOAD_TIMEOUT:this.state!==s.State.ERROR&&(t.fatal?(this.warn(""+t.details),this.state=s.State.ERROR):t.levelRetry||this.state!==s.State.WAITING_LEVEL||(this.state=s.State.IDLE));break;case g.ErrorDetails.BUFFER_FULL_ERROR:if("main"===t.parent&&(this.state===s.State.PARSING||this.state===s.State.PARSED)){var r=!0,i=this.getFwdBufferInfo(this.media,h.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()}}},b.checkBuffer=function(){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}},b.onFragLoadEmergencyAborted=function(){this.state=s.State.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},b.onBufferFlushed=function(e,t){var r=t.type;if(r!==u.ElementaryStreamTypes.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===u.ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,h.PlaylistLevelType.MAIN)}},b.onLevelsUpdated=function(e,t){this.levels=t.levels},b.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},b.seekToStartPos=function(){var e=this.media,t=e.currentTime,r=this.startPosition;if(r>=0&&t0&&(s1&&!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,s=t.level;i&&t.sn===i.sn&&i.level===s&&t.urlId===i.urlId||(this.hls.trigger(a.Events.FRAG_CHANGED,{frag:t}),i&&i.level===s||this.hls.trigger(a.Events.LEVEL_SWITCHED,{level:s}),this.fragPlaying=t)}}},E=y,(S=[{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentLevel",get:function(){var e=this.media;if(e){var t=this.getAppendedFrag(e.currentTime);if(t)return t.level}return-1}},{key:"nextBufferedFrag",get:function(){var e=this.media;if(e){var t=this.getAppendedFrag(e.currentTime);return this.followingBufferedFrag(t)}return null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&v(E.prototype,S),T&&v(E,T),y}(s.default)},"./src/controller/subtitle-stream-controller.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"SubtitleStreamController",(function(){return g}));var i=r("./src/events.ts"),s=r("./src/utils/buffer-helper.ts"),n=r("./src/controller/fragment-finders.ts"),a=r("./src/utils/discontinuities.ts"),o=r("./src/controller/level-helper.ts"),l=r("./src/controller/fragment-tracker.ts"),h=r("./src/controller/base-stream-controller.ts"),u=r("./src/types/loader.ts"),c=r("./src/types/level.ts");function d(e,t){for(var r=0;r=s[o].start&&a<=s[o].end){n=s[o];break}var l=r.start+r.duration;n?n.end=l:(n={start:a,end:l},s.push(n)),this.fragmentTracker.fragBuffered(r)}}},y.onBufferFlushing=function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var s=this.currentTrackId,n=this.levels;if(!n.length||!n[s]||!n[s].details)return;var a=i-n[s].details.targetduration;if(a<=0)return;t.endOffsetSubtitles=Math.max(0,a),this.tracksBuffered.forEach((function(e){for(var t=0;t=u.length||s!==l)&&c){if(this.mediaBuffer=this.mediaBufferTimeRanges,i.live||null!==(r=c.details)&&void 0!==r&&r.live){var d=this.mainDetails;if(i.deltaUpdateFailed||!d)return;var f=d.fragments[0];c.details?0===this.alignPlaylists(i,c.details)&&f&&Object(o.addSliding)(i,f.start):i.hasProgramDateTime&&d.hasProgramDateTime?Object(a.alignMediaPlaylistByPDT)(i,d):f&&Object(o.addSliding)(i,f.start)}c.details=i,this.levelLastLoaded=s,this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===h.State.IDLE&&(Object(n.findFragmentByPTS)(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0))}}},y._handleFragmentLoadComplete=function(e){var t=e.frag,r=e.payload,s=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&s&&s.key&&s.iv&&"AES-128"===s.method){var a=performance.now();this.decrypter.webCryptoDecrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).then((function(e){var r=performance.now();n.trigger(i.Events.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:a,tdecrypt:r}})}))}},y.doTick=function(){if(this.media){if(this.state===h.State.IDLE){var e,t=this.currentTrackId,r=this.levels;if(!r.length||!r[t]||!r[t].details)return;var i=r[t].details,a=i.targetduration,o=this.config,u=this.media,c=s.BufferHelper.bufferedInfo(this.mediaBufferTimeRanges,u.currentTime-a,o.maxBufferHole),d=c.end;if(c.len>this.getMaxBufferLength()+a)return;console.assert(i,"Subtitle track details are defined on idle subtitle stream controller tick");var f,g=i.fragments,p=g.length,v=i.edge,m=this.fragPrevious;if(d-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))},f.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)},f.onMediaDetaching=function(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),u(this.media.textTracks).forEach((function(e){Object(s.clearCurrentCues)(e)})),this.subtitleTrack=-1,this.media=null)},f.onManifestLoading=function(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0},f.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},f.onSubtitleTrackLoaded=function(e,t){var r=t.id,i=t.details,s=this.trackId,n=this.tracksInGroup[s];if(n){var a=n.details;n.details=t.details,this.log("subtitle track "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&(this.retryCount=0,this.playlistLoaded(r,t,a))}else this.warn("Invalid subtitle track id "+r)},f.onLevelLoading=function(e,t){this.switchLevel(t.level)},f.onLevelSwitching=function(e,t){this.switchLevel(t.level)},f.switchLevel=function(e){var t=this.hls.levels[e];if(null!=t&&t.textGroupIds){var r=t.textGroupIds[t.urlId];if(this.groupId!==r){var s=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0,n=this.tracks.filter((function(e){return!r||e.groupId===r}));this.tracksInGroup=n;var a=this.findTrackId(null==s?void 0:s.name)||this.findTrackId();this.groupId=r;var o={subtitleTracks:n};this.log("Updating subtitle tracks, "+n.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(i.Events.SUBTITLE_TRACKS_UPDATED,o),-1!==a&&this.setSubtitleTrack(a,s)}}},f.findTrackId=function(e){for(var t=this.tracksInGroup,r=0;r=s.length)){this.clearTimer();var n=s[e];if(this.log("Switching to subtitle track "+e),this.trackId=e,n){var a=n.id,o=n.groupId,l=void 0===o?"":o,h=n.name,u=n.type,c=n.url;this.hls.trigger(i.Events.SUBTITLE_TRACK_SWITCH,{id:a,groupId:l,name:h,type:u,url:c});var d=this.switchParams(n.url,null==t?void 0:t.details);this.loadPlaylist(d)}else this.hls.trigger(i.Events.SUBTITLE_TRACK_SWITCH,{id:e})}}else this.queuedDefaultTrack=e},f.onTextTracksChanged=function(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),this.media&&this.hls.config.renderTextTracksNatively){for(var e=-1,t=u(this.media.textTracks),r=0;r=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],r),u=!0,f/(r-t)>.5))return}if(u||n.push([t,r]),this.config.renderTextTracksNatively){var g=this.captionsTracks[e];this.Cues.newCue(g,t,r,i)}else{var p=this.Cues.newCue(null,t,r,i);this.hls.trigger(s.Events.CUES_PARSED,{type:"captions",cues:p,track:e})}},t.onInitPtsFound=function(e,t){var r=this,i=t.frag,n=t.id,a=t.initPTS,o=t.timescale,l=this.unparsedVttFrags;"main"===n&&(this.initPTS[i.cc]=a,this.timescale[i.cc]=o),l.length&&(this.unparsedVttFrags=[],l.forEach((function(e){r.onFragLoaded(s.Events.FRAG_LOADED,e)})))},t.getExistingTrack=function(e){var t=this.media;if(t)for(var r=0;r>>8^255&v^99,e[f]=v,t[v]=f;var m=d[f],y=d[m],E=d[y],S=257*d[v]^16843008*v;i[f]=S<<24|S>>>8,s[f]=S<<16|S>>>16,n[f]=S<<8|S>>>24,a[f]=S,S=16843009*E^65537*y^257*m^16843008*f,l[v]=S<<24|S>>>8,h[v]=S<<16|S>>>16,u[v]=S<<8|S>>>24,c[v]=S,f?(f=m^d[d[d[E^m]]],g^=d[d[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i>>6);var g=(60&t[r+2])>>>2;if(!(g>f.length-1))return h=(1&t[r+2])<<2,h|=(192&t[r+3])>>>6,i.logger.log("manifest codec:"+a+", ADTS type:"+o+", samplingIndex:"+g),/firefox/i.test(c)?g>=6?(o=5,u=new Array(4),l=g-3):(o=2,u=new Array(2),l=g):-1!==c.indexOf("android")?(o=2,u=new Array(2),l=g):(o=5,u=new Array(4),a&&(-1!==a.indexOf("mp4a.40.29")||-1!==a.indexOf("mp4a.40.5"))||!a&&g>=6?l=g-3:((a&&-1!==a.indexOf("mp4a.40.2")&&(g>=6&&1===h||/vivaldi/i.test(c))||!a&&1===h)&&(o=2,u=new Array(2)),l=g)),u[0]=o<<3,u[0]|=(14&g)>>1,u[1]|=(1&g)<<7,u[1]|=h<<3,5===o&&(u[1]|=(14&l)>>1,u[2]=(1&l)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:f[g],channelCount:h,codec:"mp4a.40."+o,manifestCodec:d};e.trigger(n.Events.ERROR,{type:s.ErrorTypes.MEDIA_ERROR,details:s.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+g})}function o(e,t){return 255===e[t]&&240==(246&e[t+1])}function l(e,t){return 1&e[t+1]?7:9}function h(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function u(e,t){return t+5=e.length)return!1;var i=h(e,t);if(i<=r)return!1;var s=t+i;return s===e.length||c(e,s)}return!1}function g(e,t,r,s,n){if(!e.samplerate){var o=a(t,r,s,n);if(!o)return;e.config=o.config,e.samplerate=o.samplerate,e.channelCount=o.channelCount,e.codec=o.codec,e.manifestCodec=o.manifestCodec,i.logger.log("parsed codec:"+e.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function p(e){return 9216e4/e}function v(e,t,r,i,s){var n=l(e,t),a=h(e,t);if((a-=n)>0)return{headerLength:n,frameLength:a,stamp:r+i*s}}function m(e,t,r,i,s){var n=v(t,r,i,s,p(e.samplerate));if(n){var a,o=n.frameLength,l=n.headerLength,h=n.stamp,u=l+o,c=Math.max(0,r+u-t.length);c?(a=new Uint8Array(u-l)).set(t.subarray(r+l,t.length),0):a=t.subarray(r+l,r+u);var d={unit:a,pts:h};return c||e.samples.push(d),{sample:d,length:u,missing:c}}}},"./src/demux/base-audio-demuxer.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"initPTSFn",(function(){return h}));var i=r("./src/polyfills/number.ts"),s=r("./src/demux/id3.ts"),n=r("./src/demux/dummy-demuxed-track.ts"),a=r("./src/utils/mp4-tools.ts"),o=r("./src/utils/typed-array.ts"),l=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.initPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(){},t.resetContiguity=function(){},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,r){},t.demux=function(e,t){this.cachedData&&(e=Object(a.appendUint8Array)(this.cachedData,e),this.cachedData=null);var r,i,l=s.getID3Data(e,0),u=l?l.length:0,c=this._audioTrack,d=this._id3Track,f=l?s.getTimeStamp(l):void 0,g=e.length;for(0!==this.frameIndex&&null!==this.initPTS||(this.initPTS=h(f,t)),l&&l.length>0&&d.samples.push({pts:this.initPTS,dts:this.initPTS,data:l}),i=this.initPTS;ue?(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)},t.readBits=function(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<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},t.skipScalingList=function(e){for(var t=8,r=8,i=0;i0)return e.subarray(r,r+i)},o=function(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(e,t){return s(e,t)&&o(e,t+6)+10<=e.length-t},h=function(e){for(var t=d(e),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(n);break;case 12:case 13:a=e[u++],h+=String.fromCharCode((31&n)<<6|63&a);break;case 14:a=e[u++],o=e[u++],h+=String.fromCharCode((15&n)<<12|(63&a)<<6|(63&o)<<0)}}return h},E={decodeTextFrame:p};function S(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},"./src/demux/mp3demuxer.ts":function(e,t,r){"use strict";r.r(t);var i=r("./src/demux/base-audio-demuxer.ts"),s=r("./src/demux/id3.ts"),n=r("./src/utils/logger.ts"),a=r("./src/demux/mpegaudio.ts");function o(e,t){return o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},o(e,t)}var l=function(e){var t,r;function i(){return e.apply(this,arguments)||this}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,o(t,r);var l=i.prototype;return l.resetInitSegment=function(t,r,i){e.prototype.resetInitSegment.call(this,t,r,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,isAAC:!1,samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}},i.probe=function(e){if(!e)return!1;for(var t=(s.getID3Data(e,0)||[]).length,r=e.length;t0},t.demux=function(e){var t=e,r=Object(s.dummyTrack)();if(this.config.progressive){this.remainderData&&(t=Object(i.appendUint8Array)(this.remainderData,e));var n=Object(i.segmentValidRange)(t);this.remainderData=n.remainder,r.samples=n.valid||new Uint8Array}else r.samples=t;return{audioTrack:Object(s.dummyTrack)(),avcTrack:r,id3Track:Object(s.dummyTrack)(),textTrack:Object(s.dummyTrack)()}},t.flush=function(){var e=Object(s.dummyTrack)();return e.samples=this.remainderData||new Uint8Array,this.remainderData=null,{audioTrack:Object(s.dummyTrack)(),avcTrack:e,id3Track:Object(s.dummyTrack)(),textTrack:Object(s.dummyTrack)()}},t.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){},e}();n.minProbeByteLength=1024,t.default=n},"./src/demux/mpegaudio.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"appendFrame",(function(){return l})),r.d(t,"parseHeader",(function(){return h})),r.d(t,"isHeaderPattern",(function(){return u})),r.d(t,"isHeader",(function(){return c})),r.d(t,"canParse",(function(){return d})),r.d(t,"probe",(function(){return f}));var i=null,s=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],n=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],a=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],o=[0,1,1,4];function l(e,t,r,i,s){if(!(r+24>t.length)){var n=h(t,r);if(n&&r+n.frameLength<=t.length){var a=i+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(r,r+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function h(e,t){var r=e[t+1]>>3&3,l=e[t+1]>>1&3,h=e[t+2]>>4&15,u=e[t+2]>>2&3;if(1!==r&&0!==h&&15!==h&&3!==u){var c=e[t+2]>>1&1,d=e[t+3]>>6,f=1e3*s[14*(3===r?3-l:3===l?3:4)+h-1],g=n[3*(3===r?0:2===r?1:2)+u],p=3===d?1:2,v=a[r][l],m=o[l],y=8*v*m,E=Math.floor(v*f/g+c)*m;if(null===i){var S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);i=S?parseInt(S[1]):0}return!!i&&i<=87&&2===l&&f>=224e3&&0===d&&(e[t+3]=128|e[t+3]),{sampleRate:g,channelCount:p,frameLength:E,samplesPerFrame:y}}}function u(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function c(e,t){return t+1=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}}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,s=32;s=e.length)return void i();for(var s=e[t].units;!(r>=s.length);r++){var n=s[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type)){var a=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,n,a),!a)return}}}},e}();t.default=n},"./src/demux/transmuxer-interface.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return c}));var i=r("./node_modules/webworkify-webpack/index.js"),s=r("./src/events.ts"),n=r("./src/demux/transmuxer.ts"),a=r("./src/utils/logger.ts"),o=r("./src/errors.ts"),l=r("./src/utils/mediasource-helper.ts"),h=r("./node_modules/eventemitter3/index.js"),u=Object(l.getMediaSource)()||{isTypeSupported:function(){return!1}},c=function(){function e(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 d=e.config,f=function(t,r){(r=r||{}).frag=c.frag,r.id=c.id,e.trigger(t,r)};this.observer=new h.EventEmitter,this.observer.on(s.Events.FRAG_DECRYPTED,f),this.observer.on(s.Events.ERROR,f);var g={mp4:u.isTypeSupported("video/mp4"),mpeg:u.isTypeSupported("audio/mpeg"),mp3:u.isTypeSupported('audio/mp4; codecs="mp3"')},p=navigator.vendor;if(d.enableWorker&&"undefined"!=typeof Worker){var v;a.logger.log("demuxing in webworker");try{v=this.worker=i("./src/demux/transmuxer-worker.ts"),this.onwmsg=this.onWorkerMessage.bind(this),v.addEventListener("message",this.onwmsg),v.onerror=function(t){e.trigger(s.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+")")})},v.postMessage({cmd:"init",typeSupported:g,vendor:p,id:t,config:JSON.stringify(d)})}catch(e){a.logger.warn("Error in worker:",e),a.logger.error("Error while initializing DemuxerWorker, fallback to inline"),v&&self.URL.revokeObjectURL(v.objectURL),this.transmuxer=new n.default(this.observer,g,d,p,t),this.worker=null}}else this.transmuxer=new n.default(this.observer,g,d,p,t)}var t=e.prototype;return t.destroy=function(){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},t.push=function(e,t,r,i,s,o,l,h,u,c){var d,f,g=this;u.transmuxing.start=self.performance.now();var p=this.transmuxer,v=this.worker,m=o?o.start:s.start,y=s.decryptdata,E=this.frag,S=!(E&&s.cc===E.cc),T=!(E&&u.level===E.level),b=E?u.sn-E.sn:-1,_=this.part?u.part-this.part.index:1,L=!T&&(1===b||0===b&&1===_),A=self.performance.now();(T||b||0===s.stats.parsing.start)&&(s.stats.parsing.start=A),!o||!_&&L||(o.stats.parsing.start=A);var D=!(E&&(null===(d=s.initSegment)||void 0===d?void 0:d.url)===(null===(f=E.initSegment)||void 0===f?void 0:f.url)),w=new n.TransmuxState(S,L,h,T,m,D);if(!L||S||D){a.logger.log("[transmuxer-interface, "+s.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+S+"\n trackSwitch: "+T+"\n contiguous: "+L+"\n accurateTimeOffset: "+h+"\n timeOffset: "+m+"\n initSegmentChange: "+D);var I=new n.TransmuxConfig(r,i,t,l,c);this.configureTransmuxer(I)}if(this.frag=s,this.part=o,v)v.postMessage({cmd:"demux",data:e,decryptdata:y,chunkMeta:u,state:w},e instanceof ArrayBuffer?[e]:[]);else if(p){var P=p.push(e,y,u,w);Object(n.isPromise)(P)?P.then((function(e){g.handleTransmuxComplete(e)})):this.handleTransmuxComplete(P)}},t.flush=function(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 s=r.flush(e);Object(n.isPromise)(s)?s.then((function(r){t.handleFlushResult(r,e)})):this.handleFlushResult(s,e)}},t.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},t.onWorkerMessage=function(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)}},t.configureTransmuxer=function(e){var t=this.worker,r=this.transmuxer;t?t.postMessage({cmd:"configure",config:e}):r&&r.configure(e)},t.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}()},"./src/demux/transmuxer-worker.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return o}));var i=r("./src/demux/transmuxer.ts"),s=r("./src/events.ts"),n=r("./src/utils/logger.ts"),a=r("./node_modules/eventemitter3/index.js");function o(e){var t=new a.EventEmitter,r=function(t,r){e.postMessage({event:t,data:r})};t.on(s.Events.FRAG_DECRYPTED,r),t.on(s.Events.ERROR,r),e.addEventListener("message",(function(s){var a=s.data;switch(a.cmd){case"init":var o=JSON.parse(a.config);e.transmuxer=new i.default(t,a.typeSupported,o,a.vendor,a.id),Object(n.enableLogs)(o.debug),r("init",null);break;case"configure":e.transmuxer.configure(a.config);break;case"demux":var h=e.transmuxer.push(a.data,a.decryptdata,a.chunkMeta,a.state);Object(i.isPromise)(h)?h.then((function(t){l(e,t)})):l(e,h);break;case"flush":var c=a.chunkMeta,d=e.transmuxer.flush(c);Object(i.isPromise)(d)?d.then((function(t){u(e,t,c)})):u(e,d,c)}}))}function l(e,t){if((r=t.remuxResult).audio||r.video||r.text||r.id3||r.initSegment){var r,i=[],s=t.remuxResult,n=s.audio,a=s.video;n&&h(i,n),a&&h(i,a),e.postMessage({event:"transmuxComplete",data:t},i)}}function h(e,t){t.data1&&e.push(t.data1.buffer),t.data2&&e.push(t.data2.buffer)}function u(e,t,r){t.forEach((function(t){l(e,t)})),e.postMessage({event:"flush",data:r})}},"./src/demux/transmuxer.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return y})),r.d(t,"isPromise",(function(){return S})),r.d(t,"TransmuxConfig",(function(){return T})),r.d(t,"TransmuxState",(function(){return b}));var i,s=r("./src/events.ts"),n=r("./src/errors.ts"),a=r("./src/crypt/decrypter.ts"),o=r("./src/demux/aacdemuxer.ts"),l=r("./src/demux/mp4demuxer.ts"),h=r("./src/demux/tsdemuxer.ts"),u=r("./src/demux/mp3demuxer.ts"),c=r("./src/remux/mp4-remuxer.ts"),d=r("./src/remux/passthrough-remuxer.ts"),f=r("./src/demux/chunk-cache.ts"),g=r("./src/utils/mp4-tools.ts"),p=r("./src/utils/logger.ts");try{i=self.performance.now.bind(self.performance)}catch(e){p.logger.debug("Unable to use Performance API on this environment"),i=self.Date.now}var v=[{demux:h.default,remux:c.default},{demux:l.default,remux:d.default},{demux:o.default,remux:c.default},{demux:u.default,remux:c.default}],m=1024;v.forEach((function(e){var t=e.demux;m=Math.max(m,t.minProbeByteLength)}));var y=function(){function e(e,t,r,i,s){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=s}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,r,s){var n=this,a=r.transmuxing;a.executeStart=i();var o=new Uint8Array(e),l=this.cache,h=this.config,u=this.currentTransmuxState,c=this.transmuxConfig;s&&(this.currentTransmuxState=s);var d=function(e,t){var r=null;return e.byteLength>0&&null!=t&&null!=t.key&&null!==t.iv&&null!=t.method&&(r=t),r}(o,t);if(d&&"AES-128"===d.method){var f=this.getDecrypter();if(!h.enableSoftwareAES)return this.decryptionPromise=f.webCryptoDecrypt(o,d.key.buffer,d.iv.buffer).then((function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t})),this.decryptionPromise;var p=f.softwareDecrypt(o,d.key.buffer,d.iv.buffer);if(!p)return a.executeEnd=i(),E(r);o=new Uint8Array(p)}var v=s||u,m=v.contiguous,y=v.discontinuity,S=v.trackSwitch,T=v.accurateTimeOffset,b=v.timeOffset,_=v.initSegmentChange,L=c.audioCodec,A=c.videoCodec,D=c.defaultInitPts,w=c.duration,I=c.initSegmentData;if((y||S||_)&&this.resetInitSegment(I,L,A,w),(y||_)&&this.resetInitialTimestamp(D),m||this.resetContiguity(),this.needsProbing(o,y,S)){if(l.dataLength){var P=l.flush();o=Object(g.appendUint8Array)(P,o)}this.configureTransmuxer(o,c)}var R=this.transmux(o,d,b,T,r),C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,a.executeEnd=i(),R},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=i();var a=this.decrypter,o=this.cache,l=this.currentTransmuxState,h=this.decryptionPromise;if(h)return h.then((function(){return t.flush(e)}));var u=[],c=l.timeOffset;if(a){var d=a.flush();d&&u.push(this.push(d,null,e))}var f=o.dataLength;o.reset();var g=this.demuxer,p=this.remuxer;if(!g||!p)return f>=m&&this.observer.emit(s.Events.ERROR,s.Events.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=i(),[E(e)];var v=g.flush(c);return S(v)?v.then((function(r){return t.flushRemux(u,r,e),u})):(this.flushRemux(u,v,e),u)},t.flushRemux=function(e,t,r){var s=t.audioTrack,n=t.avcTrack,a=t.id3Track,o=t.textTrack,l=this.currentTransmuxState,h=l.accurateTimeOffset,u=l.timeOffset;p.logger.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var c=this.remuxer.remux(s,n,a,o,u,h,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=i()},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i){var s=this.demuxer,n=this.remuxer;s&&n&&(s.resetInitSegment(t,r,i),n.resetInitSegment(e,t,r))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,r,i,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,s):this.transmuxUnencrypted(e,r,i,s)},t.transmuxUnencrypted=function(e,t,r,i){var s=this.demuxer.demux(e,t,!1,!this.config.progressive),n=s.audioTrack,a=s.avcTrack,o=s.id3Track,l=s.textTrack;return{remuxResult:this.remuxer.remux(n,a,o,l,t,r,!1,this.id),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,s){var n=this;return this.demuxer.demuxSampleAes(e,t,r).then((function(e){return{remuxResult:n.remuxer.remux(e.audioTrack,e.avcTrack,e.id3Track,e.textTrack,r,i,!1,n.id),chunkMeta:s}}))},t.configureTransmuxer=function(e,t){for(var r,i=this.config,s=this.observer,n=this.typeSupported,a=this.vendor,o=t.audioCodec,h=t.defaultInitPts,u=t.duration,c=t.initSegmentData,f=t.videoCodec,g=0,m=v.length;g>4>1){if((C=I+5+t[I+4])===I+188)continue}else C=I+4;switch(R){case f:P&&(g&&(n=m(g))&&this.parseAVCPES(n,!1),g={data:[],size:0}),g&&(g.data.push(t.subarray(C,I+188)),g.size+=I+188-C);break;case y:P&&(S&&(n=m(S))&&(o.isAAC?this.parseAACPES(n):this.parseMPEGPES(n)),S={data:[],size:0}),S&&(S.data.push(t.subarray(C,I+188)),S.size+=I+188-C);break;case E:P&&(T&&(n=m(T))&&this.parseID3PES(n),T={data:[],size:0}),T&&(T.data.push(t.subarray(C,I+188)),T.size+=I+188-C);break;case 0:P&&(C+=t[C]+1),L=this._pmtId=p(t,C);break;case L:P&&(C+=t[C]+1);var k=v(t,C,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,i);(f=k.avc)>0&&(a.pid=f),(y=k.audio)>0&&(o.pid=y,o.isAAC=k.isAAC),(E=k.id3)>0&&(d.pid=E),b&&!_&&(u.logger.log("reparse from beginning"),b=!1,I=D-188),_=this.pmtParsed=!0;break;case 17:case 8191:break;default:b=!0}}else w++;w>0&&this.observer.emit(l.Events.ERROR,l.Events.ERROR,{type:c.ErrorTypes.MEDIA_ERROR,details:c.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"Found "+w+" TS packet/s that do not start with 0x47"}),a.pesData=g,o.pesData=S,d.pesData=T;var O={audioTrack:o,avcTrack:a,id3Track:d,textTrack:this._txtTrack};return s&&this.extractRemainingSamples(O),O},t.flush=function(){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},t.extractRemainingSamples=function(e){var t,r=e.audioTrack,i=e.avcTrack,s=e.id3Track,n=i.pesData,a=r.pesData,o=s.pesData;n&&(t=m(n))?(this.parseAVCPES(t,!0),i.pesData=null):i.pesData=n,a&&(t=m(a))?(r.isAAC?this.parseAACPES(t):this.parseMPEGPES(t),r.pesData=null):(null!=a&&a.size&&u.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=a),o&&(t=m(o))?(this.parseID3PES(t),s.pesData=null):s.pesData=o},t.demuxSampleAes=function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new o.default(this.observer,this.config,t);return this.decrypt(i,s)},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,s=e.avcTrack;i.samples&&i.isAAC?t.decryptAacSamples(i.samples,0,(function(){s.samples?t.decryptAvcSamples(s.samples,0,0,(function(){r(e)})):r(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(function(){r(e)}))}))},t.destroy=function(){this._initPTS=this._initDTS=null,this._duration=0},t.parseAVCPES=function(e,t){var r,i=this,s=this._avcTrack,o=this.parseAVCNALu(e.data),l=this.avcSample,h=!1;e.data=null,l&&o.length&&!s.audFound&&(y(l,s),l=this.avcSample=g(!1,e.pts,e.dts,"")),o.forEach((function(t){switch(t.type){case 1:r=!0,l||(l=i.avcSample=g(!0,e.pts,e.dts,"")),l.frame=!0;var o=t.data;if(h&&o.length>4){var u=new n.default(o).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(l.key=!0)}break;case 5:r=!0,l||(l=i.avcSample=g(!0,e.pts,e.dts,"")),l.key=!0,l.frame=!0;break;case 6:r=!0;var c=new n.default(S(t.data));c.readUByte();for(var d=0,f=0,p=!1,v=0;!p&&c.bytesAvailable>1;){d=0;do{d+=v=c.readUByte()}while(255===v);f=0;do{f+=v=c.readUByte()}while(255===v);if(4===d&&0!==c.bytesAvailable){if(p=!0,181===c.readUByte()&&49===c.readUShort()&&1195456820===c.readUInt()&&3===c.readUByte()){for(var m=c.readUByte(),T=31&m,b=[m,c.readUByte()],_=0;_16){for(var L=[],A=0;A<16;A++)L.push(c.readUByte().toString(16)),3!==A&&5!==A&&7!==A&&9!==A||L.push("-");for(var D=f-16,w=new Uint8Array(D),I=0;I=0){var c={data:e.subarray(h,l-n-1),type:u};o.push(c)}else{var d=this.getLastNalUnit();if(d&&(a&&l<=4-a&&d.state&&(d.data=d.data.subarray(0,d.data.byteLength-a)),(r=l-n-1)>0)){var f=new Uint8Array(d.data.byteLength+r);f.set(d.data,0),f.set(e.subarray(0,r),d.data.byteLength),d.data=f,d.state=0}}l=0&&n>=0){var g={data:e.subarray(h,i),type:u,state:n};o.push(g)}if(0===o.length){var p=this.getLastNalUnit();if(p){var v=new Uint8Array(p.data.byteLength+e.byteLength);v.set(p.data,0),v.set(e,p.data.byteLength),p.data=v}}return s.naluState=n,o},t.parseAACPES=function(e){var t,r,s,n,a,o=0,h=this._audioTrack,d=this.aacOverFlow,f=e.data;if(d){this.aacOverFlow=null;var g=d.sample.unit.byteLength,p=Math.min(d.missing,g),v=g-p;d.sample.unit.set(f.subarray(0,p),v),h.samples.push(d.sample),o=d.missing}for(t=o,r=f.length;t1;){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 h=t[7];192&h&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&h?s-(n=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>54e5&&(u.logger.warn(Math.round((s-n)/9e4)+"s delta between PTS and DTS, align them"),s=n):n=s);var c=(i=t[8])+9;if(e.size<=c)return null;e.size-=c;for(var d=new Uint8Array(e.size),f=0,g=o.length;fp){c-=p;continue}t=t.subarray(c),p-=c,c=0}d.set(t,a),a+=p}return r&&(r-=i+3),{data:d,pts:s,dts:n,len:r}}return null}function y(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 s=r[i-1];e.pts=s.pts,e.dts=s.dts}t.samples.push(e)}e.debug.length&&u.logger.log(e.pts+"/"+e.dts+":"+e.debug)}function E(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.ptst)return i;return 0}},{key:"maxAutoLevel",get:function(){var e=this.levels,t=this.autoLevelCapping;return-1===t&&e&&e.length?e.length-1:t}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&m(t.prototype,r),y&&m(t,y),e}();y.defaultConfig=void 0},"./src/is-supported.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"isSupported",(function(){return n})),r.d(t,"changeTypeSupported",(function(){return a}));var i=r("./src/utils/mediasource-helper.ts");function s(){return self.SourceBuffer||self.WebKitSourceBuffer}function n(){var e=Object(i.getMediaSource)();if(!e)return!1;var t=s(),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 a(){var e,t=s();return"function"==typeof(null==t||null===(e=t.prototype)||void 0===e?void 0:e.changeType)}},"./src/loader/fragment-loader.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return c})),r.d(t,"LoadError",(function(){return f}));var i=r("./src/polyfills/number.ts"),s=r("./src/errors.ts");function n(e){var t="function"==typeof Map?new Map:void 0;return n=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;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,i)}function i(){return a(e,arguments,h(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),l(i,e)},n(e)}function a(e,t,r){return a=o()?Reflect.construct:function(e,t,r){var i=[null];i.push.apply(i,t);var s=new(Function.bind.apply(e,i));return r&&l(s,r.prototype),s},a.apply(null,arguments)}function o(){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 l(e,t){return l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},l(e,t)}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}var u=Math.pow(2,17),c=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t){var r=this,i=e.url;if(!i)return Promise.reject(new f({type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var n=this.config,a=n.fLoader,o=n.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var h=r.loader=e.loader=a?new a(n):new o(n),c=d(e),g={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout,highWaterMark:u};e.stats=h.stats,h.load(c,g,{onSuccess:function(t,s,n,a){r.resetLoader(e,h),i({frag:e,part:null,payload:t.data,networkDetails:a})},onError:function(t,i,n){r.resetLoader(e,h),l(new f({type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:t,networkDetails:n}))},onAbort:function(t,i,n){r.resetLoader(e,h),l(new f({type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,networkDetails:n}))},onTimeout:function(t,i,n){r.resetLoader(e,h),l(new f({type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,networkDetails:n}))},onProgress:function(r,i,s,n){t&&t({frag:e,part:null,payload:s,networkDetails:n})}})}))},t.loadPart=function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,o=n.loader;return new Promise((function(l,h){i.loader&&i.loader.destroy();var c=i.loader=e.loader=a?new a(n):new o(n),g=d(e,t),p={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:n.fragLoadingMaxRetryTimeout,highWaterMark:u};t.stats=c.stats,c.load(g,p,{onSuccess:function(s,n,a,o){i.resetLoader(e,c),i.updateStatsFromPart(e,t);var h={frag:e,part:t,payload:s.data,networkDetails:o};r(h),l(h)},onError:function(r,n,a){i.resetLoader(e,c),h(new f({type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:r,networkDetails:a}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,c),h(new f({type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,networkDetails:a}))},onTimeout:function(r,n,a){i.resetLoader(e,c),h(new f({type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,networkDetails:a}))}})}))},t.updateStatsFromPart=function(e,t){var r=e.stats,i=t.stats,s=i.total;if(r.loaded+=i.loaded,s){var n=Math.round(e.duration/t.duration),a=Math.min(Math.round(r.loaded/s),n),o=(n-a)*Math.round(r.loaded/a);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,h=i.loading;l.start?l.first+=h.first-h.start:(l.start=h.start,l.first=h.first),l.end=h.end},t.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function d(e,t){void 0===t&&(t=null);var r=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;return Object(i.isFiniteNumber)(n)&&Object(i.isFiniteNumber)(a)&&(s.rangeStart=n,s.rangeEnd=a),s}var f=function(e){var t,r;function i(t){for(var r,i=arguments.length,s=new Array(i>1?i-1:0),n=1;n>8*(15-r)&255;return t},r.setDecryptDataFromLevelKey=function(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},r.setElementaryStreamInfo=function(e,t,r,i,s,n){void 0===n&&(n=!1);var a=this.elementaryStreams,o=a[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,s)):a[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:s,partial:n}},r.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[i.AUDIO]=null,e[i.VIDEO]=null,e[i.AUDIOVIDEO]=null},d(t,[{key:"decryptdata",get:function(){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&&a.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(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(s.isFiniteNumber)(this.programDateTime))return null;var e=Object(s.isFiniteNumber)(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;return!(null===(e=this.decryptdata)||void 0===e||!e.keyFormat||!this.decryptdata.uri)}}]),t}(f),p=function(e){function t(t,r,i,s,n){var a;(a=e.call(this,i)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.stats=new l.LoadStats,a.duration=t.decimalFloatingPoint("DURATION"),a.gap=t.bool("GAP"),a.independent=t.bool("INDEPENDENT"),a.relurl=t.enumeratedString("URI"),a.fragment=r,a.index=s;var o=t.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,n),n&&(a.fragOffset=n.fragOffset+n.duration),a}return h(t,e),d(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}]),t}(f)},"./src/loader/key-loader.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return a}));var i=r("./src/events.ts"),s=r("./src/errors.ts"),n=r("./src/utils/logger.ts"),a=function(){function e(e){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=e,this._registerListeners()}var t=e.prototype;return t._registerListeners=function(){this.hls.on(i.Events.KEY_LOADING,this.onKeyLoading,this)},t._unregisterListeners=function(){this.hls.off(i.Events.KEY_LOADING,this.onKeyLoading)},t.destroy=function(){for(var e in this._unregisterListeners(),this.loaders){var t=this.loaders[e];t&&t.destroy()}this.loaders={}},t.onKeyLoading=function(e,t){var r=t.frag,s=r.type,a=this.loaders[s];if(r.decryptdata){var o=r.decryptdata.uri;if(o!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(a&&(n.logger.warn("abort previous key loader for type:"+s),a.abort()),!o)return void n.logger.warn("key uri is falsy");var h=l.loader,u=r.loader=this.loaders[s]=new h(l);this.decrypturl=o,this.decryptkey=null;var c={url:o,frag:r,responseType:"arraybuffer"},d={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)};u.load(c,d,f)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(i.Events.KEY_LOADED,{frag:r}))}else n.logger.warn("Missing decryption data on fragment in onKeyLoading")},t.loadsuccess=function(e,t,r){var s=r.frag;s.decryptdata?(this.decryptkey=s.decryptdata.key=new Uint8Array(e.data),s.loader=null,delete this.loaders[s.type],this.hls.trigger(i.Events.KEY_LOADED,{frag:s})):n.logger.error("after key load, decryptdata unset")},t.loaderror=function(e,t){var r=t.frag,n=r.loader;n&&n.abort(),delete this.loaders[r.type],this.hls.trigger(i.Events.ERROR,{type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},t.loadtimeout=function(e,t){var r=t.frag,n=r.loader;n&&n.abort(),delete this.loaders[r.type],this.hls.trigger(i.Events.ERROR,{type:s.ErrorTypes.NETWORK_ERROR,details:s.ErrorDetails.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},e}()},"./src/loader/level-details.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"LevelDetails",(function(){return n}));var i=r("./src/polyfills/number.ts");function s(e,t){for(var r=0;re.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},t=e,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Object(i.isFiniteNumber)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){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(){var e;return null!==(e=this.fragments)&&void 0!==e&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!==(e=this.partList)&&void 0!==e&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var e;return null!==(e=this.partList)&&void 0!==e&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&s(t.prototype,r),n&&s(t,n),e}()},"./src/loader/level-key.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"LevelKey",(function(){return n}));var i=r("./node_modules/url-toolkit/src/url-toolkit.js");function s(e,t){for(var r=0;r2){var r=t.shift()+".";return r+=parseInt(t.shift()).toString(16),r+=("000"+parseInt(t.shift()).toString(16)).substr(-4)}return e},e.resolve=function(e,t){return s.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.parseMasterPlaylist=function(t,r){var i,s=[],n={},a=!1;for(c.lastIndex=0;null!=(i=c.exec(t));)if(i[1]){var o=new l.AttrList(i[1]),h={attrs:o,bitrate:o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),name:o.NAME,url:e.resolve(i[2],r)},u=o.decimalResolution("RESOLUTION");u&&(h.width=u.width,h.height=u.height),m((o.CODECS||"").split(/[ ,]+/).filter((function(e){return e})),h),h.videoCodec&&-1!==h.videoCodec.indexOf("avc1")&&(h.videoCodec=e.convertAVC1ToAVCOTI(h.videoCodec)),s.push(h)}else if(i[3]){var d=new l.AttrList(i[3]);d["DATA-ID"]&&(a=!0,n[d["DATA-ID"]]=d)}return{levels:s,sessionData:a?n:null}},e.parseMasterPlaylistMedia=function(t,r,i,s){var n;void 0===s&&(s=[]);var a=[],o=0;for(d.lastIndex=0;null!==(n=d.exec(t));){var h=new l.AttrList(n[1]);if(h.TYPE===i){var u={attrs:h,bitrate:0,id:o++,groupId:h["GROUP-ID"],instreamId:h["INSTREAM-ID"],name:h.NAME||h.LANGUAGE||"",type:i,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:h.LANGUAGE,url:h.URI?e.resolve(h.URI,r):""};if(s.length){var c=e.findGroup(s,u.groupId)||s[0];y(u,c,"audioCodec"),y(u,c,"textCodec")}a.push(u)}}return a},e.parseLevelPlaylist=function(e,t,r,u,c){var d,v,m,y=new a.LevelDetails(t),S=y.fragments,T=null,b=0,_=0,L=0,A=0,D=null,w=new n.Fragment(u,t),I=-1,P=!1;for(f.lastIndex=0,y.m3u8=e;null!==(d=f.exec(e));){P&&(P=!1,(w=new n.Fragment(u,t)).start=L,w.sn=b,w.cc=A,w.level=r,T&&(w.initSegment=T,w.rawProgramDateTime=T.rawProgramDateTime));var R=d[1];if(R){w.duration=parseFloat(R);var C=(" "+d[2]).slice(1);w.title=C||null,w.tagList.push(C?["INF",R,C]:["INF",R])}else if(d[3])Object(i.isFiniteNumber)(w.duration)&&(w.start=L,m&&(w.levelkey=m),w.sn=b,w.level=r,w.cc=A,w.urlId=c,S.push(w),w.relurl=(" "+d[3]).slice(1),E(w,D),D=w,L+=w.duration,b++,_=0,P=!0);else if(d[4]){var k=(" "+d[4]).slice(1);D?w.setByteRange(k,D):w.setByteRange(k)}else if(d[5])w.rawProgramDateTime=(" "+d[5]).slice(1),w.tagList.push(["PROGRAM-DATE-TIME",w.rawProgramDateTime]),-1===I&&(I=S.length);else{if(!(d=d[0].match(g))){h.logger.warn("No matches on slow regex match for level playlist!");continue}for(v=1;v-1){h.logger.warn("Keyformat "+V+" is not supported from the manifest");continue}if("identity"!==V)continue;H&&(m=o.LevelKey.fromURL(t,$),$&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(H)>=0&&(m.method=H,m.keyFormat=V,q&&(m.keyID=q),K&&(m.keyFormatVersions=K),m.iv=W));break;case"START":var z=new l.AttrList(M).decimalFloatingPoint("TIME-OFFSET");Object(i.isFiniteNumber)(z)&&(y.startTimeOffset=z);break;case"MAP":var Y=new l.AttrList(M);w.relurl=Y.URI,Y.BYTERANGE&&w.setByteRange(Y.BYTERANGE),w.level=r,w.sn="initSegment",m&&(w.levelkey=m),w.initSegment=null,T=w,P=!0;break;case"SERVER-CONTROL":var X=new l.AttrList(M);y.canBlockReload=X.bool("CAN-BLOCK-RELOAD"),y.canSkipUntil=X.optionalFloat("CAN-SKIP-UNTIL",0),y.canSkipDateRanges=y.canSkipUntil>0&&X.bool("CAN-SKIP-DATERANGES"),y.partHoldBack=X.optionalFloat("PART-HOLD-BACK",0),y.holdBack=X.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var Q=new l.AttrList(M);y.partTarget=Q.decimalFloatingPoint("PART-TARGET");break;case"PART":var J=y.partList;J||(J=y.partList=[]);var Z=_>0?J[J.length-1]:void 0,ee=_++,te=new n.Part(new l.AttrList(M),w,t,ee,Z);J.push(te),w.duration+=te.duration;break;case"PRELOAD-HINT":var re=new l.AttrList(M);y.preloadHint=re;break;case"RENDITION-REPORT":var ie=new l.AttrList(M);y.renditionReports=y.renditionReports||[],y.renditionReports.push(ie);break;default:h.logger.warn("line parsed but not handled: "+d)}}}D&&!D.relurl?(S.pop(),L-=D.duration,y.partList&&(y.fragmentHint=D)):y.partList&&(E(w,D),w.cc=A,y.fragmentHint=w);var se=S.length,ne=S[0],ae=S[se-1];if((L+=y.skippedSegments*y.targetduration)>0&&se&&ae){y.averagetargetduration=L/se;var oe=ae.sn;y.endSN="initSegment"!==oe?oe:0,ne&&(y.startCC=ne.cc,ne.initSegment||y.fragments.every((function(e){return e.relurl&&(t=e.relurl,p.test(null!=(r=null===(i=s.parseURL(t))||void 0===i?void 0:i.path)?r:""));var t,r,i}))&&(h.logger.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(w=new n.Fragment(u,t)).relurl=ae.relurl,w.level=r,w.sn="initSegment",ne.initSegment=w,y.needSidxRanges=!0))}else y.endSN=0,y.startCC=0;return y.fragmentHint&&(L+=y.fragmentHint.duration),y.totalduration=L,y.endCC=A,I>0&&function(e,t){for(var r=e[t],i=t;i--;){var s=e[i];if(!s)return;s.programDateTime=r.programDateTime-1e3*s.duration,r=s}}(S,I),y},e}();function m(e,t){["video","audio","text"].forEach((function(r){var i=e.filter((function(e){return Object(u.isCodecType)(e,r)}));if(i.length){var s=i.filter((function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)}));t[r+"Codec"]=s.length>0?s[0]:i[0],e=e.filter((function(e){return-1===i.indexOf(e)}))}})),t.unknownCodecs=e}function y(e,t,r){var i=t[r];i&&(e[r]=i)}function E(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":function(e,t,r){"use strict";r.r(t);var i=r("./src/polyfills/number.ts"),s=r("./src/events.ts"),n=r("./src/errors.ts"),a=r("./src/utils/logger.ts"),o=r("./src/utils/mp4-tools.ts"),l=r("./src/loader/m3u8-parser.ts"),h=r("./src/types/loader.ts"),u=r("./src/utils/attr-list.ts");function c(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var d=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.hls=e,this.registerListeners()}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(s.Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(s.Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(s.Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},t.unregisterListeners=function(){var e=this.hls;e.off(s.Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(s.Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(s.Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(s.Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},t.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,s=new(r||i)(t);return e.loader=s,this.loaders[e.type]=s,s},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var r=t.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:h.PlaylistContextType.MANIFEST,url:r,deliveryDirectives:null})},t.onLevelLoading=function(e,t){var r=t.id,i=t.level,s=t.url,n=t.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:h.PlaylistContextType.LEVEL,url:s,deliveryDirectives:n})},t.onAudioTrackLoading=function(e,t){var r=t.id,i=t.groupId,s=t.url,n=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:h.PlaylistContextType.AUDIO_TRACK,url:s,deliveryDirectives:n})},t.onSubtitleTrackLoading=function(e,t){var r=t.id,i=t.groupId,s=t.url,n=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:h.PlaylistContextType.SUBTITLE_TRACK,url:s,deliveryDirectives:n})},t.load=function(e){var t,r,i,s,n,o,l=this.hls.config,u=this.getInternalLoader(e);if(u){var c=u.context;if(c&&c.url===e.url)return void a.logger.trace("[playlist-loader]: playlist request ongoing");a.logger.log("[playlist-loader]: aborting previous loader for type: "+e.type),u.abort()}switch(e.type){case h.PlaylistContextType.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,s=l.manifestLoadingRetryDelay,n=l.manifestLoadingMaxRetryTimeout;break;case h.PlaylistContextType.LEVEL:case h.PlaylistContextType.AUDIO_TRACK:case h.PlaylistContextType.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,s=l.levelLoadingRetryDelay,n=l.levelLoadingMaxRetryTimeout}if(u=this.createInternalLoader(e),null!==(t=e.deliveryDirectives)&&void 0!==t&&t.part&&(e.type===h.PlaylistContextType.LEVEL&&null!==e.level?o=this.hls.levels[e.level].details:e.type===h.PlaylistContextType.AUDIO_TRACK&&null!==e.id?o=this.hls.audioTracks[e.id].details:e.type===h.PlaylistContextType.SUBTITLE_TRACK&&null!==e.id&&(o=this.hls.subtitleTracks[e.id].details),o)){var d=o.partTarget,f=o.targetduration;d&&f&&(i=Math.min(1e3*Math.max(3*d,.8*f),i))}var g={timeout:i,maxRetry:r,retryDelay:s,maxRetryDelay:n,highWaterMark:0},p={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(e,g,p)},t.loadsuccess=function(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 s=e.data;0===s.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),s.indexOf("#EXTINF:")>0||s.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)},t.loaderror=function(e,t,r){void 0===r&&(r=null),this.handleNetworkError(t,r,!1,e)},t.loadtimeout=function(e,t,r){void 0===r&&(r=null),this.handleNetworkError(t,r,!0)},t.handleMasterPlaylist=function(e,t,r,i){var n=this.hls,o=e.data,h=c(e,r),d=l.default.parseMasterPlaylist(o,h),f=d.levels,g=d.sessionData;if(f.length){var p=f.map((function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}})),v=f.map((function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}})),m=l.default.parseMasterPlaylistMedia(o,h,"AUDIO",p),y=l.default.parseMasterPlaylistMedia(o,h,"SUBTITLES",v),E=l.default.parseMasterPlaylistMedia(o,h,"CLOSED-CAPTIONS");m.length&&(m.some((function(e){return!e.url}))||!f[0].audioCodec||f[0].attrs.AUDIO||(a.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new u.AttrList({}),bitrate:0,url:""}))),n.trigger(s.Events.MANIFEST_LOADED,{levels:f,audioTracks:m,subtitles:y,captions:E,url:h,stats:t,networkDetails:i,sessionData:g})}else this.handleManifestParsingError(e,r,"no level found in manifest",i)},t.handleTrackOrLevelPlaylist=function(e,t,r,a){var o=this.hls,d=r.id,f=r.level,g=r.type,p=c(e,r),v=Object(i.isFiniteNumber)(d)?d:0,m=Object(i.isFiniteNumber)(f)?f:v,y=function(e){switch(e.type){case h.PlaylistContextType.AUDIO_TRACK:return h.PlaylistLevelType.AUDIO;case h.PlaylistContextType.SUBTITLE_TRACK:return h.PlaylistLevelType.SUBTITLE;default:return h.PlaylistLevelType.MAIN}}(r),E=l.default.parseLevelPlaylist(e.data,p,m,y,v);if(E.fragments.length){if(g===h.PlaylistContextType.MANIFEST){var S={attrs:new u.AttrList({}),bitrate:0,details:E,name:"",url:p};o.trigger(s.Events.MANIFEST_LOADED,{levels:[S],audioTracks:[],url:p,stats:t,networkDetails:a,sessionData:null})}if(t.parsing.end=performance.now(),E.needSidxRanges){var T,b=null===(T=E.fragments[0].initSegment)||void 0===T?void 0:T.url;this.load({url:b,isSidxRequest:!0,type:g,level:f,levelDetails:E,id:d,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=E,this.handlePlaylistLoaded(e,t,r,a)}else o.trigger(s.Events.ERROR,{type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:p,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},t.handleSidxRequest=function(e,t){var r=Object(o.parseSegmentIndex)(new Uint8Array(e.data));if(r){var i=r.references,s=t.levelDetails;i.forEach((function(e,t){var i=e.info,n=s.fragments[t];0===n.byteRange.length&&n.setByteRange(String(1+i.end-i.start)+"@"+String(i.start)),n.initSegment&&n.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}))}},t.handleManifestParsingError=function(e,t,r,i){this.hls.trigger(s.Events.ERROR,{type:n.ErrorTypes.NETWORK_ERROR,details:n.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===h.PlaylistContextType.MANIFEST,url:e.url,reason:r,response:e,context:t,networkDetails:i})},t.handleNetworkError=function(e,t,r,i){void 0===r&&(r=!1),a.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=n.ErrorDetails.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case h.PlaylistContextType.MANIFEST:o=r?n.ErrorDetails.MANIFEST_LOAD_TIMEOUT:n.ErrorDetails.MANIFEST_LOAD_ERROR,l=!0;break;case h.PlaylistContextType.LEVEL:o=r?n.ErrorDetails.LEVEL_LOAD_TIMEOUT:n.ErrorDetails.LEVEL_LOAD_ERROR,l=!1;break;case h.PlaylistContextType.AUDIO_TRACK:o=r?n.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:n.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case h.PlaylistContextType.SUBTITLE_TRACK:o=r?n.ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:n.ErrorDetails.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var c={type:n.ErrorTypes.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,networkDetails:t};i&&(c.response=i),this.hls.trigger(s.Events.ERROR,c)},t.handlePlaylistLoaded=function(e,t,r,i){var n=r.type,a=r.level,o=r.id,l=r.groupId,u=r.loader,c=r.levelDetails,d=r.deliveryDirectives;if(null!=c&&c.targetduration){if(u)switch(c.live&&(u.getCacheAge&&(c.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(c.ageHeader)||(c.ageHeader=0)),n){case h.PlaylistContextType.MANIFEST:case h.PlaylistContextType.LEVEL:this.hls.trigger(s.Events.LEVEL_LOADED,{details:c,level:a||0,id:o||0,stats:t,networkDetails:i,deliveryDirectives:d});break;case h.PlaylistContextType.AUDIO_TRACK:this.hls.trigger(s.Events.AUDIO_TRACK_LOADED,{details:c,id:o||0,groupId:l||"",stats:t,networkDetails:i,deliveryDirectives:d});break;case h.PlaylistContextType.SUBTITLE_TRACK:this.hls.trigger(s.Events.SUBTITLE_TRACK_LOADED,{details:c,id:o||0,groupId:l||"",stats:t,networkDetails:i,deliveryDirectives:d})}}else this.handleManifestParsingError(e,r,"invalid target duration",i)},e}();t.default=d},"./src/polyfills/number.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"isFiniteNumber",(function(){return i})),r.d(t,"MAX_SAFE_INTEGER",(function(){return s}));var i=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},s=Number.MAX_SAFE_INTEGER||9007199254740991},"./src/remux/aac-helper.ts":function(e,t,r){"use strict";r.r(t);var i=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){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])}else{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])}},e}();t.default=i},"./src/remux/mp4-generator.ts":function(e,t,r){"use strict";r.r(t);var i=Math.pow(2,32)-1,s=function(){function e(){}return e.init=function(){var t;for(t in e.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:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var s=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]);e.STTS=e.STSC=e.STCO=n,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,a,l,a,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,s))},e.box=function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),s=1;s>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),n=0,t=8;n>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var s=Math.floor(r/(i+1)),n=Math.floor(r%(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,t>>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,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 e.box(e.types.mvhd,a)},e.sdtp=function(t){var r,i,s=t.samples||[],n=new Uint8Array(4+s.length);for(r=0;r>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,u=t.pixelRatio[0],c=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,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]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))},e.esds=function(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]))},e.mp4a=function(t){var r=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){var r=t.samplerate;return e.box(e.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},e.stsd=function(t){return"audio"===t.type?t.isAAC||"mp3"!==t.codec?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))},e.tkhd=function(t){var r=t.id,s=t.duration*t.timescale,n=t.width,a=t.height,o=Math.floor(s/(i+1)),l=Math.floor(s%(i+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))},e.traf=function(t,r){var s=e.sdtp(t),n=t.id,a=Math.floor(r/(i+1)),o=Math.floor(r%(i+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o])),e.trun(t,s.length+16+20+8+16+8+8),s)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,s,n,a,o,l,h=t.samples||[],u=h.length,c=12+16*u,d=new Uint8Array(c);for(r+=8+c,d.set([0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,d)},e.initSegment=function(t){e.types||e.init();var r=e.moov(t),i=new Uint8Array(e.FTYP.byteLength+r.byteLength);return i.set(e.FTYP),i.set(r,e.FTYP.byteLength),i},e}();s.types=void 0,s.HDLR_TYPES=void 0,s.STTS=void 0,s.STSC=void 0,s.STCO=void 0,s.STSZ=void 0,s.VMHD=void 0,s.SMHD=void 0,s.STSD=void 0,s.FTYP=void 0,s.DINF=void 0,t.default=s},"./src/remux/mp4-remuxer.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return p})),r.d(t,"normalizePts",(function(){return v}));var i=r("./src/polyfills/number.ts"),s=r("./src/remux/aac-helper.ts"),n=r("./src/remux/mp4-generator.ts"),a=r("./src/events.ts"),o=r("./src/errors.ts"),l=r("./src/utils/logger.ts"),h=r("./src/types/loader.ts"),u=r("./src/utils/timescale-conversion.ts");function c(){return c=Object.assign||function(e){for(var t=1;t0?e:r.pts}),e[0].pts);return t&&l.logger.debug("PTS rollover detected"),r},t.remux=function(e,t,r,i,s,n,a,o){var u,c,d,f,g,p,m=s,y=s,E=e.pid>-1,S=t.pid>-1,T=t.samples.length,b=e.samples.length>0,_=T>1;if((!E||b)&&(!S||_)||this.ISGenerated||a){this.ISGenerated||(d=this.generateIS(e,t,s));var L=this.isVideoContiguous,A=-1;if(_&&(A=function(e){for(var t=0;t0){l.logger.warn("[mp4-remuxer]: Dropped "+A+" out of "+T+" video samples due to a missing keyframe");var D=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(A),t.dropped+=A,y+=(t.samples[0].pts-D)/(t.timescale||9e4)}else-1===A&&(l.logger.warn("[mp4-remuxer]: No keyframe found out of "+T+" video samples"),p=!1);if(this.ISGenerated){if(b&&_){var w=this.getVideoStartPts(t.samples),I=(v(e.samples[0].pts,w)-w)/t.inputTimeScale;m+=Math.max(0,I),y+=Math.max(0,-I)}if(b){if(e.samplerate||(l.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s)),c=this.remuxAudio(e,m,this.isAudioContiguous,n,S||_||o===h.PlaylistLevelType.AUDIO?y:void 0),_){var P=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(l.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s)),u=this.remuxVideo(t,y,L,P)}}else _&&(u=this.remuxVideo(t,y,L,0));u&&(u.firstKeyFrame=A,u.independent=-1!==A)}}return this.ISGenerated&&(r.samples.length&&(g=this.remuxID3(r,s)),i.samples.length&&(f=this.remuxText(i,s))),{audio:c,video:u,initSegment:d,independent:p,text:f,id3:g}},t.generateIS=function(e,t,r){var s,a,o,l=e.samples,h=t.samples,u=this.typeSupported,c={},d=!Object(i.isFiniteNumber)(this._initPTS),f="audio/mp4";if(d&&(s=a=1/0),e.config&&l.length&&(e.timescale=e.samplerate,e.isAAC||(u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3")),c.audio={id:"audio",container:f,codec:e.codec,initSegment:!e.isAAC&&u.mpeg?new Uint8Array(0):n.default.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(o=e.inputTimeScale,s=a=l[0].pts-Math.round(o*r))),t.sps&&t.pps&&h.length&&(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:n.default.initSegment([t]),metadata:{width:t.width,height:t.height}},d)){o=t.inputTimeScale;var g=this.getVideoStartPts(h),p=Math.round(o*r);a=Math.min(a,v(h[0].dts,g)-p),s=Math.min(s,g-p)}if(Object.keys(c).length)return this.ISGenerated=!0,d&&(this._initPTS=s,this._initDTS=a),{tracks:c,initPTS:s,timescale:o}},t.remuxVideo=function(e,t,r,i){var s,h,f,p=e.inputTimeScale,y=e.samples,E=[],S=y.length,T=this._initPTS,b=this.nextAvcDts,_=8,L=Number.POSITIVE_INFINITY,A=Number.NEGATIVE_INFINITY,D=0,w=!1;r&&null!==b||(b=t*p-(y[0].pts-v(y[0].dts,y[0].pts)));for(var I=0;IP.pts&&(D=Math.max(Math.min(D,P.pts-P.dts),-18e3)),P.dts0?I-1:I].dts&&(w=!0)}w&&y.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),h=y[0].dts,f=y[y.length-1].dts;var R=Math.round((f-h)/(S-1));if(D<0){if(D<-2*R){l.logger.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+Object(u.toMsFromMpegTsClock)(-R,!0)+" ms");for(var C=D,k=0;kR;if(x||M<-1){x?l.logger.warn("AVC: "+Object(u.toMsFromMpegTsClock)(M,!0)+" ms ("+M+"dts) hole between fragments detected, filling it"):l.logger.warn("AVC: "+Object(u.toMsFromMpegTsClock)(-M,!0)+" ms ("+M+"dts) overlapping between fragments detected"),h=b;var F=y[0].pts-M;y[0].dts=h,y[0].pts=F,l.logger.log("Video: First PTS/DTS adjusted: "+Object(u.toMsFromMpegTsClock)(F,!0)+"/"+Object(u.toMsFromMpegTsClock)(h,!0)+", delta: "+Object(u.toMsFromMpegTsClock)(M,!0)+" ms")}}g&&(h=Math.max(0,h));for(var N=0,B=0,U=0;U0?z-1:z].dts;if(ie.stretchShortVideoTrack&&null!==this.nextAudioPts){var ne=Math.floor(ie.maxBufferHole*p),ae=(i?L+i*p:this.nextAudioPts)-Y.pts;ae>ne?((s=ae-se)<0&&(s=se),l.logger.log("[mp4-remuxer]: It is approximately "+ae/90+" ms to the next segment; using duration "+s/90+" ms for the last video frame.")):s=se}else s=se}var oe=Math.round(Y.pts-Y.dts);E.push(new m(Y.key,s,Q,oe))}if(E.length&&d&&d<70){var le=E[0].flags;le.dependsOn=2,le.isNonSync=0}console.assert(void 0!==s,"mp4SampleDuration must be computed"),this.nextAvcDts=b=f+s,this.isVideoContiguous=!0;var he={data1:n.default.moof(e.sequenceNumber++,h,c({},e,{samples:E})),data2:K,startPTS:L/p,endPTS:(A+s)/p,startDTS:h/p,endDTS:b/p,type:"video",hasAudio:!1,hasVideo:!0,nb:E.length,dropped:e.dropped};return e.samples=[],e.dropped=0,console.assert(K.length,"MDAT length must not be zero"),he},t.remuxAudio=function(e,t,r,i,h){var u=e.inputTimeScale,d=u/(e.samplerate?e.samplerate:u),f=e.isAAC?1024:1152,g=f*d,p=this._initPTS,y=!e.isAAC&&this.typeSupported.mpeg,E=[],S=e.samples,T=y?0:8,b=this.nextAudioPts||-1,_=t*u;if(this.isAudioContiguous=r=r||S.length&&b>0&&(i&&Math.abs(_-b)<9e3||Math.abs(v(S[0].pts-p,_)-b)<20*g),S.forEach((function(e){e.pts=v(e.pts-p,_)})),!r||b<0){if(S=S.filter((function(e){return e.pts>=0})),!S.length)return;b=0===h?0:i?Math.max(0,_):S[0].pts}if(e.isAAC)for(var L=void 0!==h,A=this.config.maxAudioFramesDrift,D=0,w=b;D=A*g&&C<1e4&&L){var k=Math.round(R/g);(w=P-k*g)<0&&(k--,w+=g),0===D&&(this.nextAudioPts=b=w),l.logger.warn("[mp4-remuxer]: Injecting "+k+" audio frame @ "+(w/u).toFixed(3)+"s due to "+Math.round(1e3*R/u)+" ms gap.");for(var O=0;O0))return;U+=T;try{F=new Uint8Array(U)}catch(e){return void this.observer.emit(a.Events.ERROR,a.Events.ERROR,{type:o.ErrorTypes.MUX_ERROR,details:o.ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,bytes:U,reason:"fail allocating audio mdat "+U})}y||(new DataView(F.buffer).setUint32(0,U),F.set(n.default.types.mdat,4))}F.set(W,T);var q=W.byteLength;T+=q,E.push(new m(!0,f,q,0)),B=K}var V=E.length;if(V){var z=E[E.length-1];this.nextAudioPts=b=B+d*z.duration;var Y=y?new Uint8Array(0):n.default.moof(e.sequenceNumber++,N/d,c({},e,{samples:E}));e.samples=[];var X=N/u,Q=b/u,J={data1:Y,data2:F,startPTS:X,endPTS:Q,startDTS:X,endDTS:Q,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,console.assert(F.length,"MDAT length must not be zero"),J}},t.remuxEmptyAudio=function(e,t,r,i){var n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.nextAudioPts,h=(null!==o?o:i.startDTS*n)+this._initDTS,u=i.endDTS*n+this._initDTS,c=1024*a,d=Math.ceil((u-h)/c),f=s.default.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(l.logger.warn("[mp4-remuxer]: remux empty Audio"),f){for(var g=[],p=0;p4294967296;)e+=r;return e}var m=function(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 y(e)},y=function(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":function(e,t,r){"use strict";r.r(t);var i=r("./src/polyfills/number.ts"),s=r("./src/utils/mp4-tools.ts"),n=r("./src/loader/fragment.ts"),a=r("./src/utils/logger.ts"),o=function(){function e(){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 t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(e){this.initPTS=e,this.lastEndDTS=null},t.resetNextTimestamp=function(){this.lastEndDTS=null},t.resetInitSegment=function(e,t,r){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e),this.emitInitSegment=!0},t.generateInitSegment=function(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(s.parseInitSegment)(e);t||(t=h(i.audio,n.ElementaryStreamTypes.AUDIO)),r||(r=h(i.video,n.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"}:a.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=o},t.remux=function(e,t,r,n,o){var h=this.initPTS,u=this.lastEndDTS,c={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};Object(i.isFiniteNumber)(u)||(u=this.lastEndDTS=o||0);var d=t.samples;if(!d||!d.length)return c;var f={initPTS:void 0,timescale:1},g=this.initData;if(g&&g.length||(this.generateInitSegment(d),g=this.initData),!g||!g.length)return a.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1),Object(i.isFiniteNumber)(h)||(this.initPTS=f.initPTS=h=l(g,d,u));var p=Object(s.getDuration)(d,g),v=u,m=p+v;Object(s.offsetStartDTS)(g,d,h),p>0?this.lastEndDTS=m:(a.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var y=!!g.audio,E=!!g.video,S="";y&&(S+="audio"),E&&(S+="video");var T={data1:d,startPTS:v,startDTS:v,endPTS:m,endDTS:m,type:S,hasAudio:y,hasVideo:E,nb:1,dropped:0};return c.audio="audio"===T.type?T:void 0,c.video="audio"!==T.type?T:void 0,c.text=n,c.id3=r,c.initSegment=f,c},e}(),l=function(e,t,r){return Object(s.getStartDTS)(e,t)-r};function h(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===n.ElementaryStreamTypes.VIDEO?"avc1.42e01e":"mp4a.40.5"}t.default=o},"./src/task-loop.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"default",(function(){return i}));var i=function(){function e(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var t=e.prototype;return t.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},t.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},t.onHandlerDestroyed=function(){},t.hasInterval=function(){return!!this._tickInterval},t.hasNextTick=function(){return!!this._tickTimer},t.setInterval=function(e){return!this._tickInterval&&(this._tickInterval=self.setInterval(this._boundTick,e),!0)},t.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},t.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},t.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},t.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},t.doTick=function(){},e}()},"./src/types/cmcd.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"CMCDVersion",(function(){return a})),r.d(t,"CMCDObjectType",(function(){return i})),r.d(t,"CMCDStreamingFormat",(function(){return s})),r.d(t,"CMCDStreamType",(function(){return n}));var i,s,n,a=1;!function(e){e.MANIFEST="m",e.AUDIO="a",e.VIDEO="v",e.MUXED="av",e.INIT="i",e.CAPTION="c",e.TIMED_TEXT="tt",e.KEY="k",e.OTHER="o"}(i||(i={})),function(e){e.DASH="d",e.HLS="h",e.SMOOTH="s",e.OTHER="o"}(s||(s={})),function(e){e.VOD="v",e.LIVE="l"}(n||(n={}))},"./src/types/level.ts":function(e,t,r){"use strict";function i(e,t){for(var r=0;rNumber.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(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;iNumber.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=i.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(s.lastIndex=0;null!==(t=s.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},e}()},"./src/utils/binary-search.ts":function(e,t,r){"use strict";r.r(t),t.default={search:function(e,t){for(var r=0,i=e.length-1,s=null,n=null;r<=i;){var a=t(n=e[s=(r+i)/2|0]);if(a>0)r=s+1;else{if(!(a<0))return n;i=s-1}}return null}}},"./src/utils/buffer-helper.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"BufferHelper",(function(){return n}));var i=r("./src/utils/logger.ts"),s={length:0,start:function(){return 0},end:function(){return 0}},n=function(){function e(){}return e.isBuffered=function(t,r){try{if(t)for(var i=e.getBuffered(t),s=0;s=i.start(s)&&r<=i.end(s))return!0}catch(e){}return!1},e.bufferInfo=function(t,r,i){try{if(t){var s,n=e.getBuffered(t),a=[];for(s=0;sa&&(i[n-1].end=e[s].end):i.push(e[s])}else i.push(e[s])}else i=e;for(var o,l=0,h=t,u=t,c=0;c=d&&t=e&&s.logger.log(this.time+" ["+e+"] "+t)},e}(),p=function(e){for(var t=[],r=0;rl&&(this.logger.log(i.DEBUG,"Too large cursor position "+this.pos),this.pos=l)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r=144&&this.backSpace();var t=a(e);this.pos>=l?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))},t.clearFromPos=function(e){var t;for(t=e;t0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},t.getTextAndFormat=function(){return this.rows},e}(),S=function(){function e(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 E(r),this.nonDisplayedMemory=new E(r),this.lastOutputScreen=new E(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var t=e.prototype;return t.reset=function(){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},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(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)},t.insertChars=function(e){for(var t=0;t=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)},t.outputDataUpdate=function(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))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),T=function(){function e(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new g;this.channels=[null,new S(e,t,i),new S(e+1,r,i)],this.cmdHistory={a:null,b:null},this.logger=i}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var r,s,n,a=!1;this.logger.time=e;for(var o=0;o ("+p([s,n])+")"),(r=this.parseCmd(s,n))||(r=this.parseMidrow(s,n)),r||(r=this.parsePAC(s,n)),r||(r=this.parseBackgroundAttributes(s,n)),!r&&(a=this.parseChars(s,n))){var l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(i.WARNING,"No channel found yet. TEXT-MODE?")}r||a||this.logger.log(i.WARNING,"Couldn't parse cleaned data "+p([s,n])+" orig: "+p([t[o],t[o+1]]))}},t.parseCmd=function(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(_(e,t,r))return b(null,null,r),this.logger.log(i.DEBUG,"Repeated command ("+p([e,t])+") is dropped"),!0;var s=20===e||21===e||23===e?1:2,n=this.channels[s];return 20===e||21===e||28===e||29===e?32===t?n.ccRCL():33===t?n.ccBS():34===t?n.ccAOF():35===t?n.ccAON():36===t?n.ccDER():37===t?n.ccRU(2):38===t?n.ccRU(3):39===t?n.ccRU(4):40===t?n.ccFON():41===t?n.ccRDC():42===t?n.ccTR():43===t?n.ccRTD():44===t?n.ccEDM():45===t?n.ccCR():46===t?n.ccENM():47===t&&n.ccEOC():n.ccTO(t-32),b(e,t,r),this.currentChannel=s,!0},t.parseMidrow=function(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 s=this.channels[r];return!!s&&(s.ccMIDROW(t),this.logger.log(i.DEBUG,"MIDROW ("+p([e,t])+")"),!0)}return!1},t.parsePAC=function(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(_(e,t,i))return b(null,null,i),!0;var s=e<=23?1:2;r=t>=64&&t<=95?1===s?h[e]:c[e]:1===s?u[e]:d[e];var n=this.channels[s];return!!n&&(n.setPAC(this.interpretPAC(r,t)),b(e,t,i),this.currentChannel=s,!0)},t.interpretPAC=function(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},t.parseChars=function(e,t){var r,s,n=null,o=null;if(e>=25?(r=2,o=e-8):(r=1,o=e),o>=17&&o<=19?(s=17===o?t+80:18===o?t+112:t+144,this.logger.log(i.INFO,"Special char '"+a(s)+"' in channel "+r),n=[s]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]),n){var l=p(n);this.logger.log(i.DEBUG,"Char codes = "+l.join(",")),b(e,t,this.cmdHistory)}return n},t.parseBackgroundAttributes=function(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=f[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var s=e<=23?1:2;return this.channels[s].setBkgData(i),b(e,t,this.cmdHistory),!0},t.reset=function(){for(var e=0;e=16?c--:c++;var m=Object(i.fixLineBreaks)(d.trim()),y=Object(s.generateCueId)(t,r,m);e&&e.cues&&e.cues.getCueById(y)||((h=new g(t,r,m)).id=y,h.line=p+1,h.align="left",h.position=10+Math.min(80,10*Math.floor(8*c/32)),f.push(h))}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(n.addCueToTrack)(e,t)}))),f}};t.default=o},"./src/utils/discontinuities.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"findFirstFragWithCC",(function(){return a})),r.d(t,"shouldAlignOnDiscontinuities",(function(){return o})),r.d(t,"findDiscontinuousReferenceFrag",(function(){return l})),r.d(t,"adjustSlidingStart",(function(){return u})),r.d(t,"alignStream",(function(){return c})),r.d(t,"alignPDT",(function(){return d})),r.d(t,"alignFragmentByPDTDelta",(function(){return f})),r.d(t,"alignMediaPlaylistByPDT",(function(){return g}));var i=r("./src/polyfills/number.ts"),s=r("./src/utils/logger.ts"),n=r("./src/controller/level-helper.ts");function a(e,t){for(var r=null,i=0,s=e.length;ir.startCC||e&&e.cc=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.destroy=function(){},e}();t.default=s},"./src/utils/ewma.ts":function(e,t,r){"use strict";r.r(t);var i=function(){function e(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 t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}();t.default=i},"./src/utils/fetch-loader.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"fetchSupported",(function(){return d}));var i=r("./src/polyfills/number.ts"),s=r("./src/loader/load-stats.ts"),n=r("./src/demux/chunk-cache.ts");function a(e){var t="function"==typeof Map?new Map:void 0;return a=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;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,i)}function i(){return o(e,arguments,u(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),h(i,e)},a(e)}function o(e,t,r){return o=l()?Reflect.construct:function(e,t,r){var i=[null];i.push.apply(i,t);var s=new(Function.bind.apply(e,i));return r&&h(s,r.prototype),s},o.apply(null,arguments)}function l(){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 h(e,t){return h=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},h(e,t)}function u(e){return u=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},u(e)}function c(){return c=Object.assign||function(e){for(var t=1;t=i&&s(t,r,a.flush(),e)):s(t,r,l,e),n()})).catch((function(){return Promise.reject()}))}()},e}();function g(e,t){return new self.Request(e.url,t)}var p=function(e){var t,r;function i(t,r,i){var s;return(s=e.call(this,t)||this).code=void 0,s.details=void 0,s.code=r,s.details=i,s}return r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,h(t,r),i}(a(Error));t.default=f},"./src/utils/imsc1-ttml-parser.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"IMSC1_CODEC",(function(){return u})),r.d(t,"parseIMSC1",(function(){return g}));var i=r("./src/utils/mp4-tools.ts"),s=r("./src/utils/vttparser.ts"),n=r("./src/utils/vttcue.ts"),a=r("./src/demux/id3.ts"),o=r("./src/utils/timescale-conversion.ts"),l=r("./src/utils/webvtt-parser.ts");function h(){return h=Object.assign||function(e){for(var t=1;t"):i}function o(e){if(self.console&&!0===e||"object"==typeof e){!function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function c(e,t){var r,i,s,n=[];if(!t.length)return n;"data"in e?(r=e.data,i=e.start,s=e.end):(i=0,s=(r=e).byteLength);for(var l=i;l1?l+u:s;if(o(r.subarray(l+4,l+8))===t[0])if(1===t.length)n.push({data:r,start:l+8,end:d});else{var f=c({data:r,start:l+8,end:d},t.slice(1));f.length&&a.apply(n,f)}l=d}return n}function d(e){var t=c(e,["moov"])[0],r=t?t.end:null,i=c(e,["sidx"]);if(!i||!i[0])return null;var s=[],n=i[0],a=n.data[0],o=0===a?8:16,u=h(n,o);o+=4,o+=0===a?8:16,o+=2;var d=n.end+0,f=l(n,o);o+=2;for(var g=0;g>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var y=h(n,p);p+=4,s.push({referenceSize:m,subsegmentDuration:y,info:{duration:y/u,start:d,end:d+m-1}}),d+=m,o=p+=4}return{earliestPresentationTime:0,timescale:u,version:a,referencesCount:f,references:s,moovEndOffset:r}}function f(e){for(var t=[],r=c(e,["moov","trak"]),i=0;ie)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}()},"./src/utils/texttrack-utils.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"sendAddTrackEvent",(function(){return s})),r.d(t,"addCueToTrack",(function(){return n})),r.d(t,"clearCurrentCues",(function(){return a})),r.d(t,"removeCuesInRange",(function(){return o})),r.d(t,"getCuesInRange",(function(){return l}));var i=r("./src/utils/logger.ts");function s(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 n(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 s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}"disabled"===r&&(e.mode=r)}function a(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 o(e,t,r){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var s=l(e.cues,t,r),n=0;ne[r].endTime)return-1;for(var i=0,s=r;i<=s;){var n=Math.floor((s+i)/2);if(te[n].startTime&&i-1)for(var n=s,a=e.length;n=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}},"./src/utils/time-ranges.ts":function(e,t,r){"use strict";r.r(t),t.default={toString:function(e){for(var t="",r=e.length,i=0;i1?t-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return S},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return b},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");b=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}()},"./src/utils/vttparser.ts":function(e,t,r){"use strict";r.r(t),r.d(t,"parseTimeStamp",(function(){return n})),r.d(t,"fixLineBreaks",(function(){return c})),r.d(t,"VTTParser",(function(){return d}));var i=r("./src/utils/vttcue.ts"),s=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function n(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var a=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,r){for(var i=0;i=0&&r<=100)return this.set(e,r),!0}return!1},e}();function o(e,t,r,i){var s=i?e.split(i):[e];for(var n in s)if("string"==typeof s[n]){var a=s[n].split(r);2===a.length&&t(a[0],a[1])}}var l=new i.default(0,0,""),h="middle"===l.align?"middle":"center";function u(e,t,r){var i=e;function s(){var t=n(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function u(){e=e.replace(/^\s+/,"")}if(u(),t.startTime=s(),u(),"--\x3e"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.substr(3),u(),t.endTime=s(),u(),function(e,t){var i=new a;o(e,(function(e,t){var s;switch(e){case"region":for(var n=r.length-1;n>=0;n--)if(r[n].id===t){i.set(e,r[n].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),i.integer(e,s[0]),i.percent(e,s[0])&&i.set("snapToLines",!1),i.alt(e,s[0],["auto"]),2===s.length&&i.alt("lineAlign",s[1],["start",h,"end"]);break;case"position":s=t.split(","),i.percent(e,s[0]),2===s.length&&i.alt("positionAlign",s[1],["start",h,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",h,"end","left","right"])}}),/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var s=i.get("line","auto");"auto"===s&&-1===l.line&&(s=-1),t.line=s,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",h);var n=i.get("position","auto");"auto"===n&&50===l.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function c(e){return e.replace(//gi,"\n")}var d=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new s,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=c(e);r>>0).toString()};function c(e,t,r){return u(e.toString())+u(t.toString())+u(r)}function d(e,t,r,u,d,f,g,p){var v,m=new s.VTTParser,y=Object(n.utf8ArrayToStr)(new Uint8Array(e)).trim().replace(l,"\n").split("\n"),E=[],S=Object(a.toMpegTsClockFromTimescale)(t,r),T="00:00.000",b=0,_=0,L=!0,A=!1;m.oncue=function(e){var t=u[d],r=u.ccOffset,i=(b-S)/9e4;if(null!=t&&t.new&&(void 0!==_?r=u.ccOffset=t.start:function(e,t,r){var i=e[t],s=e[i.prevCC];if(!s||!s.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!==(n=s)&&void 0!==n&&n.new;){var n;e.ccOffset+=i.start-s.start,i.new=!1,s=e[(i=s).prevCC]}e.presentationOffset=r}(u,d,i)),i&&(r=i-u.presentationOffset),A){var s=e.endTime-e.startTime,n=Object(o.normalizePts)(9e4*(e.startTime+r-_),9e4*f)/9e4;e.startTime=n,e.endTime=n+s}var a=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(a)),e.id||(e.id=c(e.startTime,e.endTime,a)),e.endTime>0&&E.push(e)},m.onparsingerror=function(e){v=e},m.onflush=function(){v?p(v):g(E)},y.forEach((function(e){if(L){if(h(e,"X-TIMESTAMP-MAP=")){L=!1,A=!0,e.substr(16).split(",").forEach((function(e){h(e,"LOCAL:")?T=e.substr(6):h(e,"MPEGTS:")&&(b=parseInt(e.substr(7)))}));try{_=function(e){var t=parseInt(e.substr(-3)),r=parseInt(e.substr(-6,2)),s=parseInt(e.substr(-9,2)),n=e.length>9?parseInt(e.substr(0,e.indexOf(":"))):0;if(!(Object(i.isFiniteNumber)(t)&&Object(i.isFiniteNumber)(r)&&Object(i.isFiniteNumber)(s)&&Object(i.isFiniteNumber)(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*r,(t+=6e4*s)+36e5*n}(T)/1e3}catch(e){A=!1,v=e}return}""===e&&(L=!1)}m.parse(e+"\n")})),m.flush()}},"./src/utils/xhr-loader.ts":function(e,t,r){"use strict";r.r(t);var i=r("./src/utils/logger.ts"),s=r("./src/loader/load-stats.ts"),n=/^age:\s*[\d.]+\s*$/m,a=function(){function e(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 s.LoadStats,this.retryDelay=0}var t=e.prototype;return t.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},t.abortInternal=function(){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()))},t.abort=function(){var e;this.abortInternal(),null!==(e=this.callbacks)&&void 0!==e&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},t.load=function(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()},t.loadInternal=function(){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 s=this.xhrSetup;try{if(s)try{s(r,t.url)}catch(e){r.open("GET",t.url,!0),s(r,t.url)}r.readyState||r.open("GET",t.url,!0);var n=this.context.headers;if(n)for(var a in n)r.setRequestHeader(a,n[a])}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()}},t.readystatechange=function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var s=t.readyState,n=this.config;if(!r.aborted&&s>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===s){t.onreadystatechange=null,t.onprogress=null;var a=t.status;if(a>=200&&a<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 h=this.callbacks.onProgress;if(h&&h(r,e,o,t),!this.callbacks)return;var u={url:t.responseURL,data:o};this.callbacks.onSuccess(u,r,e,t)}else r.retry>=n.maxRetry||a>=400&&a<499?(i.logger.error(a+" while loading "+e.url),this.callbacks.onError({code:a,text:t.statusText},e,t)):(i.logger.warn(a+" 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,n.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout)}},t.loadtimeout=function(){i.logger.warn("timeout while loading "+this.context.url);var e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&n.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},e}();t.default=a}}).default},e.exports=t())},622:function(e){var t,r,i,s,n;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var s=n.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=n.normalizePath(s.path),n.buildURLFromParts(s)}var a=n.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return i.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):t;var o=n.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var u=o.path,c=u.substring(0,u.lastIndexOf("/")+1)+a.path;h.path=n.normalizePath(c)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=i.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(h)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");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=n},47:(e,t)=>{"use strict";t.l=s;var r=2147483647;function i(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return n(e,t,r)}function n(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|u(e,t),n=i(r),a=n.write(e,t);a!==r&&(n=n.slice(0,a));return n}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(m(e,ArrayBuffer)||e&&m(e.buffer,ArrayBuffer))return function(e,t,r){if(t<0||e.byteLength=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function u(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||m(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return v(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;default:if(n)return i?-1:v(e).length;t=(""+t).toLowerCase(),n=!0}}function c(e,t,r,i){r=Number(r)||0;const s=e.length-r;i?(i=Number(i))>s&&(i=s):i=s;const n=t.length;let a;for(i>n/2&&(i=n/2),a=0;a>8,s=r%256,n.push(s),n.push(i);return n}(t,e.length-r),e,r,i)}function p(e,t,r,i){let s;for(s=0;s=t.length||s>=e.length);++s)t[s+r]=e[s];return s}function v(e,t){var r;t=t||1/0;for(var i=e.length,s=null,n=[],a=0;a55295&&r<57344){if(!s){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(a+1===i){(t-=3)>-1&&n.push(239,191,189);continue}s=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),s=r;continue}r=65536+(s-55296<<10|r-56320)}else s&&(t-=3)>-1&&n.push(239,191,189);if(s=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function m(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.from=function(e,t,r){return n(e,t,r)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,r){return function(e,t,r){return a(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},s.allocUnsafe=function(e){return o(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var r;if(void 0===t)for(t=0,r=0;r=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t=0;--a)e[a+t]=this[a+r];else Uint8Array.prototype.set.call(e,this.subarray(r,i),t);return n},s.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}const s=this.length-t;if((void 0===r||r>s)&&(r=s),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return c(this,e,t,r);case"utf8":case"utf-8":return d(this,e,t,r);case"ascii":case"latin1":case"binary":return f(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}}},934:e=>{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof r&&(i=r,r=void 0),null!=r&&(i.code=r);try{return t(e,i)}catch(r){i.message=e.message,i.stack=e.stack;const s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(e)),t(new s,i)}}},485:function(e,t,r){var i;!function(s){"use strict";function n(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function a(e,t,r,i,s,a){return n((o=n(n(t,e),n(i,a)))<<(l=s)|o>>>32-l,r);var o,l}function o(e,t,r,i,s,n,o){return a(t&r|~t&i,e,t,s,n,o)}function l(e,t,r,i,s,n,o){return a(t&i|r&~i,e,t,s,n,o)}function h(e,t,r,i,s,n,o){return a(t^r^i,e,t,s,n,o)}function u(e,t,r,i,s,n,o){return a(r^(t|~i),e,t,s,n,o)}function c(e,t){var r,i,s,a,c;e[t>>5]|=128<>>9<<4)]=t;var d=1732584193,f=-271733879,g=-1732584194,p=271733878;for(r=0;r>5]>>>t%32&255);return r}function f(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t>5]|=(255&e.charCodeAt(t/8))<>>4&15)+i.charAt(15&t);return s}function p(e){return unescape(encodeURIComponent(e))}function v(e){return function(e){return d(c(f(e),8*e.length))}(p(e))}function m(e,t){return function(e,t){var r,i,s=f(e),n=[],a=[];for(n[15]=a[15]=void 0,s.length>16&&(s=c(s,8*e.length)),r=0;r<16;r+=1)n[r]=909522486^s[r],a[r]=1549556828^s[r];return i=c(n.concat(f(t)),512+8*t.length),d(c(a.concat(i),640))}(p(e),p(t))}function y(e,t,r){return t?r?m(t,e):g(m(t,e)):r?v(e):g(v(e))}void 0===(i=function(){return y}.call(t,r,t,e))||(e.exports=i)}()},422:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-native",PC_WEB:"PC-web"};var r={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return r.isAndroid()?t.ANDROID_WEB:r.isIOS()?t.IOS_WEB:r.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!n(s("os "))&&!n(s("android[/ ]"))},isIOS:function(){return n(s("os "))},isAndroid:function(){return n(s("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return r.isAndroid()||r.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},device:t,getBrowser:function(){return r.isX5()?"X5":r.isChrome()?"Chrome":r.isFirefox()?"Firefox":r.isIOSSafari()?"iOS-Safari":r.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function s(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=r},77:e=>{let t;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(t||(t=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))}},t={};function r(i){var s=t[i];if(void 0!==s)return s.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,r),n.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};return(()=>{"use strict";r.d(i,{default:()=>Jt});const e={DC_SIGNAL:"SIGNAL",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_SEND_REQUEST:"SEND_REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_PIECE_CANCEL:"PIECE_CANCEL",DC_CLOSE:"CLOSE",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",REQUESTING_MAP_HAVE:"REQUESTING_MAP_HAVE",BUILDER_MAP_HAVE:"BUILDER_MAP_HAVE",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PARTIAL:"SYN_PARTIAL"},t={...e,SCH_DCHAVE:"SCH_DCHAVE",SCH_WAIT_PEER:"SCH_WAIT_PEER",STREAM_DETECT:"STREAM_DETECT",STREAM_DISABLE:"STREAM_DISABLE",SW_STREAM_ENABLE:"SW_STREAM_ENABLE",SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_MEDIA:"SW_MEDIA",SW_PRE_MEDIA:"SW_PRE_MEDIA",SW_GET_MEDIA:"SW_GET_MEDIA",SW_STREAM:"SW_STREAM",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED"};var s=r(204),n=r.n(s),a=r(47);const o=64e3;function l(){return!0}function h(e){return new URL(location.href).searchParams.get(e)}function u(){return Date.parse(new Date)/1e3}function c(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function d(e,t,r,i=3500){const s=new XMLHttpRequest;return new Promise(((n,a)=>{s.open("GET",e,!0),s.responseType="arraybuffer",s.timeout=i,s.onreadystatechange=e=>{if(4===s.readyState){const e=s.status;206===e?n(s.response):a(`status ${e}`)}},s.onerror=e=>{a("request error")},s.ontimeout=e=>{a("timeout")},s.setRequestHeader("Range",t||"bytes=0-0"),r&&r(s,e),s.send()})).catch((e=>{}))}function f(){if("undefined"==typeof window)return null;var e={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}function g(e){const t=a.l.from(e),r=new a.l(e.byteLength);return t.copy(r),r}function p(){return location.protocol.startsWith("https")}function v(e,t){const r=e.byteLength-t,i=[];let s=t,n=Math.floor(r/o),l=r%o;for(let t=0;t0){const t=(0,a.l)(l);e.copy(t,0,s,s+l),i.push(t)}return i}function m(e,t){if(e.size<=t)return;const r=[...e.values()];do{e.delete(r.shift())}while(e.size>t)}function y(e){return e instanceof ArrayBuffer&&0!==e.byteLength}const E={debug:0,info:1,warn:2,error:3,none:4};const S=class{constructor(e){this.logLevel=e,this.onlineDebug=!1,console.debug=console.log,"debug"!==e&&"info"!==e||(this.logLevel="warn"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in E||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in E)this[e]=console[e]}resetLogger(){this.onlineDebug=!1;for(let e in E)E[e]e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:f(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void L()((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var r;!t.address||t.address.endsWith(".local")?(r="Ignoring unsupported ICE candidate.",console.warn(r)):this.destroy(e)}))}send(e){this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,L()((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,L()((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=A),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}get isBufferedAmountHigh(){return this._channel.bufferedAmount>A}write(e,t){if(this.destroyed)return t(new Error("cannot write after peer is destroyed"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(e)}this.isBufferedAmountHigh?this._cb=t:t(null)}else this._chunk=e,this._cb=t}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=D(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=D(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((r=>{const i=[];r.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((r=>{if(this.destroyed)return;const i=[];r.result().forEach((e=>{const r={};e.names().forEach((t=>{r[t]=e.stat(t)})),r.id=e.id,r.type=e.type,r.timestamp=e.timestamp,i.push(t(r))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,r)=>{if(this.destroyed)return;t&&(r=[]);const i={},s={},n={};let a=!1;r.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(s[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(n[e.id]=e)}));const o=e=>{a=!0;let t=s[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let r=i[e.remoteCandidateId];r&&(r.ip||r.address)?(this.remoteAddress=r.ip||r.address,this.remotePort=Number(r.port)):r&&r.ipAddress?(this.remoteAddress=r.ipAddress,this.remotePort=Number(r.portNumber)):"string"==typeof e.googRemoteAddress&&(r=e.googRemoteAddress.split(":"),this.remoteAddress=r[0],this.remotePort=Number(r[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(r.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(n[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(n).length&&!Object.keys(s).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>A||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=a.l.from(t)),this.emit("data",t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}w.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},w.channelConfig={};const I=w;class P{constructor(e,t,r,i,s=0){this.sn=e,this.segId=t,this.data=r,this.fromPeerId=i,this.level=s||0}static fromSegment(e){return new P(e.sn,e.segId,e.data,e.fromPeerId,e.level)}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var R=r(422),C=r.n(R);class k extends(n()){static get defaultPacketSize(){return o}static get VERSION(){return"8"}constructor(e,t,r,i,s,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=s,this.isInitiator=i,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,r),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=o,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.uploadInterrupter={targetSegId:void 0,currentSegId:void 0,canceled:!1},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.gotPeers=!1,this.currentLevel=0,this.currentPos=0,this.useBackupSignal=!1,this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,r){this.remotePeerId=r,this.channelId=this.isInitiator?`${t}-${r}`:`${r}-${t}`,r&&(this.timeJoin=u(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this._startTimer()),setTimeout((()=>{for(let t of this.signalMsgs)this.emit(e.DC_SIGNAL,t,!0)}),0)}_startTimer(){this.connTimeout=setTimeout((()=>{this.logger.warn(`dc ${this.channelId} connection timeout`),this.emit(e.DC_TIMEOUT)}),25e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,r,i){if(i&&this.downloading&&!(this.streamListeners.length>0||this.remainAttachments<=2))return this.logger.info(`cancel download ${i} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:r,seg_id:i})}addStreamListener(e,t,r){this.streamListeners.push({handler:r,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_initPeerChannel(){const t=new I({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let r=!0;"Ice connection failed."===t.message&&this.notFatalClosed&&(r=!1),this.emit(e.DC_ERROR,r)})),t.on("signal",(t=>{this.signalMsgs.push(t),this.emit(e.DC_SIGNAL,t)}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED to ${this.remotePeerId} from ${this.intermediator?"peer":"server"}`),this.connected=!0,clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:r}=this;if("string"==typeof t){let i=JSON.parse(t);if(!this.connected)return void this.msgQueue.push(i);let s,n=i.event;switch(s=n!==e.DC_PLAYLIST&&n!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${n}`,r.debug(`datachannel receive ${s} from ${this.remotePeerId}`),n){case e.DC_HAVE:if(this.emit(i.event,i),!i.sn)return;this.config.live||(i.snthis.endSN&&(this.endSN=i.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=u(),this.timeReceivePiece=performance.now(),this.pieceMsg=i,this._prepareForBinary(i.attachments,i.seg_id,i.sn,i.size),this.emit(i.event,i);break;case e.DC_PIECE_CANCEL:this.uploadInterrupter.targetSegId=i.seg_id,this.emit(i.event,i);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(i.event,i);break;case e.DC_REQUEST:this._handleRequestMsg(i);break;case e.DC_PIECE_ACK:this.uploadInterrupter.canceled||(this._handlePieceAck(i.size,i.miss),this.emit(i.event,i));break;case e.DC_STATS:this._handleStats(i);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(i);break;case e.DC_METADATA:this._handleMetadata(i);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,i));break;case e.DC_CHOKE:r.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:r.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(i.event,i.fatal||!1);break;default:this.emit(i.event,i)}}else{if(!this.downloading)return void r.warn(`peer not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`);this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((e,t)=>{"disconnected"===e&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.connected=!1)}))}sendJson(t){t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const r=JSON.stringify(t);return r.length>o?(this.logger.error("string to send is too large"),!1):this.send(r,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_checkIfNeedInterrupt(){const{targetSegId:t,currentSegId:r,canceled:i}=this.uploadInterrupter;return!!i||!(!t||t!==r)&&(this.logger.info("cancel send data"),this.sendMsgPieceAbort(`${r} transfer canceled`),this.datasToSend=[],this.uploadInterrupter.canceled=!0,this._handlePieceAck(this.bytesUploaded,0),this.emit(e.DC_PIECE_ACK,{seg_id:r,size:this.bytesUploaded,canceled:!0}),!0)}_sendDataSync(){if(this._checkIfNeedInterrupt()||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();this.bytesUploaded+=t.byteLength,this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,this.logger.warn(t.message),void this.emit(e.DC_ERROR,!1);this._sendDataSync()}))}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){this.logger.warn(`datachannel ${this.channelId} send data failed, close it`),this.emit(e.DC_ERROR,!1)}return!1}sendMsgHave(t,r,i={}){const s=i.reverse||void 0;delete i.reverse,this.sendJson({event:s?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:r,...i})}sendPieceNotFound(t,r,i={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:r,sn:t,...i})}sendPeers(t){this.sendJson({event:e.DC_PEERS,peers:t})}sendPeersRequest(){this.sendJson({event:e.DC_GET_PEERS})}sendMsgStats(t,r={}){const i={event:e.DC_STATS,total_conns:t,...r};this.sendJson(i)}sendMsgPlaylist(t,r,i){const s=this.playlistMap.get(t);if(s&&s.seq>=i)return;const n={event:e.DC_PLAYLIST,url:t,data:r,seq:i};this.playlistMap.set(t,{data:r,seq:i}),this.sendJson(n)}sendMsgSignal(t,r,i){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:r,data:i})}sendMsgSignalReject(t,r,i,s=!1){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:r,reason:i,fatal:s})}sendMetaData(t,r,i,s=!1){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!C().isMobile(),mobile_net:s,channel:this.channel,version:"2.7.4",sequential:r,peers:i})}sendPartialBuffer(e,t,r={}){this.sendMsgPiece(e,r);for(let e=0;e${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const i={...e,ext:t};this.sendJson(i)}sendBuffer(t,r,i,s={}){const n=s.reverse||void 0;delete s.reverse;let a=i.byteLength,o=0,l=0;a%this.packetSize==0?l=a/this.packetSize:(l=Math.floor(a/this.packetSize)+1,o=a%this.packetSize);let h={event:e.DC_PIECE,attachments:l,seg_id:r,sn:t,level:s.level,size:a,reverse:n};delete s.level,this.sendMsgPiece(h,s);const u=function(e,t,r,i){let s=[];if(i){let n;for(let i=0;i=this.minRequiredSpeed(e))}close(t){t||(this.notFatalClosed=!0),this.emit(e.DC_CLOSE,t)}receiveSignal(e){e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:r}=t;r(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(t=!0){this.logger.info(`destroy datachannel ${this.channelId}`),this.chokeTimer&&clearTimeout(this.chokeTimer),this.connTimeout&&clearTimeout(this.connTimeout),this.uploading&&this.sendMsgPieceAbort("peer is closing"),this._notifyDownloadListenersAbort("upstream peer is closed");let r={event:e.DC_CLOSE,fatal:t};this.sendJson(r),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:r,level:i,reverse:s}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let n=s?this.remainAttachments+1:r-this.remainAttachments;const a=0===this.remainAttachments;if(this.emit(e.DC_PIECE_DATA,this.bufSN,this.segId,t,n,a,this.pieceMsg),this.streamListeners.length>0)for(let e of this.streamListeners){const{handler:r}=e;r(this.bufSN,this.segId,!1,t,a)}if(a){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:e.DC_PIECE_ACK,sn:this.bufSN,seg_id:this.segId,level:i,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(s)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:r,seq:i}=e;this.playlistMap.set(t,{data:r,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const r=this.playlistMap.get(e);return r.seq<=t||r.seq>t+2?null:r}_handleMetadata(t){const{logger:r}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,r.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const i=t.channel;if(this.channel!==i)return r.error(`peer channel ${i} not matched!`),void this.emit(e.DC_ERROR,!0);t.super&&(r.info(`got super peer ${this.remotePeerId}`),this.super=!0);switch(t.platform){case e.DC_PLAT_ANDROID:this.platform=e.DC_PLAT_ANDROID;break;case e.DC_PLAT_IOS:this.platform=e.DC_PLAT_IOS;break;case e.DC_PLAT_WEB:this.platform=e.DC_PLAT_WEB}if(this.mobile=t.mobile||!1,this.mobileNet=t.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===e.DC_PLAT_WEB||!1,this.sequential=t.sequential,r.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,r.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(e.DC_METADATA,t),t.field&&!this.config.live&&t.sequential){const{field:e}=t;if(Array.isArray(e))this._handleField(e);else for(let t in e)this._handleField(e[t])}}_handleField(e){e.forEach((e=>{e>=0&&(ethis.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=u();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPos=e.pos)}_handleRequestMsg(t){if(this.dataExchangeTs=u(),this.uploading)return this.logger.warn(`${this.remotePeerId} is uploading when receive request`),void this.sendPieceNotFound(t.sn,t.seg_id,{level:t.level});this.uploading=!0,this.emit(e.DC_REQUEST,t)}_handlePieceAck(e,t){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(e/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),t>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${t}`)}_prepareForBinary(e,t,r,i){this.bufArr=[],this.remainAttachments=e,this.segId=t,this.bufSN=r,this.expectedSize=i}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let r=a.l.concat(this.bufArr);const i=r.byteLength;if(i===this.expectedSize){let t=r.buffer;const i=new P(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,i,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${i}`)}this.segId="",this.bufArr=[],this._loadedBytes=0}checkIfNeedChoke(e=!1){const{logger:t}=this,r=performance.now()-this.timeSendRequest;if(!e&&r<1500)t.info(`duration ${r} no need choke`);else if(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>2&&!this.choked){this.choked=!0;const e=30*this.miss;e<=150?(t.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,t.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*e)):t.warn(`datachannel ${this.channelId} is choked permanently`)}}get bufArrSize(){return this.downloading?this.pieceMsg.attachments-this.remainAttachments:0}loadtimeout(){const{logger:e,pieceMsg:t}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded`),this.checkIfNeedChoke(),!0}sendMsgPieceAbort(t){(this.uploading||0!==this.datasToSend.length)&&(this.uploading=!1,this.sendJson({event:e.DC_PIECE_ABORT,reason:t}))}loadedBytes(){return this._loadedBytes}currentLoadSpeed(){return 0===this.timeReceivePiece?0:this.loadedBytes()/(performance.now()-this.timeReceivePiece)}minRequiredSpeed(e){return(this.pieceMsg.size-this.loadedBytes())/e}}const O=k,M={DPlayer:"dplayer",CBPlayer:"cbplayer",jwplayer:"jwplayer",videojs:"videojs",Clappr:"clappr",ckplayer:"ckplayer",MediaElementPlayer:"mediaelement",MediaElement:"mediaelement",TcPlayer:"tcplayer",flowplayer:"flowplayer",Chimee:"chimee",ChimeePlayer:"chimee",HlsJsPlayer:"xgplayer",fluidPlayer:"fluidplayer",OpenPlayer:"openplayer",Plyr:"plyr",Playerjs:"playerjs",Aliplayer:"aliplayer",shaka:"shakaplayer"};function x(){let e;for(let t in M)if(window[t]){e=M[t];break}return e}const F="nllL",N="d3NzJ",B="==",U="TNBLy9z",G="aWduY",j="mNvbQ",H="WwuY2RuY";class $ extends(n()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===h("_p2p")),e.tag&&e.tag.length>20)throw new Error("Tag is too long");if(e.appName&&e.appName.length>30)throw new Error("appName is too long");if(e.appId&&e.appId.length>30)throw new Error("appId is too long");if(e.token&&e.token.length>20)throw new Error("Token is too long")}initLogger(){const{config:e}=this;e.showSlogan&&"en"==("zh-CN"===(navigator.language||navigator.userLanguage)?"cn":"en")&&console.log(`%cLet the browsers become your unlimitedly scalable CDN!\n%c${window.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldC9lbi8=")}`,"color: dodgerblue; padding:20px 0; font-size: x-large","font-size: medium; padding-bottom:15px");const t=new S(e.logLevel);return e.logger=this.logger=t,t}getExtraForStats(){return{}}getExtraForPeersRequest(){const e={};return e.num_want=this._getNumWant(),e}_getNumWant(){const{tracker:e}=this,t=e.scheduler.peersNum;if(t>0&&e.maxConnsActive-t>0)return e.maxConnsActive-t}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return"function"==typeof t?(r,i)=>`${e}-${t(r,i)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,r=decodeURIComponent(window.atob(N+U+G+H+F+j+B)),{wsSignalerAddr:i}=t;if(i){let s;"object"==typeof i?(i.main||(i.main=r),s=i.main):"string"==typeof i&&(s=i,t.wsSignalerAddr={main:s}),s===r&&(s=void 0),s&&!t.wsSignalerAddr.backup&&(e=b().parseURL(s).netLoc.substr(2))}else t.wsSignalerAddr={main:r,default:!0};return e}get commonBrowserInfo(){const e=C().getPlatform(),t=C().getNetType()||"wifi";return this.netType=t,{device:e,netType:t,player:x()||void 0}}get isMobileNet(){return"wifi"!==this.netType&&"ethernet"!==this.netType}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",r=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),window.removeEventListener(t,r)};e?window.removeEventListener(t,r):window.addEventListener(t,r)}destroy(){this.disableP2P(!0),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return $.version}static isSupported(){const e=f();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{CN:"cn",EU:"eu",HK:"hk",USA:"us"}}}$.version="2.7.4",$.protocolVersion=O.VERSION;const W=$;function K(e,t){let r;if(e&&("string"==typeof e?r=document.querySelector(e):e instanceof HTMLMediaElement&&(r=e)),!r){const e=[...document.getElementsByTagName("video"),...document.getElementsByTagName("audio")];1===e.length?r=e[0]:(t&&(r=e.find((e=>e.src===t))),r||(r=e.find((e=>e.currentTime>0))))}return r}let q={wsMaxRetries:10,p2pEnabled:!0,wifiOnly:!1,memoryCacheLimit:{pc:629145600,mobile:314572800},dcDownloadTimeout:25,logLevel:"error",tag:"",webRTCConfig:{},token:void 0,appName:void 0,appId:void 0,prefetchNum:5,showSlogan:!1,trickleICE:!0,announceLocation:"cn",trackerZone:void 0,geoIpPreflight:!0,getStats:function(e,t,r){},getPeerId:function(e){},getPeersInfo:function(e){}};const V={...q,httpLoadTime:3,sharePlaylist:!1,useHttpRange:!0,hlsjsInstance:null,proxyOnly:!1,p2pBlackList:["aac","mp3","vtt","webvtt","key"],live:!0,swFile:"./sw.js",swScope:"./",swAutoRegister:!0,mediaElem:void 0,httpStreamEnabled:!0,swStreamEnabled:!0,diskCacheLimit:{pc:262144e4,mobile:1572864e3},useDiskCache:!0,waitForPeer:!1,waitForPeerTimeout:4,strictSegmentId:!1},z="store not init";function Y(e){return new Promise(((t,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)}))}function X(e,t){return t?t("readonly",(t=>Y(t.get(e)))):Promise.reject(z)}function Q(e,t,r){return r?r("readwrite",(r=>(r.put(t,e),Y(r.transaction)))):Promise.reject(z)}function J(e,t){return t?t("readwrite",(t=>(t.delete(e),Y(t.transaction)))):Promise.reject(z)}function Z(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},Y(e.transaction)}const ee="size";class te extends(n()){constructor(e,t){super(),this.name="SegmentStore",this.logger=t.logger,this.logger.info("use SegmentStore"),this.channel=e.channel;const r=e.browserInfo.device;this.isPC=r===C().device.PC_WEB||r===C().device.PC_NATIVE,this.maxBufSize=this.isPC?t.diskCacheLimit.pc:t.diskCacheLimit.mobile,this.overflowed=!1,this.loadingSN=0}async setupStore(){if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate(),t=Math.floor(e.quota-e.usage);t{if(this.isPC&&this.maxBufSize<629145600||!this.isPC&&this.maxBufSize<367001600)return void t("disk storage not enough");let r=function(e,t){const r=indexedDB.open(e);r.onupgradeneeded=()=>{const e=r.result;t.forEach((t=>{e.createObjectStore(t)}))};const i=Y(r);return t.map((e=>(t,r)=>i.then((i=>r(i.transaction(e,t).objectStore(e))))))}(this.channel,["segments","id2Sn","metadata"]);this.segmentsStore=r[0],this.id2SnStore=r[1],this.metaStore=r[2];const i=setTimeout((()=>{t("setupStore timeout")}),500);this._initMetaStore().then((()=>{clearTimeout(i),e()})).catch((e=>{t(e)}))}))}_initMetaStore(){return new Promise(((e,t)=>{X(ee,this.metaStore).then((t=>{t||(this.logger.info("init MetaStore size"),Q(ee,0,this.metaStore)),e()})).catch((e=>{t()}))}))}currBufSize(){return X(ee,this.metaStore)}async hasSegOfId(e){if(!e)return Promise.resolve(!1);const t=await X(e,this.id2SnStore);return new Promise(((r,i)=>{void 0!==t?X(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?r(!0):r(!1)})).catch((e=>{this.logger.error(e),r(!1)})):r(!1)}))}async getSegById(e){if(!e)return null;const t=await X(e,this.id2SnStore);return new Promise(((e,r)=>{void 0!==t?X(t,this.segmentsStore).then((t=>{if(t&&t.length>0){const r=t[0];if(!y(r.data))return this.logger.error(`getSegById ${r.sn} is not buffer`),void e(null);e(P.fromSegment(r))}else e(null)})).catch((t=>{this.logger.error(t),e(null)})):e(null)}))}getSegIdBySN(e){return new Promise(((t,r)=>{X(e,this.segmentsStore).then((e=>{e&&e.length>0?t(e[0].segId):t(null)})).catch((e=>{this.logger.error(e),t(null)}))}))}putSeg(t){const{logger:r}=this;y(t.data)?this._addSeg(t).then((t=>{this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t)})).catch((e=>{r.error(e),("QuotaExceededError"===e.name||e.inner&&"QuotaExceededError"===e.inner.name)&&this._trimDisk(!0)})):r.error(`putSeg ${t.sn} is not buffer`)}_addSeg(e){const{segId:t,sn:r}=e;return Q(t,r,this.id2SnStore),new Promise(((i,s)=>{X(r,this.segmentsStore).then((n=>{n?0===n.filter((e=>e.segId===t)).length&&(n.push(this._segmentToCache(e)),Q(r,n,this.segmentsStore).then((()=>{this._increaseBufSize(e.data.byteLength),i(e)})).catch((e=>{s(e)}))):Q(r,[this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(e.data.byteLength),i(e)})).catch((e=>{s(e)}))})).catch((e=>{s(e)}))}))}async _trimDisk(t=!1){let r=this.maxBufSize;const{logger:i}=this;let s=await this.currBufSize();var n;(t&&(r=s-52428800,r<0&&(r=0)),s{if(e.getAllKeys)return Y(e.getAllKeys());const t=[];return Z(e,(e=>t.push(e.key))).then((()=>t))})):Promise.reject(z)).then((async t=>{const n=t.sort(((e,t)=>e-t));let a=0;do{if(a++>10){console.error("too much loops in SegmentStore");break}const t=n.shift();if(void 0===t){i.error("lastSN not found");continue}if(t>=this.loadingSN){i.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const r=n[0],o=await X(t,this.segmentsStore);if(!o){i.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),J(t,this.segmentsStore).then((()=>{this._decreaseBufSize(parseInt(l))})),o.forEach((s=>{J(s.segId,this.id2SnStore),i.info(`pop seg ${s.segId} size ${s.data.byteLength}`),this.emit(e.BM_LOST,{sn:t,segId:s.segId,next:r,level:s.level})})),s-=l,i.info(`pop sn ${t} size ${l} currBufSize ${s}`),this.overflowed||(this.overflowed=!0)}while(s>=r)}))}_decreaseBufSize(e){X(ee,this.metaStore).then((t=>{t&&Q(ee,t-e,this.metaStore)})).catch((e=>{this.logger.error(e)}))}_increaseBufSize(e){X(ee,this.metaStore).then((t=>{Q(ee,t+e,this.metaStore),this._trimDisk()})).catch((e=>{this.logger.error(e)}))}_segmentToCache(e){return{data:e.data,level:e.level,segId:e.segId,sn:e.sn}}clear(){this.logger.warn("clear segment store");try{this._clearDisk()}catch(e){}}_clearDisk(e){return function(e){return new Promise(((t,r)=>{indexedDB.databases().then((i=>{const s=i.filter((t=>t.name!==e)).map((e=>new Promise(((t,r)=>{const i=indexedDB.deleteDatabase(e.name);i.onsuccess=t,i.onerror=r,i.onblocked=r}))));Promise.all(s).then(t).catch(r)})).catch(r)})).catch((e=>{}))}(e)}destroy(){this.clear(),this.removeAllListeners()}}const re=te;class ie extends(n()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info("use SegmentCache");const r=e.browserInfo.device;if(this.maxBufSize=r===C().device.PC_WEB||r===C().device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,t.live)this.maxBufSize=31457280;else{const e=function(){const{memory:e}=performance;return e?e.jsHeapSizeLimit-e.usedJSHeapSize:-1}();e>=0&&e{const i=this.id2Sn.get(e);this._segPool.has(i)?t(this._segPool.get(i).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((r,i)=>{if(!this._segPool.has(t))return void r(null);const s=this._segPool.get(t);for(let t of s)if(t.segId===e)return void r(t);r(null)}))}getSegIdBySN(e){return new Promise(((t,r)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}_calSegPoolSize(){let e=0;return this._segPool.forEach((t=>{t.forEach((t=>{e+=t.size}))})),e}putSeg(e){this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),y(e.data)?this._addSeg(e):this.logger.error(`putSeg ${e.sn} is not buffer`)}_addSeg(t){const{logger:r}=this,{segId:i,sn:s,size:n}=t;if(this.id2Sn.set(i,s),this._segPool.has(s)){this._segPool.get(s).push(t)}else this._segPool.set(s,[t]);this._currBufSize+=parseInt(n);const a=this._segPool.size;if(this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t),this._currBufSizee-t));let l=0;do{if(l++>10){console.error("too much loops in SegmentCache");break}const t=o.shift();if(void 0===t){r.error("lastSN not found");continue}const i=o[0],s=this._segPool.get(t);if(!s){r.error("lastSeg not found");continue}let n=0;s.forEach((e=>{n+=e.size})),this._currBufSize-=parseInt(n),this._segPool.delete(t),s.forEach((r=>{this.id2Sn.delete(r.segId),this.emit(e.BM_LOST,{sn:t,segId:r.segId,next:i,level:r.level})})),r.info(`pop sn ${t} size ${n} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>5)}clear(){this.logger.warn("clear segment cache"),this._segPool.clear(),this.id2Sn.clear(),this._currBufSize=0}destroy(){this.clear(),this.removeAllListeners()}}const se=ie;class ne extends W{constructor(e={}){super(e),e.validateSegment||(e.validateSegment=function(e,t){return!0}),this.config=Object.assign({},V,e),this.rangeTested=!1,this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t,segmentId:r,strictSegmentId:i}=this.config,s=e=>{const t=b().parseURL(e);return`${t.netLoc.substr(2)+t.path.substring(0,t.path.lastIndexOf("."))}`},n=i?(e,t,r,i)=>{let s=r.split("?")[0];return s.startsWith("http")&&(s=s.split("://")[1]),i?`${s}|${i}`:`${s}`}:(e,t)=>`${e}-${t}`;t&&(s=this.makeChannelId(e,t)),r||(this.config.segmentId=n);return{channelIdMaker:s,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo,tag:this.config.tag||void 0}}}setupElectron(){this.browserInfo.device===R.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e=super.getExtraForStats();return!this.config.live&&this.media&&(e.pos=Math.round(this.media.currentTime)),this.multiBitrate&&this.currentLevel!==this.lastLevel&&(e.level=this.currentLevel+"",this.lastLevel=this.currentLevel),e}getExtraForPeersRequest(){const e=super.getExtraForPeersRequest();return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){super.destroy()}async initSegmentManager(){const{logger:e,config:t}=this;if(window.indexedDB&&t.useDiskCache&&!t.live){const r=new re(this,t);try{await r.setupStore(),this.bufMgr=r}catch(r){e.warn(r),this.bufMgr=new se(this,t)}}else this.bufMgr=new se(this,t);if(this.bufMgr.maxBufSize<=0)throw new Error("bufMgr state is invalid")}getTagForVod(){const e=`${(0,R.getBrowser)()}${p()?"s":""}`;return this.bufMgr?`${e}_${"SegmentStore"===this.bufMgr.name?"d":"m"}`:e}}class ae{constructor(){this.method=null,this.key=null,this.iv=null,this._uri=null}get uri(){return!this._uri&&this.reluri&&(this._uri=T.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}class oe{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[oe.ElementaryStreamTypes.AUDIO]:!1,[oe.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=T.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url}set url(e){this._url=e}get byteRange(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;let e=[];if(this.rawByteRange){const t=this.rawByteRange.split("@",2);if(1===t.length){const t=this.lastByteRangeEndOffset;e[0]=t||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get decryptdata(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}get endProgramDateTime(){if(!Number.isFinite(this.programDateTime))return null;let e=Number.isFinite(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}addElementaryStream(e){this._elementaryStreams[e]=!0}hasElementaryStream(e){return!0===this._elementaryStreams[e]}createInitializationVector(e){let t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new ae,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}}class le{constructor(e){this.endCC=0,this.endSN=0,this.fragments=[],this.initSegment=null,this.live=!0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=e,this.version=null}get hasProgramDateTime(){return!(!this.fragments[0]||!Number.isFinite(this.fragments[0].programDateTime))}}const he=/^(\d+)x(\d+)$/,ue=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class ce{constructor(e){"string"==typeof e&&(e=ce.parseAttrList(e));for(let t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;eNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}enumeratedString(e){return this[e]}decimalResolution(e){const t=he.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,r={};for(ue.lastIndex=0;null!==(t=ue.exec(e));){let e=t[2],i='"';0===e.indexOf(i)&&e.lastIndexOf(i)===e.length-1&&(e=e.slice(1,-1)),r[t[1]]=e}return r}}const de=ce,fe={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}};const ge=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,pe=/#EXT-X-MEDIA:(.*)/g,ve=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),me=/(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/,ye=/\.(mp4|m4s|m4v|m4a)$/i;class Ee{static findGroup(e,t){if(!e)return null;let r=null;for(let i=0;i2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return T.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let r,i=[];function s(e,t){["video","audio"].forEach((r=>{const i=e.filter((e=>function(e,t){const r=fe[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)));if(i.length){const s=i.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${r}Codec`]=s.length>0?s[0]:i[0],e=e.filter((e=>-1===i.indexOf(e)))}})),t.unknownCodecs=e}for(ge.lastIndex=0;null!=(r=ge.exec(e));){const e={},n=e.attrs=new de(r[1]);e.url=Ee.resolve(r[2],t);const a=n.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=n.decimalInteger("AVERAGE-BANDWIDTH")||n.decimalInteger("BANDWIDTH"),e.name=n.NAME,s([].concat((n.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=Ee.convertAVC1ToAVCOTI(e.videoCodec)),i.push(e)}return i}static parseMasterPlaylistMedia(e,t,r,i=[]){let s,n=[],a=0;for(pe.lastIndex=0;null!==(s=pe.exec(e));){const e={},o=new de(s[1]);if(o.TYPE===r){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=r,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=Ee.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),i.length){const t=Ee.findGroup(i,e.groupId);e.audioCodec=t?t.codec:i[0].codec}e.id=a++,n.push(e)}}return n}static parseLevelPlaylist(e,t){let r,i,s=0,n=0,a=new le(t),o=new ae,l=0,h=null,u=new oe,c=null;for(ve.lastIndex=0;null!==(r=ve.exec(e));){const e=r[1];if(e){u.duration=parseFloat(e);const t=(" "+r[2]).slice(1);u.title=t||null,u.tagList.push(t?["INF",e,t]:["INF",e])}else if(r[3]){if(Number.isFinite(u.duration)){const e=s++;u.start=n,u.levelkey=o,u.sn=e,u.cc=l,u.baseurl=t,u.relurl=(" "+r[3]).slice(1),Se(u,h),a.fragments.push(u),h=u,n+=u.duration,u=new oe}}else if(r[4]){if(u.rawByteRange=(" "+r[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(u.lastByteRangeEndOffset=e)}}else if(r[5])u.rawProgramDateTime=(" "+r[5]).slice(1),u.tagList.push(["PROGRAM-DATE-TIME",u.rawProgramDateTime]),null===c&&(c=a.fragments.length);else{for(r=r[0].match(me),i=1;i=0&&(o.method=f,o.baseuri=t,o.reluri=g,o.key=null,o.iv=p));break;case"START":let i=new de(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(i)&&(a.startTimeOffset=i);break;case"MAP":let h=new de(e);u.relurl=h.URI,u.rawByteRange=h.BYTERANGE,u.baseurl=t,u.sn="initSegment",a.initSegment=u,u=new oe,u.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${r}`)}}}return u=h,u&&!u.relurl&&(a.fragments.pop(),n-=u.duration),a.totalduration=n,a.averagetargetduration=n/a.fragments.length,a.endSN=s-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>ye.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),u=new oe,u.relurl=a.fragments[0].relurl,u.baseurl=t,u.level=id,u.sn="initSegment",a.initSegment=u,a.needSidxRanges=!0),c&&function(e,t){let r=e[t];for(let i=t-1;i>=0;i--){const t=e[i];t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(a.fragments,c),a}}function Se(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Number.isFinite(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}var Te=r(485),be=r.n(Te),_e=r(934),Le=r.n(_e);const Ae=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}},De=(e,t,r)=>{((e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)})(e,{value:t,duration:r,startTime:(new Date).getTime()})};class we{constructor(){this.p2p=0,this.share=0,this.http=0}recordP2p(e){this.p2p+=e}recordShare(e){this.share+=e}recordHttp(e){this.http+=e}resetTraffic(){this.p2p=0,this.share=0,this.http=0}get healthRatio(){if(0===this.http)return 1e3;let e=Math.round((this.p2p+this.share)/this.http*100);return e<=0&&(e=1),e}}const Ie="SW_GEOIP_KEY",Pe="TRACKER_EXPT",Re="IPAPI_ERROR",Ce="Y24u",ke="Y2Ru",Oe="Nvb",Me="YnllLm",xe="Q==",Fe="aGsuc3d",Ne="hcm1j",Be="bG91ZC",Ue="5uZXQ=",Ge=Symbol("httpDownloaded"),je=Symbol("p2pDownloaded"),He=Symbol("p2pUploaded");class $e extends(n()){constructor(e,t,r,i,s){let n;super(),this.config=e.config;let a=this.config.announceLocation;switch(this.config.trackerZone&&(a=this.config.trackerZone),a){case"cn":case"eu":n=Ce+ke+Me+Oe+xe;break;case"hk":n=Fe+Ne+Be+Ue;break;case"us":n="dXMuaGR0dmNsb3VkLmNvbQ=="}this.engine=e,this.key=t||void 0,this.baseUrl=i||`https://${window.atob(n)}/v1`,this.channelId=window.btoa(r),this.timestamp=u(),this.health=new we;const o=b().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,"");const l=function(e,t,r,i,s,n){let a=location.hostname;"localhost"===a&&n&&(a=`${n}.${a}`);function o(e,t,r,i,s,n){return be()(e+t+r+i+s,n)}const l=o(a,t,r,i,s,e);return l.substr(0,8)}(this.timestamp,"2.7.4",this.announce,this.channelId,s.type,this.key);this.native=!!s.bundle,this.announceInfo={...s,channel:this.channelId,ts:this.timestamp,version:"2.7.4",v:l,announce:this.announce,token:this.key},this.announceURL=`${this.baseUrl}/channel`,this.reportFails=0,this.statsRequesting=!1,this.forbidden=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[Ge]=0,this[je]=0,this[He]=0,this.speed=0,this.offline=!1,this.errsBufStalled=0,this.mediaRequests=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,r)=>{if((e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return!(!e.duration||!e.startTime)&&(new Date).getTime()-e.startTimee.json())).then((e=>{if("success"===e.status){const r=e.mobile?432e5:2592e5;De(Ie,e,r),t(e)}else{const t=new Error(`preflight status ${e.status}`);r(Le()(t,Re))}})).catch((e=>{r(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(Le()(new Error("request timeout"),Re))}),600)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(t.code!==Pe){const t=Ae(Ie);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:r,isp:i,as:s,mobile:n,countryCode:a,continentCode:o}=e;n&&(this.announceInfo.netType="cellular");const l=s.split(" ")[0].substr(2);this.announceInfo.tag||(this.announceInfo.tag=`${o||""}-${(0,R.getBrowser)()}${p()?"s":""}`),this.announceInfo={...this.announceInfo,lat:t,lon:r,isp:i,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return this.announceInfo.tag||(this.announceInfo.tag=`${(0,R.getBrowser)()}${p()?"s":""}`),new Promise(((t,r)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>{if(!e.ok){const t=e.status>=500&&e.status<600;r(Le()(new Error(`server response code is ${e.status}`),Pe,{retry:t}))}return e.json()})).then((e=>{this.engine||r(Le()(new Error("runtime error"),Pe,{retry:!1}));const i=e.data;if(i.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:i}=e.data;r(Le()(new Error(i),Pe,{retry:t>=5e3}))}else i.info&&console.info(`${i.info}`),i.warn&&console.warn(`${i.warn}`),i.min_conns||(i.min_conns=8),(!i.rejected||i.rejected&&i.share_only)&&i.id&&i.report_interval&&i.peers?(this.peerId=this.id=i.id,i.report_interval<20&&(i.report_interval=20),this.btStats(i.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,t(i)):(this.engine&&(this.engine.p2pEnabled=!1),r(Le()(new Error("msg not valid"),Pe,{retry:!1})))})).catch((t=>{e.error(`btAnnounce error ${t}`),r(Le()(t,Pe,{retry:!0}))}))}))}btStats(e=10){this.heartbeater=setInterval((()=>{this.postStats()}),1e3*e)}postStatsWithBeacon(){if(this.offline)return;this.offline=!0;let e={off:!0};this.statsRequesting||(e={...e,...this._makeStatsBody()}),navigator.sendBeacon(this.statsURL,JSON.stringify(e))}postStats(){const{logger:t}=this.engine;this.statsRequesting=!0,fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.statsRequesting=!1,this.reportFails=0,e.text()))).then((r=>{let i;if(i=r?JSON.parse(r):{ret:0,data:{}},-1===i.ret)clearInterval(this.heartbeater),t.error(`${i.data.msg} code ${i.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:r=0,failConns:i=0,rebuffers:s=0,requests:n=0,errsInternalExpt:a=0}=this.lastStats||{};this[Ge]>=e&&(this[Ge]-=e),this[je]>=t&&(this[je]-=t),this[He]>=r&&(this[He]-=r),this.failConns>=i&&(this.failConns-=i),this.errsBufStalled>=s&&(this.errsBufStalled-=s),this.mediaRequests>=n&&(this.mediaRequests-=n),this.errsInternalExpt>=a&&(this.errsInternalExpt-=a),this.exptMsg&&(this.exptMsg=void 0)}})).catch((e=>{t.error(`btStats error ${e}`),this.statsRequesting=!1,this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e,t=!1){const{logger:r}=this.engine,{asn:i,country:s}=this.announceInfo;let n={exclusions:e,asn:i,country:s,ratio:this.health.healthRatio,urgent:t||void 0},a={};return this.engine.getExtraForPeersRequest&&(a=this.engine.getExtraForPeersRequest()),n=Object.assign({},n,a),new Promise(((e,t)=>{fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(n)}).then((e=>e.json())).then((r=>{-1===r.ret?t(new Error(r.data.msg)):e(r.data)})).catch((e=>{r.error(`btGetPeers error ${e}`),t(e)})).finally((()=>{this.health.resetTraffic()}))}))}increFailConns(){this.failConns++}increRebuffers(){this.errsBufStalled++}increMediaRequests(){this.mediaRequests++}reportFlow(e){const t=Math.round(e/1024);this[Ge]+=t,this.totalHTTPDownloaded+=t,this.health.recordHttp(t),this._emitStats()}reportDCTraffic(e,t){const r=Math.round(e/1024);this[je]+=r,this.totalP2PDownloaded+=r,this.health.recordP2p(r),this.speed=Math.round(t),this._emitStats()}reportUploaded(e=0){const t=Math.round(e/1024);this.totalP2PUploaded+=t,this.health.recordShare(t),this[He]+=t,this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),this.removeAllListeners(),clearInterval(this.heartbeater)}_emitStats(){this.engine.emit("stats",{totalHTTPDownloaded:this.totalHTTPDownloaded,totalP2PDownloaded:this.totalP2PDownloaded,totalP2PUploaded:this.totalP2PUploaded,p2pDownloadSpeed:this.speed});const e=this.config.getStats;e&&"function"==typeof e&&e(this.totalP2PDownloaded,this.totalP2PUploaded,this.totalHTTPDownloaded,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let r={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,rebuffers:this.errsBufStalled||void 0,requests:this.mediaRequests||void 0,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[Ge])||0,p2p:Math.round(this[je])||0,share:Math.round(this[He])||0,asn:e,country:t},i={};return this.engine.getExtraForStats&&(i=this.engine.getExtraForStats()),r=Object.assign({},r,i),this.lastStats=JSON.parse(JSON.stringify(r)),Object.keys(r).forEach((e=>{0===r[e]&&delete r[e]})),this.exptMsg&&(r.exptMsg="2.7.4 "+this.exptMsg),r}get _requestHeader(){let e={};return this.native&&(e={...e,token:this.key,"User-Agent":"electron",appid:this.announceInfo.bundle}),e}}const We=$e;const Ke=0,qe=1,Ve=2,ze=3,Ye=(e,t,r,i,s)=>e.filter((e=>e.bitset.hasWithId(r,i,s,t)));class Xe{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const r=Number(e);if(r<0)continue;const i=new Map;if(t[e])for(let r of t[e])i.set(r,{state:qe,segId:void 0});this.levelMap.set(r,i)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,r,i=Ke){if(t<0)return!1;const s=this._createOrGetSet(t).get(e);return!!s&&((!r||!s.segId||s.segId===r)&&(i===Ke||s.state===i))}has(e,t,r=Ke){return this.hasWithId(e,t,void 0,r)}hasCompleteOr(e,t,r=qe){const i=this._createOrGetSet(t).get(e);return!!i&&(i.state===qe||i.state===r)}getObj(e,t){let r=this._createOrGetSet(t).get(e);return r||(r={}),r}getSegId(e,t){return this.getObj(e,t).segId}getState(e,t){return this.getObj(e,t).state}delete(e,t){const r=this._createOrGetSet(t);return-1===t?(this.levelMap.forEach((t=>{t.delete(e)})),!0):r.delete(e)}add(e,t,r,i){if("number"!=typeof(s=e)||s%1!=0)return;var s;this._createOrGetSet(t).set(e,{state:i,segId:r}),this.isLive&&this._trimBitset(e)}array(e){const t=this._createOrGetSet(e);return this._keysForStateComplete(t)}allArray(){let e={};return this.levelMap.forEach(((t,r)=>{e[r]=this._keysForStateComplete(t)})),e}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetSet(e).size}_createOrGetSet(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}_trimBitset(e){const t=e-20;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[r,i]of e)i.state===qe&&t.push(r);return t}}class Qe{constructor(){this.levelMap=new Map}totalLevels(){return this.levelMap.size}has(e,t){return this._createOrGetMap(t).has(e)}delete(e,t){return this._createOrGetMap(t).delete(e)}decre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);1===t?r.delete(e):r.set(e,t-1)}}incre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);r.set(e,t+1)}else r.set(e,1)}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetMap(e).size}_createOrGetMap(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}}const Je=class{constructor(){this.peerMap=new Map}isEmpty(){return 0===this.peerMap.size}size(){return this.peerMap.size}clear(){this.peerMap.clear()}getPeers(){return[...this.peerMap.values()]}getPeerValues(){return this.peerMap.values()}hasPeer(e){return this.peerMap.has(e)}addPeer(e,t){this.peerMap.set(e,t)}getPeerIds(){return[...this.peerMap.keys()]}removePeer(e){this.peerMap.delete(e)}getPeersOrderByWeight(){const e=this.getAvailablePeers();return e.sort(((e,t)=>0===t.weight?1:0===e.weight?-1:t.weight-e.weight)),e}getPeer(e){return this.peerMap.get(e)}getAvailablePeers(){return this.getPeers().filter((e=>e.isAvailableUrgently))}},Ze=1,et=2,tt=3,rt=4;class it{constructor(e){this.generator=e,this.status=Ze,this.next=this.next.bind(this)}next(e){if(this.status===rt)return console.warn("status is canceled");if(this.status===et)return console.warn("status is waiting");const t=this.execute.bind(this,this.cb);this.nextInfo=this.generator(t),this.status=et,this.nextInfo.execute(e)}execute(e,t){this.status=tt,e.apply(t,[this.next])}cancel(){this.status=rt,this.nextInfo&&"function"==typeof this.nextInfo.cancel&&this.nextInfo.cancel()}start(e,t){if("function"!=typeof e)throw new SyntaxError("param cb must be a function");this.cb=e,this.next(t)}continue(e){this.status=Ze,this.next(e)}}const st=Symbol("shareOnly");class nt extends(n()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new Je,this._setupEngine&&this._setupEngine(),this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[st]=!1,this.downloadOnly=!1,this.loadedPeerNum=0}get isMobileNet(){return this.engine.isMobileNet}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const e=this.getStatsForPeer();let t=this.peersNum;const r=u();this.getPeers().forEach((i=>{t>4&&(r-i.dataExchangeTs>150||r-i.gotStatsTs>=83)?(this.logger.warn(`close dead or different level peer ${i.remotePeerId} level ${i.currentLevel}`),i.close(!1),t--):i.connected&&i.sendMsgStats(t,e)}))}),4e4)}getStatsForPeer(){return{}}getNonactivePeers(){const e=u();return this.getPeers().filter((t=>e-t.dataExchangeTs>150)).sort(((e,t)=>e.dataExchangeTs-t.dataExchangeTs))}requestPeers(){this.logger.info("request peers from peer");const t={event:e.DC_GET_PEERS};for(let e of this.getPeers())e.mobileNet||e.super||e.sendJson(t)}chokePeerRequest(t){const r={event:e.DC_CHOKE};t?t.sendJson(r):this._broadcastToPeers(r)}unchokePeerRequest(t){const r={event:e.DC_UNCHOKE};t?t.sendJson(r):this._broadcastToPeers(r)}stopRequestFromPeers(){for(let e of this.getPeers())e.choked=!0}resumeRequestFromPeers(){for(let e of this.getPeers())e.choked=!1}setShareOnly(){this[st]=!0}deletePeer(e){this.peerManager.hasPeer(e.remotePeerId)&&this.peerManager.removePeer(e.remotePeerId),this._peersStats(this.peerManager.getPeerIds())}getPeers(){return[...this.peerManager.getPeerValues()]}addPeer(e){const{logger:t}=this;this.peerManager.addPeer(e.remotePeerId,e),this[st]&&(e.choked=!0);const r=this.peerManager.getPeerIds();this._peersStats(r),t.info(`add peer ${e.remotePeerId}, now has ${r.length} peers`),!e.mobileNet&&!this.waitForPeer&&e.isInitiator&&this.peersNum<=5&&e.peersConnected>1&&e.sendPeersRequest()}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const{logger:e}=this,t=this.getIdlePeer().length;if(e.info(`peers: ${this.peersNum} idle peers: ${t}`),te.downloading));e.warn(`downloading: ${r.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of r)e.warn(`${t.remotePeerId} loading ${t.segId} packets ${t.bufArr.length} total ${t.pieceMsg.attachments}`)}return t>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(t){this.bufMgr=t,t.on(e.BM_LOST,(({sn:t,segId:r,next:i,level:s})=>{this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:r,level:s||void 0}),this.onBufferManagerLost(t,r,i,s)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),this.checkTimer&&this.checkTimer.cancel(),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(t){const{logger:r}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),r.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}, canceled ${e.canceled||!1}`))})).on(e.DC_PIECE_ABORT,(e=>{r.warn(`peer ${t.remotePeerId} download aborted, reason ${e.reason}`),t.downloading&&this._handlePieceAborted&&this._handlePieceAborted(t.remotePeerId),t.downloading=!1})).on(e.DC_REQUEST,(()=>{})).on(e.DC_SEND_REQUEST,(()=>{}))}_broadcastToPeers(e){for(let t of this.getPeers())t.sendJson(e)}_peersStats(e){this.engine.emit("peers",e);const t=this.engine.config.getPeersInfo;t&&"function"==typeof t&&t(e)}startCheckPeersTimer(e=3e3){this.checkTimer=new it((function(e){let t;return{execute:function(r=1e3){t=setTimeout(e,r)},cancel:function(){clearTimeout(t)}}})),this.checkTimer.start((e=>{this.checkPeers();const t=1e3*(0===(r=this.loadedPeerNum)?3:.5*r+1.67);var r;this.logger.info(`loaded peers ${this.loadedPeerNum} nextDelay ${t}`),this.loadedPeerNum=0,e(t)}),e)}}const at=nt;class ot extends(n()){constructor(e){super(),this.internalMap=new Map,this.eventName=e}has(e,t){return this.internalMap.has(this._generateId(e,t))}set(e,t,r){const i=this._generateId(e,t);this.internalMap.set(i,r),this.emit(`${this.eventName}${e}-${t}`,r)}get(e,t){return this.internalMap.get(this._generateId(e,t))}delete(e,t){const r=this._generateId(e,t),i=this.internalMap.get(r);return!!i&&(i.destroy(),this.internalMap.delete(r),!0)}clear(){this.internalMap.clear(),this.removeAllListeners()}_generateId(e,t){return"number"!=typeof t&&(t=Number(t)),`${t}-${e}`}}const lt=0,ht=1,ut=2,ct=3;class dt extends(n()){constructor(e,r,i,s,n,a=!1,o){super(),this.coordinator=e,this.logger=r,this.rangeSupported=a,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=2e3,this.allowLoadPartial=!1,this.pieceMsg={event:t.DC_PIECE,sn:i,level:s,seg_id:n},o&&this.setExtra(o),this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.forwardBufList=[],this.reverseBufList=[],this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.timer=void 0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.rangeRequesting=!1,this.waitingRemain=!1,this.httpLoaded=0,this.p2pLoaded=0,this.deadline=0,this.p2pCanceled=!1}get segId(){return this.pieceMsg.seg_id}isDownloading(){return this.timeReceivePiece>0}isAlmostDeadline(){return!!this.rangeRequesting||this.deadline>0&&this.deadline-performance.now()<400}hasPeer(e){return!!e&&(e===this.forwardPeer||e===this.reversePeer)}_notifyStreamListeners(e,t,r){const{sn:i,seg_id:s,attachments:n}=this.pieceMsg,a=e&&0===r||!e&&r===n-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;e?this.reverseBufList.push(t):this.forwardBufList.push(t),a&&(this.forwardBufList.push([...this.reverseBufList].reverse()),this.reverseBufList.push([...this.forwardBufList].reverse()));for(let e of o){const{handler:r}=e;r(i,s,!1,t,a)}a&&(o.length=0)}_notifyStreamListenersAbort(){const e=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let t of e){const{handler:e}=t;e(void 0,void 0,!0,"aborted by synthesizer")}e.length=0}_notifyStreamListenersRemain(){if(this.forwardStreamListeners.length>0){for(let e=this.forwardOffset+1;e0){for(let e=this.reverseOffset-1;e>=0;e--)this._notifyStreamListeners(!0,this.bufArr[e],e);this.reverseStreamListeners=[]}}addStreamListener(e,t,r){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:r,peerId:t})}removeStreamListener(e){const t=t=>t.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=t(this.forwardStreamListeners),this.reverseStreamListeners=t(this.reverseStreamListeners)}setTimeout(e=0){e<=0?setTimeout((()=>{this._handleTimeout(!1,!1)}),0):(this.deadline=performance.now()+e,this._startTimer(e))}setExtra(e={}){e.url&&(this.url=e.url),e.rangeStart&&(this.rangeStart=e.rangeStart),e.rangeEnd&&(this.rangeEnd=e.rangeEnd),e.httpLoadTime&&(this.httpLoadTime=e.httpLoadTime),e.allowLoadPartial&&(this.allowLoadPartial=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup),e.headers&&(this.headers=e.headers),e.segId&&!this.pieceMsg.seg_id&&(this.pieceMsg.seg_id=e.segId)}hasForwardPeer(){return!!this.forwardPeer}hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e){this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1)}setReversePeer(e){this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0)}deletePeer(e,t=!1){const r=e===this.reversePeer;this._detachPeer(e),r?(this.reversePeer=null,t&&(this.reverseOffset=this.pieceMsg.attachments||1e4)):(this.forwardPeer=null,t&&(this.forwardOffset=-1)),this.isEmpty()&&this._handleTimeout(!1,!1)}terminate(){this._handleTimeout(!1,!1)}_emitPartialOrError(e){if(this.allowLoadPartial&&this.hasPartialBuffer()){const[e,r]=this.getPartialBuffer();this.emit(t.SYN_PARTIAL,this.pieceMsg,e,r)}else this.emit(t.SYN_ERROR,this.pieceMsg,e)}hasPartialBuffer(){return this.hasForwardBuffer()||this.hasReverseBuffer()}hasForwardBuffer(){return this.forwardOffset>=0}hasReverseBuffer(){return this.pieceMsg&&this.reverseOffset=0?a.l.concat(this.bufArr.slice(0,this.forwardOffset+1)):null,this.pieceMsg&&this.reverseOffset!!e)).forEach((i=>{i.cancelDownload(t,r,e)}))}destroy(){this.logger.info("destroy syn"),clearTimeout(this.timer),this._notifyStreamListenersAbort(),this._cancelP2p(),this.removeAllListeners(),this.destroyed=!0,this._detachPeer(this.forwardPeer),this.forwardPeer=null,this.forwardOffset=-1,this._detachPeer(this.reversePeer),this.reversePeer=null,this.reverseOffset=1e4,this.bufArr=[],this.forwardStreamListeners=[],this.reverseStreamListeners=[]}_detachPeer(e){if(!e)return;const r=e===this.reversePeer?this.reverseEvents:this.forwardEvents;e.off(t.DC_PIECE_DATA,r.onPieceData).off(t.DC_PIECE,r.onPiece).off(t.DC_PIECE_NOT_FOUND,r.onPieceNotFound).off(t.DC_PIECE_ABORT,r.onPieceAbort)}_receivePacket(e,r,i,s=!0){const{seg_id:n,sn:o,level:l,size:h}=this.pieceMsg,u=r-1;if(this.bufArr[u])return this.logger.warn(`syn bufArr ${this.pieceMsg.sn} already has ${u} size ${i.byteLength}`),!1;if(s?this.p2pLoaded+=i.byteLength:this.httpLoaded+=i.byteLength,this.bufArr[u]=i,e?this.reverseOffset=u:this.forwardOffset=u,this._notifyStreamListeners(e,i,u),this.forwardOffset!==this.reverseOffset-1)return!0;this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0),clearTimeout(this.timer),this._notifyStreamListenersRemain();const c=h/(performance.now()-this.timeStart);let d=a.l.concat(this.bufArr);const f=d.byteLength;if(f===h){let e=d.buffer;const r=new P(o,n,e,this.getFromPeerId(),l);this.emit(t.SYN_OUTPUT,r,{speed:c,p2p:this.p2pLoaded,http:this.httpLoaded})}else{this.logger.error(`${l}-${o} expectedSize ${h} != byteLength ${f} forward ${this.forwardOffset} reverse ${this.reverseOffset}`);for(let e=0;e{if(this.destroyed)return;if(!this._validateMsg(t,a.level,r))return void this.logger.warn(`onPieceData ${a.level}-${t} not match ${JSON.stringify(this.pieceMsg)} from ${e.remotePeerId}`);const{reverse:o}=a;this._receivePacket(o,s,i)&&!this.waitingRemain&&!this.rangeRequesting&&this.deadline>0&&this._shouldSwitch()&&(this.logger.warn("should switch to http"),clearTimeout(this.timer),this._handleTimeout(!1,!1))},s=r=>{if(this.destroyed)return;const{attachments:i,size:s,sn:n,level:a,seg_id:o}=r;return s&&this._validateMsg(n,a,o)?this.pieceMsg.size&&s!==this.pieceMsg.size?(this.logger.warn(`onPiece ${r.level}-${r.sn} size not match`),void this.emit(t.SYN_ERROR,this.pieceMsg,lt)):void(0===this.bufArr.length&&(this.pieceMsg={...this.pieceMsg,seg_id:o,size:s,attachments:i},this.reverseOffset=i,this.bufArr=new Array(i),this.timeReceivePiece=performance.now())):(this.logger.warn(`onPiece ${JSON.stringify(r)} not match ${JSON.stringify(this.pieceMsg)}`),void this.deletePeer(e))},n=t=>{this.destroyed||this.deletePeer(e)},a=()=>{this.destroyed||this.deletePeer(e)},o={onPieceData:i,onPiece:s,onPieceNotFound:n,onPieceAbort:a};r?this.reverseEvents=o:this.forwardEvents=o,e.on(t.DC_PIECE_DATA,i).once(t.DC_PIECE,s).once(t.DC_PIECE_NOT_FOUND,n).once(t.DC_PIECE_ABORT,a)}_validateMsg(e,t,r){return(!this.pieceMsg.seg_id||r===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}_shouldSwitch(){const e=this.pieceMsg.size-64e3*this.loadedPackets();return this.coordinator.shouldSwitchToHttp(e,this.deadline,this.p2pSpeed,64e3,this.httpLoadTime)}_startTimer(e,t=!0){this.timer=setTimeout(this._handleTimeout.bind(this,t),e)}loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(e=!1,r=!0){if(this.destroyed)return;const{level:i,sn:s,size:n,attachments:a}=this.pieceMsg;if(!n||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${i}-${s} url ${this.url}`),void this.emit(t.SYN_ERROR,this.pieceMsg,lt);if(e&&this.timeReceivePiece>0&&(this.logger.warn(`syn ${this.loadedPackets()} of ${a} packets loaded`),this.shouldWaitForRemain(this.httpLoadTime))){const e=this.httpLoadTime;return this.waitingRemain=!0,this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}if(r){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>e.currentLoadSpeed()-t.currentLoadSpeed())).shift();e&&e.loadtimeout()}if(this._cancelP2p(),this.rangeSupported&&this.url)return this._loadRemainBufferByHttp();this._notifyStreamListenersAbort(),this._emitPartialOrError(ct)}shouldWaitForRemain(e){if(e<=0||this.isEmpty())return!1;const t=performance.now()-this.timeStart;return t<500||t<1e3&&this.timeReceivePiece>0&&e>3e3||this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed;let r=0;[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(r+=e.loadedBytes())}));const i=(this.pieceMsg.size-r)/e;return this.logger.info(`syn remainTime ${e} speed ${t} required ${i}`),t>=i}get p2pSpeed(){let e=0;return[this.forwardPeer,this.reversePeer].forEach((t=>{t&&(e+=t.currentLoadSpeed())})),e}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull()&&e!==t?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}_loadRemainBufferByHttp(){if(this.rangeRequesting)return;const{size:e,sn:r,level:i}=this.pieceMsg,s=this.rangeEnd>0?this.rangeEnd-1:0,n=this.forwardOffset,l=function(e,t,r,i=0,s=0){const n=o;let a="bytes=",l=i,h=s||r-1;const u=Math.floor(r/n),c=r%n>0?u+1:u;e>=0&&(l+=(e+1)*n),a=`${a}${l}-`,t>=0&&t6e3&&(u=6e3),this.logger.info(`continue download ${i}-${r} from ${this.url} range: ${l} timeout ${u}`),this.rangeRequesting=!0,this.headers&&(this.xhrSetup=e=>{for(const t of Object.keys(this.headers))e.setRequestHeader(t,this.headers[t])}),d(this.url,l,this.xhrSetup,u).then((e=>{if(this.destroyed)return;if(this.rangeRequesting=!1,!e)return void this.emit(t.SYN_ERROR,this.pieceMsg,ht);let i=a.l.from(e);const s=i.byteLength/(performance.now()-h);this.coordinator.addHttpSpeed(s),i.byteLength===this.pieceMsg.size&&this.logger.warn(`syn range request ${r} resp whole ts`);const o=v(i,0);let l=n+1;for(let e=0;e{if(this.destroyed)return;this.rangeRequesting=!1,this.logger.error(`http partial download ${r} error ${e}`);const i="timeout"===e?ut:ht;this.emit(t.SYN_ERROR,this.pieceMsg,i)}))}_print(){const{level:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e}-${t}`)}}class ft{constructor(){this.meanHttpSpeed=0}addHttpSpeed(e){this.meanHttpSpeed=.4*this.meanHttpSpeed+.6*e}shouldSwitchToHttp(e,t,r,i,s){if(this.meanHttpSpeed<=0)return!1;if(r>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*s>=e)return!1;return((s+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-r)*r{if(e.bitset&&t.sn>=0){const{sn:r,level:i,complete:s,seg_id:n}=t;this._receiveDCHave(r,i,n);const a=s?qe:Ve;e.bitset.add(r,i,n,a),e.isAvailableUrgently&&this._handleDCHave(e,r,i,n,a)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:r,level:i,seg_id:s}=t;this._receiveDCHave(r,i,s),e.bitset.hasCompleteOr(r,i,ze)||e.bitset.add(r,i,s,ze),e.isAvailableUrgently&&this._handleDCHave(e,r,i,s,ze)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:r,level:i}=t;e.bitset.has(r,i)&&(e.bitset.delete(r,i),this.bitCounts.decre(r,i))})).on(t.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=7||this.notifyAllPeers(e.sn,e.level,e.seg_id,e.reverse?ze:Ve)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:r,level:i}=t,s=this.requestingMap.get(r,i);if(s)return void s.removeStreamListener(e.remotePeerId);const n=this.segmentBuilderMap.get(r,i);n&&n.removeStreamListener(e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:r,level:i}=t;e.bitset.delete(r,i),this.bitCounts.decre(r,i),e.checkIfNeedChoke(!0)})).on(t.DC_REQUEST,(async r=>{const{logger:i}=this,{sn:s,level:n,reverse:a}=r;this.isUploader=!0;let o=r.seg_id;o||(o=await this.bufMgr.getSegIdBySN(s));const l=this.requestingMap.get(s,n);let h=!1;l&&l.isDownloading()&&(h=!0);const u=await this.bufMgr.getSegById(o);if(u)i.info("found seg from bufMgr"),u.level===n?e.sendBuffer(u.sn,u.segId,u.data,{from:this.engine.swVersion?"SWCache":"Cache",level:u.level,reverse:a}):e.sendPieceNotFound(s,o,{level:n});else if(h){i.info(`syn had ${l.loadedPackets()} packets, wait remain from upstream ${l.getFromPeerId()}`);const t={...l.pieceMsg,reverse:a},r=a?l.reverseBufList:l.forwardBufList;e.sendPartialBuffer(t,r,{from:l.isFull()?"WaitPartialDouble":"WaitPartialSingle",incompletes:1}),r.length=this.loadingSN){let r;const l=l=>{this.segmentBuilderMap.off(`${t.BUILDER_MAP_HAVE}${s}-${n}`,r),l&&l.level===n?(i.info(`peer request notify seg ${l.sn}`),e.sendBuffer(l.sn,l.segId,l.data,{from:"NotifySegment",level:l.level,reverse:a})):e.sendPieceNotFound(s,o,{level:n})};r=r=>{this.bufMgr.off(`${t.BM_ADDED_SN_}${s}`,l),c(r,e)},i.info(`peer request ${s} wait from fragLoader`),this.segmentBuilderMap.once(`${t.BUILDER_MAP_HAVE}${s}-${n}`,r),this.bufMgr.once(`${t.BM_ADDED_SN_}${s}`,l)}else e.sendPieceNotFound(s,o,{level:n})}function c(e,t){t.sendPartialBuffer(e.pieceMsg,e.bufferList,{from:e.source,incompletes:1}),e.bufferList.length{i?t.sendMsgPieceAbort(s):t.send(s),n&&(t.uploading=!1)}))}}))}handleMetaData(e,t){if(t.field){e.bitset=new Xe(this.config.live,t.field);for(let e in t.field){const r=Number(e);if(r<0)continue;t.field[r].forEach((e=>{this.bitset.has(e,r)||this.bitCounts.incre(e,r)}))}this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e)}}peersHas(e,t){return this.bitCounts.has(e,t)}deletePeer(e){if(this.peerManager.hasPeer(e.remotePeerId)&&e.bitset){const t=e.bitset.allArray();for(let e in t){const r=Number(e),i=t[r];i&&i.forEach((e=>{this.bitCounts.decre(e,r)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,r,i){const{logger:s,config:n}=this;this.waitForPeer&&(this.mBufferedDuration=i=n.waitForPeerTimeout+n.httpLoadTime);let a=1e3*(i-n.httpLoadTime);const o=n.httpLoadTime+1.5;if(s.info(`bufferedDuration ${i} remainLoadTime ${a}`),i<=o)return!1;if(this.requestingMap.has(e,t)){const l=this.requestingMap.get(e,t);if(!l)return this._searchAvailablePeers(e,t,r);const h=l.segId;if(h&&h!==r)return s.warn(`syn segId ${h} not match ${r}`),this.requestingMap.delete(e,t),this._searchAvailablePeers(e,t,r);if(!l.shouldWaitForRemain(a)){if(s.warn(`syn prefetch timeout at ${e}`),l.isFull())return!1;const a=this.peerManager.getPeersOrderByWeight(),h=Ye(a,qe,e,t,r);let u=Ye(a,Ve,e,t,r),c=Ye(a,ze,e,t,r);if(l.hasReversePeer()){if(u=h.concat(u),u.length>0)return this.targetPeers.forwardPeer=u[0],!0}else if(l.hasForwardPeer()){if(c=h.concat(c),c.length>0)return this.targetPeers.reversePeer=c[0],!0}else{if(h.length>0)return l.hasForwardBuffer()?this.targetPeers.reversePeer=h[0]:this.targetPeers.forwardPeer=h[0],!0;{let e=!1;if(u.length>0&&(this.targetPeers.forwardPeer=u[0],e=!0),c.length>0&&(this.targetPeers.reversePeer=c[0],e=!0),e)return!0}}return!l.isEmpty()&&n.httpRangeSupported&&i>o+1}return s.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t,r)}_searchAvailablePeers(e,t,r){if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const i=this.peerManager.getPeersOrderByWeight(),[s,n]=((e,t,r,i)=>{const s=Ye(e,qe,t,r,i);if(s.length>=2)return[s[0],s[1]];if(1===s.length){const n=Ye(e,Ve,t,r,i);if(n.length>=1)return[n[0],s[0]];const a=Ye(e,ze,t,r,i);return a.length>=1?[s[0],a[0]]:0===c(0,1)?[null,s[0]]:[s[0],null]}const n=Ye(e,Ve,t,r,i);if(n.length>=1)return[n[0],null];const a=Ye(e,ze,t,r,i);return a.length>=1?[null,a[0]]:[null,null]})(i,e,t,r);return this.targetPeers={forwardPeer:s,reversePeer:n},[s,n].some((e=>!!e))}reportTraffic(e,t,r){const{fetcher:i}=this.engine;i?(e>0&&i.reportFlow(e),t>0&&i.reportDCTraffic(t,r)):this.logger.error("DC report failed")}notifyAllPeers(e,t,r,i=qe){if(!r)return void this.logger.error("segId is required");if(this.downloadOnly)return;const{live:s}=this.config;if(this.bitset.has(e,t,i))return;const n=((e,t,r)=>`${e}-${t}-${r}`)(e,t,i);let a;i!==ze&&(a=i===qe);const o=this.requestingMap.get(e,t);for(let l of this.getPeers())o&&o.hasPeer(l)||l.notifySet.has(n)||l.bitset.hasCompleteOr(e,t,i)||l.uploading||(l.sendMsgHave(e,r,{level:t,reverse:i===ze,complete:a}),l.notifySet.add(n),s&&m(l.notifySet,20))}checkPeers(){if(!this.hasPeers)return;const{logger:e,config:t,engine:r}=this,i=t.live,{currentLevel:s}=r;if(e.info(`currentLevel ${s}`),0===this.bitCounts.size(s))return;if(!i&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;if(this.mBufferedDuration=l&&!this.bufMgr.overflowed)d=h;else{const e=Math.min(...n.filter((e=>e.endSN>=d)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;dl)return;if(i&&d>this.loadingSN+2)return;if(this.bitset.has(d,s))d++;else{if(d!==this.loadingSN&&this.bitCounts.has(d,s)&&!this.requestingMap.has(d,s))for(let r of n)if(!a.includes(r)&&r.bitset.has(d,s)){const i=r.bitset.getState(d,s);let n;n=i===qe?0===c(0,1):i===ze,a.push(r);const o=r.bitset.getSegId(d,s),l=new dt(this.coordinator,this.logger,d,s,o,t.httpRangeSupported);this._setupSynthesizer(l),n?l.setReversePeer(r):l.setForwardPeer(r),this.requestingMap.set(d,s,l),r.requestDataBySN(d,!1,{level:s,reverse:n}),e.info(`request prefetch ${d} level ${s} from peer ${r.remotePeerId} downloadNum ${r.downloadNum} reverse ${n}`);break}u++,d++}}this.loadedPeerNum=a.length}onBufferManagerLost(e,t,r,i){this.currLostSN=e,r&&(this.nextLostSN=r),this.bitset.delete(e,i),this.bitCounts.delete(e,i)}cleanRequestingMap(e){const t=this.peerManager.getPeer(e);if(t)for(let[r,i]of this.requestingMap.internalMap){const s=r.split("-"),n=Number(s[1]),a=Number(s[0]);i.hasPeerId(e)&&(this.logger.info(`delete ${e} in synthesizer`),i.deletePeer(t),this.bitCounts.decre(n,a),t.bitset.delete(n,a))}}shouldWaitForNextSeg(){let e;return e=!this.isUploader&&(!!this.isReceiver||c(0,100)>20),this.isReceiver=this.isUploader=!1,e}updateLoaded(e,t,r){this.bitset.hasCompleteOr(e,t)||(this.bitset.add(e,t,r,qe),this.bitCounts.delete(e,t))}broadcastPlaylist(e,t){if(!this.config.live)return;const r=function(e){const t=e.split("\n");let r=0,i=0;for(let e of t){const t=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e);if(t&&t[1]){r=parseInt(t[1],10);break}}for(let e of t)e.startsWith("#EXTINF")&&i++;return r+i-1}(t);if(!this.isMobileNet){let i=0;for(let s of this.getPeers())if(i++,s.sendMsgPlaylist(e,t,r),i>=5)break}this.playlistInfo.set(e,{seq:r})}getPlaylistFromPeer(e){if(!this.config.live)return null;const{seq:t}=this.playlistInfo.get(e);for(let r of this.getPeers()){const i=r.getLatestPlaylist(e,t);if(i)return i}return null}getBufferedDuration(){let{media:e,currentSrc:t}=this.engine;if(!e||e.src!==t&&0===e.currentTime){if(this.logger.info("try get video element"),e=K(this.config.mediaElem,t),!e)return 5;this.engine.media=e}let r=0,i=e.currentTime,s=e.buffered;for(let e=s.length-1;e>=0;e--)if(i>=s.start(e)&&i<=s.end(e)){r=s.end(e)-i;break}return this.mBufferedDuration=r,r>0?r:0}destroy(){super.destroy(),this.requestingMap.clear(),this.segmentBuilderMap.clear()}_notifySynthesizer(e,t,r,i,s,n=!0){const{logger:a}=this,o=this.requestingMap.get(r,i);if(!o)return;const l=o.segId;function h(s,n){n?e.requestDataById(t,r,!0,{level:i,reverse:s}):(a.info(`notify syn prefetch ${r}`),e.requestDataBySN(r,!1,{level:i,reverse:s}))}function u(){return s===Ve||s===qe}function c(){return s===ze||s===qe}t&&l&&t!==l?a.warn(`notifySynthesizer segId ${t} not match ${l}`):o.isFull()||(o.isAlmostDeadline()?a.info("almost deadline, ignored"):o.isEmpty()?o.hasForwardBuffer()&&c()?(o.setReversePeer(e),h(!0,n)):o.hasReverseBuffer()&&u()&&(o.setForwardPeer(e),h(!1,n)):!o.hasForwardPeer()&&u()?(o.setForwardPeer(e),h(!1,n)):!o.hasReversePeer()&&c()&&(o.setReversePeer(e),h(!0,n)))}_setupEngine(){}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,r={level:e};if(t&&!this.config.live){const{currentTime:e}=t;r.pos=Math.round(e)}return r}_handleSynError(e){switch(e){case ht:this.logger.warn("ERROR_SYN_RANGE_REQUEST"),this.httpRangeErrs++;break;case ut:this.logger.warn("ERROR_SYN_HTTP_TIMEOUT"),this.httpTimeouts+=3}this.httpRangeErrs>=5&&(this.config.httpLoadTime<=4.5&&(this.config.httpLoadTime+=.5),this.httpRangeErrs=0)}}class pt{constructor(t,r,i,s){this.bufferList=[],this.streamListeners=[],this.finished=!1,this.packetSize=o,this.attachments=s%this.packetSize==0?s/this.packetSize:Math.floor(s/this.packetSize)+1,this.pieceMsg={event:e.DC_PIECE,attachments:this.attachments,seg_id:i,sn:t,level:r,size:s,reverse:!1},this.sink=(0,a.l)(0),this.source="HttpStream"}receiveBytes(e,t){e.byteLength&&(this.sink=a.l.concat([this.sink,e]),this.bufferList.push(e),t&&(this.finished=!0),this._notifyStreamListeners(e))}getCompleteBuffer(){return this.sink.buffer}destroy(){this.finished||this._notifyStreamListenersAbort()}addStreamListener(e,t,r){this.streamListeners.push({handler:r,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){for(let e of this.streamListeners){const{handler:t}=e;t(void 0,void 0,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:r}=this.pieceMsg;for(let i of this.streamListeners){const{handler:s}=i;s(t,r,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const vt=class extends gt{constructor(e,t){super(e,t),this.server=t.fetcher,this.p2pEnabled=e.p2pEnabled,this.resolveMap=new Map,this.dcDownloadTimeout=t.live?5:9,this.segmentId=t.segmentId,this.segmentBypass="function"==typeof t.segmentBypass?t.segmentBypass:()=>!1}async handleGetMediaData(e,r){const{logger:i,engine:s}=this;let{url:n,range:a}=e;const o=this._getFrag(n,a);if(!o)return i.warn(`cannot get frag ${n}`),r.postMessage({action:t.SW_GET_MEDIA});if(this.segmentBypass(n,o.tagList))return i.info(`bypass frag ${n}`),r.postMessage({action:t.SW_GET_MEDIA});s.currentLevelIndex=o.level;const{sn:l,level:h}=o,u=this.segmentId(String(h),l,n,a),c=u===this.loadingSegId;c&&i.warn(`duplicate request ${u}`),this.loadingSN=l,s.bufMgr&&(s.bufMgr.loadingSN=l),this.loadingSegId=u;const d=await this.bufMgr.getSegById(u);if(d)return i.info(`bufMgr found seg sn ${l} segId ${u}`),o.loaded=d.data.byteLength,o.fromPeerId=d.fromPeerId,s.emit(t.FRAG_LOADED,{url:n,sn:l,level:h,segId:u,loaded:o.loaded,duration:o.duration,byP2p:!0,fromPeerId:d.fromPeerId}),this._onFragLoaded(n,o),r.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:d.data,incomplete:!1}});const f=this.getBufferedDuration();if(i.info(`handleGetMediaData sn ${l} bufferedDuration ${f}`),this.resolveMap.has(l)||c){let e=this.requestingMap.get(l,h);if(e||c){e&&(i.warn(`${l} is requesting, terminate syn wait for seg`),e.terminate());let s=1e3*(f-this.config.httpLoadTime)+1e3;s<0&&(s=0);let a=setTimeout((()=>{i.info(`notify seg ${l} timeout`),a=-1,r.postMessage({action:t.SW_GET_MEDIA})}),s);this.bufMgr.once(`${t.BM_ADDED_SN_}${l}`,(e=>{a<0||e&&e.level===h&&(clearTimeout(a),i.info(`notify seg ${e.sn}`),r.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:e.data,incomplete:!1}}))}))}else i.warn(`${l} is requesting, fallback`),r.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(l,h,u,f)){await this._loadFragByP2p(o,r,l,u,n,h)||r.postMessage({action:t.SW_GET_MEDIA})}else{const e=this.requestingMap.get(l,h);if(this.httpRangeSupported&&e&&e.segId===u&&e.hasPartialBuffer()){i.warn(`syn has partial buffer for ${u}`);const[s,a]=e.getPartialBuffer();r.postMessage({action:t.SW_GET_MEDIA,data:{url:n,bufferLeft:s,bufferRight:a,incomplete:!0,size:e.pieceMsg.size}},[s,a].filter((e=>!!e)).map((e=>e.buffer)))}else r.postMessage({action:t.SW_GET_MEDIA})}}async _loadFragByP2p(e,r,i,s,n,a){const{logger:o}=this;o.info(`p2p load sn ${i} segId ${s} level ${a}`);const l=await this.load(i,s,a);if(l&&(l.data||l.incomplete)){const{data:h,incomplete:u,fromPeerId:c,bufferLeft:d,bufferRight:f,size:g}=l;if(u)o.info(`p2p loaded partial segId ${s} level ${a} size ${g}`),e.loaded=(d?d.byteLength:0)+(f?f.byteLength:0);else{if(o.info(`p2p loaded segId ${s} level ${a} size ${h.byteLength} incomplete ${u}`),!await this.bufMgr.hasSegOfId(s)){const e=new P(i,s,h,c,a);o.info(`bufMgr putSeg ${i} level ${a}`),this.bufMgr.putSeg(e)}e.loaded=h.byteLength}return e.fromPeerId=c,this.engine.emit(t.FRAG_LOADED,{url:n,sn:i,level:a,segId:s,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:c}),this._onFragLoaded(n,e),r.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:h,bufferLeft:d,bufferRight:f,incomplete:u,size:g}},[d,f].filter((e=>!!e)).map((e=>e.buffer))),!0}o.warn(`P2P timeout load segId ${s}`);const h=await this.bufMgr.getSegById(s);return!!h&&(o.info(`already loaded seg sn ${i} segId ${s}`),r.postMessage({action:t.SW_GET_MEDIA,data:{url:n,buffer:h.data,incomplete:!1}}),!0)}_processStream(e,t,r,i,s){const n=o,{segmentBuilderMap:l}=this,h=new pt(r,i,s,t);h.source="SWHttpStream",l.has(r,i)||l.set(r,i,h);const u=e.getReader();let c=0,d=0,f=(0,a.l)(0);return new Promise(((e,t)=>{const r=()=>{u.read().then((({value:t,done:i})=>{if(t&&(c+=t.length),i){if(f.byteLength>0)if(c<=n){const e=(0,a.l)(c);f.copy(e,0,d*n,f.byteLength),h.receiveBytes(e,!0)}else{const e=v(f,d*n);for(let t=0;t=n){c-=n;const e=(0,a.l)(n);f.copy(e,0,d*n,(d+1)*n),d++,h.receiveBytes(e,!1)}r()})).catch((e=>{t(e)}))};r()}))}async handleMediaData(e,r){r.postMessage({action:t.SW_MEDIA});const{logger:i,engine:s}=this;let{url:n,buffer:a,stream:o,range:l,p2p:h,httpSpeed:u,size:c}=e;if(s.rangeTestUrl===n)return void(s.rangeTestUrl="");i.info(`SW_MEDIA url ${n} size ${c} range ${l} speed ${u}`),u&&this.coordinator.addHttpSpeed(u);const d=this._getFrag(n,l);if(!d)return;if(this.segmentBypass(n,d.tagList))return;const{sn:f,level:g}=d,p=this.segmentId(String(g),f,n,l);if(o){i.info(`got stream ${f}`),this.isMobileNet||this.notifyAllPeers(f,g,p,Ve);try{a=await this._processStream(o,c,f,g,p)}catch(e){return void i.warn(e)}finally{this.segmentBuilderMap.delete(f,g)}}this._handleMediaData(f,g,p,n,d,h,a)}async _handleMediaData(e,r,i,s,n,a,o){if(this.notifyAllPeers(e,r,i),n.segId=i,n.loaded=o.byteLength,this.engine.emit(t.FRAG_LOADED,{url:s,sn:e,level:r,segId:i,loaded:n.loaded,duration:n.duration,byP2p:!1}),this._onFragLoaded(s,n),!await this.bufMgr.hasSegOfId(i)){const t=new P(e,i,o,"",r);this.bufMgr.putSeg(t),this.logger.info(`bufMgr putSeg ${i} level ${r}`);const s=a&&a>0?a:0,n=o.byteLength-s;this.reportTraffic(n,s,0)}}notifySWMessage(e,r,i){switch(e){case t.SW_MEDIA:this.handleMediaData(r,i);break;case t.SW_PRE_MEDIA:this.handlePreMedia(r,i);break;case t.SW_GET_MEDIA:this.server.increMediaRequests(),this.handleGetMediaData(r,i);break;case t.SW_STREAM:this.handleStream(r);break;default:this.logger.warn(`unknown action ${e}`)}}handlePreMedia(e,r){r.postMessage({action:t.SW_PRE_MEDIA})}_getFrag(e,t){return t&&(e=`${e}|${t}`),this.fragMap.get(e)}handleStream(e){const{logger:t,segmentBuilderMap:r}=this;let{url:i,range:s,begin:n,size:a,buffer:o,done:l,aborted:h}=e;const u=this._getFrag(i,s);if(!u)return void t.warn(`handleStream cannot get frag ${i} range ${s}`);const{sn:c,level:d}=u,f=this.segmentId(String(d),c,i,s);if(n){t.info(`got stream ${c}`),this.isMobileNet||this.notifyAllPeers(c,d,f,Ve);const e=new pt(c,d,f,a);e.source="SWStream",r.has(c,d)||r.set(c,d,e)}else{if(h)return void r.delete(c,d);const e=r.get(c,d);if(!e)return;if(e.receiveBytes(o,l),l){const t=e.getCompleteBuffer();this._handleMediaData(c,d,f,i,u,0,t)}}}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(e,t){if(this.updateLoaded(t.sn,t.level,t.segId),!this.engine)return;const{media:r,targetDuration:i}=this.engine;!this.config.live&&r&&i&&(this.currPlaySN=Math.ceil(r.currentTime/i))}load(e,t,r){const{logger:i,config:s}=this;this.isReceiver=!0;let n=this.mBufferedDuration-this.config.httpLoadTime;n>this.dcDownloadTimeout&&(n=this.dcDownloadTimeout);const{forwardPeer:a,reversePeer:o}=this.targetPeers;a||o||(n-=1);let l=this.requestingMap.get(e,r),h={allowLoadPartial:this.httpRangeSupported,segId:t};l?l.setExtra(h):(l=new dt(this.coordinator,this.logger,e,r,t,this.httpRangeSupported,h),this._setupSynthesizer(l),this.requestingMap.set(e,r,l)),a&&(l.setForwardPeer(a),a.requestDataById(t,e,!0,{level:r})),o&&(l.setReversePeer(o),o.requestDataById(t,e,!0,{level:r,reverse:!0})),l.isEmpty()&&(n=0),i.info(`syn setTimeout ${n}`),l.setTimeout(1e3*n);const u=new Promise((i=>{const s={resolve:i,sn:e,level:r,segId:t,incomplete:!1};this.resolveMap.set(e,s)}));return this.targetPeers={},u}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,((t,r)=>{const{config:i,logger:s}=this,{segId:n,sn:a,data:o,level:l}=t,{speed:h,http:u,p2p:c}=r;this.httpTimeouts>0&&this.httpTimeouts--;const d=this.resolveMap.has(a);if(i.validateSegment(n,new Uint8Array(o))){this.notifyAllPeers(a,l,n),this.bitset.has(a,l)||this.reportTraffic(u,c,h);const r=e.getFromPeerId();if(d){s.info(`receive criticalSeg seg_id ${n}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:r})}else this.bitset.has(a,l)||(this.bufMgr.putSeg(t),this.updateLoaded(a,l,n))}else if(s.error(`segment ${n} validate failed`),d){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(a,l)})).on(t.SYN_PARTIAL,((t,r,i)=>{const{sn:s,level:n,size:a}=t;if(this.httpTimeouts++,this.resolveMap.has(s)){this.resolveMap.get(s).resolve({bufferLeft:r,bufferRight:i,fromPeerId:e.getFromPeerId(),incomplete:!0,size:a}),this.resolveMap.delete(s)}this.requestingMap.delete(s,n)})).on(t.SYN_ERROR,((t,r)=>{const{logger:i}=this,{sn:s,level:n}=t;if(this.resolveMap.has(s)){const e=this.resolveMap.get(s);this.resolveMap.delete(s),e.resolve()}r===ct&&e.hasPartialBuffer()?i.warn("syn abort with partial buffer"):this.requestingMap.delete(s,n)}))}_handleDCHave(e,t,r,i,s){const n=0!==this.resolveMap.size;this._notifySynthesizer(e,i,t,r,s),this.config.live&&!n&&L()((()=>{this.checkPeers()}))}};var mt=function(e,t){return mt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},mt(e,t)};function yt(e,t){function r(){this.constructor=e}mt(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Et(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,s,n=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return a}function St(){for(var e=[],t=0;t=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}(i),n=s.next();!n.done;n=s.next()){var a=n.value;this._callEventListener(e,a)}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,r=void 0===t?At.reconnectionDelayGrowFactor:t,i=e.minReconnectionDelay,s=void 0===i?At.minReconnectionDelay:i,n=e.maxReconnectionDelay,a=void 0===n?At.maxReconnectionDelay:n,o=0;return this._retryCount>0&&(o=s*Math.pow(r,this._retryCount-1))>a&&(o=a),this._debug("next delay",o),o},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,r=t.maxRetries,i=void 0===r?At.maxRetries:r,s=t.connectionTimeout,n=void 0===s?At.connectionTimeout:s,a=t.WebSocket,o=void 0===a?Lt():a;if(this._retryCount>=i)this._debug("max retries reached",this._retryCount,">=",i);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),void 0===(l=o)||!l||2!==l.CLOSING)throw Error("No valid WebSocket class provided");var l;this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new o(t,e._protocols):new o(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),n))}))}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new bt(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new _t(e,t,this))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();class wt extends(n()){constructor(e,t,r,i,s="main"){super(),this.logger=e,this.config=t,this.wsAddr=r,this.serverVersion=0,this.pingInterval=i||60,this._ws=this._init(),this.name=s}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:c(1e4,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20};let t=new Dt(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{let r=JSON.stringify(e);t.push(r)},t.addEventListener("message",(e=>{let t=e.data;const r=JSON.parse(t),i=r.action;if("pong"!==i){if("ver"!==i)return"close"===i?(this.logger.warn(`server close signal ${this.name} reason ${r.reason}`),void this.close()):void(this.onmessage&&this.onmessage(r,this.name));this.serverVersion=r.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),this.onclose&&this.onclose(),this._stopPing()})),t.addEventListener("error",(e=>{this.logger.error(`signal ${this.name} ${this.wsAddr} error`),this._stopPing(),this.onerror&&this.onerror(e)})),t}sendSignal(e,t){const r={action:"signal",to_peer_id:e,data:t};this._send(r)}sendReject(e,t,r){const i={action:"reject",to_peer_id:e,reason:t,fatal:r};this._send(i)}_send(e){this._ws&&this._ws.send(e)}_startPing(e=120){this.connected&&(this.pingTimer=setInterval((()=>{this._send({action:"ping"}),this.serverVersion>=22&&this._waitForPong()}),1e3*e))}_waitForPong(){this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),15e3)}_resetPing(){this._stopPing(),this._startPing(this.pingInterval)}_stopPing(){clearInterval(this.pingTimer),clearTimeout(this.pongTimer),this.pingTimer=null,this.pongTimer=null}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3,"normal close")})()}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.removeAllListeners()}get connected(){return!!this._ws&&this._ws.readyState===Dt.OPEN}}const It=wt,Pt=class extends(n()){constructor(e,t,r,i){super(),this.logger=e,this.config=t,this.mainAddr=r,this.backupAddr=i,this.mainWS=this._init(r),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(i,"backup"))}),900),this._connected=!1,this.destroyed=!1}_init(e,t){if(!e)return null;let r=new It(this.logger,this.config,e,270,t);return r.onopen=()=>{!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},r.onmessage=e=>{this.onmessage&&this.onmessage(e,r.name)},r.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},r.onerror=e=>{this.onerror&&this.onerror(e)},r}sendSignal(e,t,r){if(r){const i=this._getWSByName(r);i&&i.sendSignal(e,t)}else this.mainConnected?this.mainWS.sendSignal(e,t):this.backupConnected?this.backupWS.sendSignal(e,t):this.logger.warn("no signal available")}sendReject(e,t,r,i){if(i){const s=this._getWSByName(i);if(s)return void s.sendReject(e,t,r)}this.mainConnected?this.mainWS.sendReject(e,t,r):this.backupConnected?this.backupWS.sendReject(e,t,r):this.logger.warn("no signal available, send reject failed")}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close()}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(){this.mainWS&&this.mainWS.reconnect(),this.backupWS&&this.backupWS.reconnect()}destroy(){this.close(),clearTimeout(this.backupTimer),this.mainWS=null,this.backupWS=null,this.removeAllListeners(),this.destroyed=!0}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}};const Rt=function(e,t,r=40){var i=null,s=!1,n=r;return function(r=!1){if(r)return clearTimeout(i),void(s=!1);s||(s=!0,i=setTimeout((function(){e.call(t,n),s=!1,i=null}),1e3*n),n*=1.1)}};class Ct{constructor(e,t,r=15){this.engine=e,this.config=t,this.trickle=t.waitForPeer,this.poolSize=r,this.pool=[];for(let e=0;e{this.destroy()}),2e4)}_createPeer(){return new O(this.engine,void 0,void 0,!0,this.config,{trickle:this.trickle})}get size(){return this.pool.length}getPeer(){return 0===this.size?this._createPeer():this.pool.shift()}destroy(){for(let e of this.pool)e.destroy(!0);this.pool=[],clearTimeout(this.timer)}}class kt extends(n()){constructor(e,t,r,i){super(),this.engine=e,this.logger=e.logger,this.config=i,this.connected=!1,this.scheduler=r,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCSet=new Set,this.notFoundDCSet=new Set;const s=C().isMobile();this.peerPool=new Ct(e,i,s?10:15),this.signalerWs=null,this.fetcher=t,this.peers=[],this.minConns=5,this.stuns=[],this.requestMorePeers=Rt(this._requestMorePeers,this),this.maxConns=s?13:22,this.maxConnsActive=s?8:12,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.fuseRate=-1,this.overloaded=!1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:t,config:r,fetcher:i}=this,{btAnnounce:s,btAnnouncePreflight:n}=i,{wsSignalerAddr:a,wifiOnly:o,geoIpPreflight:l,getPeerId:h}=r;(l?n:s).call(i).then((e=>{if(!this.scheduler)return;t.peerId=this.peerId=e.id,this.minConns=e.min_conns;const r=e.peers;this.scheduler.notifyPeersLoaded(r.length),t.netType=i.announceInfo.netType,(e.wifi_only||o)&&t.isMobileNet&&(this.scheduler.downloadOnly=!0,this.logger.info("downloadOnly mode")),e.overload&&(this.overloaded=!0,this.logger.warn("server is overloaded, degrade"));const s=a.main;let n=a.backup;e.signal&&!e.signal2&&(n=void 0),this.signalerWs=this._initSignalerWs(e.signal||s,e.signal2||n,e.token,e.token2),0===r.length?this.requestMorePeers():this.peers=this._filterPeers(r),t.emit("peerId",this.peerId),h&&"function"==typeof h&&h(this.peerId),e.stun&&e.stun.length>0&&(this.stuns=e.stun),e.debug&&this.logger.enableDebug(),e.fuse_rate&&(this.fuseRate=e.fuse_rate),this.logger.info(`announce request response ${JSON.stringify(e,null,2)}`)})).catch((r=>{if("TRACKER_EXPT"===r.code&&t.emit(e.EXCEPTION,r),this.scheduler.notifyPeersLoaded(0),r.retry){const e=c(15e3,4e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.postStatsWithBeacon(),this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.peerPool.destroy(),this.peerPool=null,this.failedDCSet.clear(),this.notFoundDCSet.clear(),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}_filterPeers(e){const t=[],r=[...this.DCMap.keys(),...this.failedDCSet.keys(),this.peerId];return e.filter((e=>!r.includes(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator})})),t}_tryConnectToAllPeers(){if(0!==this.peers.length&&this.signalerWs.connected)for(this.logger.info(`try connect to ${this.peers.length} peers`);this.peers.length>0&&!(this.DCMap.size>=this.maxConnsActive);){let e=this.peers.shift();const t=e.intermediator;this.logger.debug(`new DataChannel ${e.id} intermediator ${t}`),this._createDatachannel(e.id,!0,t)}}_setupDC(t){t.on(e.DC_SIGNAL,((e,r)=>{const i=t.remotePeerId;if(t.intermediator){const r=this.DCMap.get(t.intermediator);if(r){if(r.sendMsgSignal(i,this.peerId,e))return;this.logger.warn(`intermediator ${t.intermediator} relay failed`)}}this.signalerWs.sendSignal(i,e,t.signalName)})).on(e.DC_PEER_SIGNAL,(e=>{const r=e.to_peer_id,i=e.from_peer_id,s=e.action;if(r&&i&&s)if(r!==this.peerId){this.logger.info(`relay signal for ${i}`);const n=this.DCMap.get(r);if(n){if("signal"!==s)return void n.sendMsgSignalReject(r,i,e.reason,e.fatal);if(n.sendMsgSignal(r,i,e.data))return}t.sendMsgSignal(i,r)}else"signal"===s?this._handleSignalMsg(i,e,t.remotePeerId):this._handSignalRejected(i,e)})).on(e.DC_GET_PEERS,(()=>{const e=u(),r=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?13:22)&&!e.super));if(r&&r.length>0){const i=[];r.forEach((r=>{if(r.remotePeerId===t.remotePeerId||r.remotePeerId===this.peerId)return;if(!this.config.live&&(r.currentPos-t.currentPos>600||r.currentPos50&&i.push({id:r.remotePeerId})})),this.logger.info(`send ${i.length} peers to ${t.remotePeerId}`),t.sendPeers(i)}})).on(e.DC_PEERS,(e=>{t.gotPeers=!0;const r=e.peers;if(r&&r.length>0&&this.scheduler.peersNum<10){const e=5;this.logger.info(`receive ${r.length} peers from ${t.remotePeerId}`),r.forEach((e=>{e.intermediator=t.remotePeerId})),this.peers=this._filterPeers(r).slice(0,e),this._tryConnectToAllPeers()}})).once(e.DC_ERROR,(e=>{this.logger.info(`datachannel ${t.channelId} failed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._destroyAndDeletePeer(t.remotePeerId,e),this.requestMorePeers(),this.fetcher&&(t.connected||e&&this.fetcher.increFailConns(),e&&this.failedDCSet.add(t.remotePeerId),this._doSignalFusing(this.scheduler.peersNum),this._tryConnectToAllPeers()))})).once(e.DC_TIMEOUT,(()=>{this.notFoundDCSet.add(t.remotePeerId)})).once(e.DC_CLOSE,(e=>{this.logger.info(`datachannel ${t.channelId} closed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(t.remotePeerId,e),e&&this.failedDCSet.add(t.remotePeerId),this.requestMorePeers(),this._tryConnectToAllPeers()})).once(e.DC_OPEN,(()=>{t.isInitiator&&this.scheduler.handshakePeer(t)})).once(e.DC_METADATA,(e=>{const{scheduler:r}=this;t.isInitiator||r.handshakePeer(t),r.handleMetaData(t,e);const i=this.DCMap.size>=this.minConns+3;this.requestMorePeers(i),this.peersIncrement++,this._doSignalFusing(r.peersNum+1)}))}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate+2?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e{let r=`${e}?id=${this.peerId}&p=web&v=2.7.4`;return t&&(r=`${r}&token=${t}`),r};let a,o=n(t,i);if(!this.overloaded&&r&&r!==t){let e=n(r,s);a=new Pt(this.logger,this.config,o,e)}else a=new It(this.logger,this.config,o,270);return a.onopen=()=>{this.connected=!0,this.engine.emit("serverConnected",!0),this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let r=e.action;const i=e.from_peer_id;switch(r){case"signal":this._handleSignalMsg(i,e,null,t);break;case"reject":this._handSignalRejected(i,e);break;default:this.logger.warn(`Signal websocket unknown action ${r}`)}},a.onclose=()=>{this.connected=!1,this.engine.emit("serverConnected",!1)},a.onerror=t=>{t.message&&this.engine.emit(e.EXCEPTION,Le()(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){this.logger.warn(`signaling ${e} rejected, reason ${t.reason}`);const r=this.DCMap.get(e);r&&!r.connected&&(r.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCSet.add(e),this._tryConnectToAllPeers()}_handleSignalMsg(e,t,r,i){if(!this.scheduler)return;const{logger:s}=this;if(t.data){if(this.failedDCSet.has(e))return void this._sendSignalReject(e,`peer ${e} in blocked list`,r,i,!0);this._handleSignal(e,t.data,r,i)}else{const t=this.DCMap.get(e);if(!t)return;if(this.signalerWs.backupConnected&&t&&t.signalMsgs.length>0&&"main"===i&&!t.useBackupSignal){t.useBackupSignal=!0,t.signalName="backup",s.warn(`${e} not found from main, try backup signal`);for(let r of t.signalMsgs)this.signalerWs.sendSignal(e,r,"backup");return}if(t.useBackupSignal)return;this._destroyAndDeletePeer(e),s.info(`signaling ${e} not found`);const{scheduler:n}=this;n.waitForPeer&&(n.waitingPeers--,0===n.waitingPeers&&n.notifyPeersLoaded(0)),this.requestMorePeers(),this._tryConnectToAllPeers(),r||this.notFoundDCSet.add(e)}}_handleSignal(e,t,r,i){const s=t.type,{logger:n}=this;let a=this.DCMap.get(e);if(a){if(a.connected)return void n.info("datachannel had connected, signal ignored");if("offer"===s){if(!(this.peerId>e))return void n.warn(`signal type wrong ${s}, ignored`);this._destroyAndDeletePeer(e,!1),n.warn(`signal type wrong ${s}, convert to non initiator`),a=this._createDatachannel(e,!1,r)}}else{if("answer"===s){const t=`signal type wrong ${s}`;return n.warn(t),this._sendSignalReject(e,t,r,i),void this._destroyAndDeletePeer(e,!1)}n.debug(`receive node ${e} connection request`);const t=this.scheduler.peersNum;if(t>=this.maxConns){const s=this.scheduler.getNonactivePeers();if(!(s.length>0)){const t=`peers reach limit ${this.maxConns}`;return n.warn(t),void this._sendSignalReject(e,t,r,i)}{let e=t-this.maxConns+2;for(s.length0;){const t=s.shift();t&&(n.warn(`close inactive peer ${t.remotePeerId}`),t.close(!1)),e--}}}a=this._createDatachannel(e,!1,r)}i&&(a.signalName=i),a.receiveSignal(t)}_createDatachannel(e,t,r){let i;if(t&&this.peerPool.size>0)i=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${i.signalMsgs.length}`),i.assignPeerId(this.peerId,e);else{let s=this.config.trickleICE;r||this.overloaded&&(s=!1),i=new O(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:r,trickle:s})}return this.DCMap.set(e,i),this._setupDC(i),i}_sendSignalReject(e,t,r,i,s){if(r){const i=this.DCMap.get(r);if(i&&i.sendMsgSignalReject(e,this.peerId,t,s))return}this.signalerWs.sendReject(e,t,s,i)}_requestMorePeers(e){const{logger:t}=this;t.info(`requestMorePeers after delay ${e}`);const r=this.scheduler.peersNum,i=this.peersIncrement;this.peersIncrement=0,r>=this.minConns||(0===r||i<=3&&!this.gotPeersFromTracker&&!this.overloaded?(this.failedDCSet.size>50&&(this.failedDCSet=new Set([...this.failedDCSet].slice(-50))),this.notFoundDCSet.size>20&&(this.notFoundDCSet=new Set([...this.notFoundDCSet].slice(-20))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCSet.keys(),...this.notFoundDCSet.keys()],0===r).then((e=>{t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=this._filterPeers(e.peers),this._tryConnectToAllPeers()})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0):r{const{config:n}=this,a=e.live;n.live=a,this.targetDuration=e.averagetargetduration,this.browserInfo={...s,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${r(this.currentSrc)}|${i}[${O.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsSwP2pEngine"),o.info(`engine version: ${W.version} hls-proxy version: ${this.swVersion}`),o.info(`channel ${this.channel}`),a||(n.startSN=e.startSN,n.endSN=e.endSN,o.info(`startSN ${e.startSN} endSN ${e.endSN}`));const{controller:l}=navigator.serviceWorker;if(l){if(n.httpStreamEnabled)try{const e=new ReadableStream({start(e){e.enqueue({action:t.STREAM_DETECT})}});l.postMessage(e,[e])}catch(e){}else l.postMessage({action:t.STREAM_DISABLE});n.swStreamEnabled&&l.postMessage({action:t.SW_STREAM_ENABLE})}this._init(this.channel,this.browserInfo),this.off(t.LEVEL_LOADED,this.onLevelLoaded)},this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,r)=>{this.multiBitrate=e.length>1,this.currentSrc=r,this.off(t.MANIFEST_PARSED,this.onManifestParsed)},this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{!this.rangeTested&&this.config.useHttpRange&&(this.rangeTestUrl=e,d(e).then((()=>{this.config.httpRangeSupported=!0,this.config.logger.info("http range is supported")})).catch((()=>{this.config.httpRangeSupported=!1,this.config.logger.warn("http range is not supported")})),this.rangeTested=!0),this.off(t.FRAG_LOADED,this.onFragLoaded)},this.once(t.FRAG_LOADED,this.onFragLoaded),this.swSupported&&(navigator.serviceWorker.onmessage=e=>{const{action:r,data:i}=e.data,s=e.ports[0];if(r!==t.SW_STREAM&&(this.logger&&this.logger.info(`engine onmessage action ${r}`),s.postMessage({action:r,pong:!0})),!this.p2pEnabled||!i)return s.postMessage({action:r});switch(r){case t.SW_PLAYLIST:this.handlePlaylist(i,s);break;case t.SW_GET_PLAYLIST:this.handleGetPlaylist(i,s);break;default:if(!this.config.scheduler)return s.postMessage({action:r});this.config.scheduler.notifySWMessage(r,i,s)}}),this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}watchRebuffering(e){this.offEventRebuffer=function(e,t){let r=null;const i=()=>{r||(r=setTimeout((()=>{t()}),2500))},s=()=>{null!=r&&(clearTimeout(r),r=null)};return e.addEventListener("waiting",i),e.addEventListener("playing",s),()=>{e.removeEventListener("waiting",i),e.removeEventListener("playing",s)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,r){const{config:i,logger:s}=this,{url:n,redirectedUrl:a,text:o,ver:l}=e;if(this.swVersion=l,0!==o.indexOf("#EXTM3U")||this.bypassLevels.indexOf(n)>=0)return console.warn("no EXTM3U delimiter or bypass audio track"),r.postMessage({action:t.SW_PLAYLIST});r.postMessage({action:t.SW_PLAYLIST,data:{active:!0,debug:s&&s.isDebugLevel,sharePlaylist:!!i.sharePlaylist}}),this._parsePlaylist(o,n.split("?")[0],a)}_parsePlaylist(e,r,i){const s=r;i&&(r=i);const{config:n,logger:a}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let i=0;const a=Ee.parseLevelPlaylist(e,r);this.levels.length>1?(i=this.levels.indexOf(a.url),-1===i?(this.restartP2p(),this.currentSrc=s,i=0):this.currentLevelIndex=i):(""!==this.currentSrc&&s!==this.currentSrc&&this.restartP2p(),this.currentSrc=s,this.levels=[r]),this.emit(t.LEVEL_LOADED,a),n.live&&function(e,t){if(e.size<=t)return;const r=[...e.keys()];do{e.delete(r.shift())}while(e.size>t)}(this.fragMap,200),a.fragments.forEach((e=>{e.level=i;let t=b().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const r=e.byteRange;2===r.length&&(t=`${t}|bytes=${r[0]}-${r[1]-1}`),this.fragMap.set(t,e)})),n.sharePlaylist&&n.scheduler&&!n.scheduler.isMobileNet&&n.scheduler.broadcastPlaylist(r.split("?")[0],e)}else{const i=Ee.parseMasterPlaylist(e,r);if(""!==this.currentSrc&&this.restartP2p(),i.length>0){i.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=i.map((e=>e.url));const t=i.map((e=>({id:e.attrs.AUDIO,codec:e.audioCodec})));Ee.parseMasterPlaylistMedia(e,r,"AUDIO",t).forEach((e=>{e.url&&this.bypassLevels.push(e.url)}))}this.emit(t.MANIFEST_PARSED,i,s)}}handleGetPlaylist(e,r){const{config:i,logger:s}=this;if(!s)return r.postMessage({action:t.SW_GET_PLAYLIST});const{scheduler:n}=i;if(!n)return void s.warn("scheduler not found");const{url:a}=e,o=a.split("?")[0];if(n.playlistInfo.has(o)){const e=n.getPlaylistFromPeer(o);if(e&&e.data){const{data:i,seq:n}=e;return s.info(`got playlist from peer seq ${n}`),r.postMessage({action:t.SW_GET_PLAYLIST,data:{text:i}}),void this._parsePlaylist(i,a.split("?")[0])}}return r.postMessage({action:t.SW_GET_PLAYLIST})}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let e="sw is not supported";return p||(e="https is required when using ServiceWorker",console.warn(e)),Promise.reject(e)}this.media=K(t.mediaElem),this.media||e&&e.warn("no video element found");const{serviceWorker:r}=navigator;return r.getRegistration(t.swFile).then((e=>e||r.register(t.swFile,{scope:t.swScope}).then((e=>{const t=e.installing||e.waiting;return e.active?e:new Promise(((r,i)=>{const s=()=>{"activated"===t.state?(t.removeEventListener("statechange",s),r(e)):"redundant"===t.state&&i("sw is redundant")};t.addEventListener("statechange",s)}))}))))}unregisterServiceWorker(){const{config:e}=this,t="serviceWorker is not registered";return new Promise(((r,i)=>{const{serviceWorker:s}=navigator;s||i(t),s.getRegistration(e.swFile).then((e=>{e?e.unregister().then((()=>{r()})).catch((()=>{i(t)})):i(t)}))}))}async _init(e,t){if(!this.p2pEnabled)return;const{logger:r}=this;try{await this.initSegmentManager()}catch(e){return void(r&&r.error(e))}t.live||(t.tag=this.getTagForVod());let i=new We(this,this.config.token,encodeURIComponent(e),this.config.announce||"",t);this.fetcher=i,this.config.fetcher=i;const s=setInterval((()=>{this.media?(clearInterval(s),this.watchRebuffering(this.media)):this.media=K(this.config.mediaElem)}),3e3);let n=new vt(this,this.config);n.bufferManager=this.bufMgr,n.fragMap=this.fragMap,this.tracker=new Ot(this,i,n,this.config),this.config.scheduler=this.tracker.scheduler,this.p2pEnabled&&!this.tracker.connected&&this.tracker.resumeP2P(),this.setupWindowListeners()}restartP2p(){this.logger&&this.logger.warn("restart P2P"),this.disableP2P(),this.enableP2P(),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.on(t.FRAG_LOADED,this.onFragLoaded)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this)}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.offEventRebuffer&&this.offEventRebuffer(),this.p2pEnabled&&(this.config.p2pEnabled=this.p2pEnabled=!1,this.tracker&&this.tracker instanceof Ot&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.rangeTestUrl="",this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(t.MANIFEST_PARSED),this.removeAllListeners(t.LEVEL_LOADED)}}const xt=Mt;function Ft(e,t,r="main"){const i=b().parseURL(e),s=i.path.substring(i.path.lastIndexOf(".")+1);return-1!==t.indexOf(s)||"main"!==r}function Nt(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}function Bt(e,t){let r,i,s,n,a;const o=performance.now();r=o-300,i=o-200,s=o,e.trequest=r,e.tfirst=i,e.tload=s,e.loading={first:r,start:i,end:s},n=a=t,e.loaded=n,e.total=a}class Ut extends(n()){constructor(){super(),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.timeout=0,this.withCredentials=!1,this.status=0,this.readyState=this.UNSENT,this.headers=new Map,this.responseHeaders=null,this.on("load",(e=>{this.onload&&this.onload(e)})),this.on("abort",(e=>{this.onabort&&this.onabort(e)})),this.on("error",(e=>{this.onerror&&this.onerror(e)})),this.on("loadstart",(e=>{this.onloadstart&&this.onloadstart(e)})),this.on("progress",(e=>{this.onprogress&&this.onprogress(e)})),this.on("timeout",(e=>{this.ontimeout&&this.ontimeout(e)})),this.on("loadend",(e=>{this.onloadend&&this.onloadend(e)})),this.on("readystatechange",(()=>{this.onreadystatechange&&this.onreadystatechange()}))}setRequestHeader(e,t){this.headers.set(e,t)}addEventListener(e,t){this.addListener(e,t)}removeEventListener(e,t){this.removeListener(e,t)}overrideMimeType(){}getAllResponseHeaders(){if(!this.responseHeaders)return null;let e="";return this.responseHeaders.forEach(((t,r)=>{e+=`${r}: ${t}\n`})),e}getResponseHeader(e){return this.responseHeaders?this.responseHeaders.get(e):null}open(){this.readyState=this.OPENED,this.emit("loadstart")}abort(){this.readyState=this.DONE,this.status=0}send(){}_emitEvent(e){this.emit(e,new ProgressEvent(e))}}class Gt{constructor(e){this.fetchSetup=e.fetchSetup||jt,this.xhrSetup=e.xhrSetup,this.controller=new window.AbortController,this.stats=Nt(),this.packetSize=o,this.fakeXhr=new Ut}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;e&&e.ok||(this.stats.aborted=!0,this.callbacks&&this.callbacks.onUpdate&&this.callbacks.onUpdate(void 0,!1,!0),this.controller.abort())}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const i=this.stats;i.trequest=i.loading.start=performance.now();let s=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new window.Headers(Object.assign({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal);const n="arraybuffer"===e.responseType,a=n?"byteLength":"length",o=r.onUpdate,l=r.onBodyStart;this.context=e,this.config=t,this.callbacks=r,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),s=function(e,t){e.withCredentials&&(t.credentials="include");for(let[r,i]of e.headers)t.headers.set(r,i);return t}(this.fakeXhr,s)),this.request=this.fetchSetup(e,s),clearTimeout(this.requestTimeout),this.requestTimeout=setTimeout((()=>{this.abortInternal(),this.fakeXhr._emitEvent("timeout"),this.fakeXhr._emitEvent("loadend"),r.onTimeout(i,e,this.response)}),this.fakeXhr.timeout||t.timeout);const{fakeXhr:h}=this;h.readyState=h.OPENED,h.emit("readystatechange"),h._emitEvent("loadstart"),fetch(this.request).then((t=>{if(this.response=this.loader=t,!t.ok){const{status:e,statusText:r}=t;throw o&&o(void 0,!1,!0),new Ht(r||"fetch, bad network response",e,t)}i.tfirst=i.loading.first=Math.max(performance.now(),i.loading.start),i.total=parseInt(t.headers.get("Content-Length")||"0");const{fakeXhr:r}=this;return r.readyState=r.HEADERS_RECEIVED,r.responseHeaders=t.headers,r.emit("readystatechange"),o&&"0"!==i.total?(l&&l(i.total),this.loadProgressively(t,i,e,o)):(r.emit("progress",new ProgressEvent("progress",{lengthComputable:!1})),n?t.arrayBuffer():t.text())})).then((t=>{const{response:s}=this;clearTimeout(this.requestTimeout),i.tload=i.loading.end=Math.max(performance.now(),i.loading.first),i.loaded=i.total=t[a];const n={url:s.url,data:t};r.onProgress(i,e,t,s),r.onSuccess(n,i,e,s)})).catch((t=>{if(clearTimeout(this.requestTimeout),i.aborted)return;o&&o(void 0,!1,!0);const s=t&&t.code||0,n=t?t.message:null;r.onError({code:s,text:n},e,t?t.details:null)}))}loadProgressively(e,t,r,i){const s=e.body.getReader();let n=0,o=0,l=(0,a.l)(0);const h=()=>s.read().then((({value:r,done:s})=>{const{fakeXhr:u}=this;if(u.readyState!==u.LOADING&&(u.readyState=u.LOADING,u.emit("readystatechange")),r&&(n+=r.length),s){if(l.byteLength>0)if(n<=this.packetSize){const e=(0,a.l)(n);l.copy(e,0,o*this.packetSize,l.byteLength),i(e,!0)}else{const e=v(l,o*this.packetSize);for(let t=0;t=this.packetSize){n-=this.packetSize;const e=(0,a.l)(this.packetSize);l.copy(e,0,o*this.packetSize,(o+1)*this.packetSize),o++,i(e,!1)}return h()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return h()}}function jt(e,t){return new window.Request(e.url,t)}class Ht extends Error{constructor(e,t,r){super(e),this.code=t,this.details=r}}const $t=class extends gt{constructor(e,t){super(e,t),this.isHlsjs=!0,this.waitForPeer=t.waitForPeer||!1,this.waitForPeerTimeout=t.waitForPeerTimeout,this.waitingPeers=0,this.waitingSeg={}}startWaitPeerTimer(){this.waitForPeer&&(this.waitForPeerTimer=setTimeout((()=>{this.waitForPeer&&(this.waitForPeer=!1,this.emit(t.SCH_WAIT_PEER))}),1e3*(this.waitForPeerTimeout+0)))}updatePlaySN(e){this.currPlaySN=e}load(e,t,r){this.isReceiver=!0;const{logger:i,config:s}=this;this.context=e;const{rangeStart:n,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:u,level:c}=l;this.callbacks=r,this.stats=Nt(),this.criticalSeg={sn:u,level:c,segId:h};let d=this.mBufferedDuration-s.httpLoadTime;d>this.dcDownloadTimeout&&(d=this.dcDownloadTimeout);const{forwardPeer:f,reversePeer:g}=this.targetPeers;f||g||(d-=1);let p=this.requestingMap.get(u,c);const v={rangeStart:Number(n),rangeEnd:Number(a),url:o,httpLoadTime:1e3*s.httpLoadTime-500,xhrSetup:s.xhrSetup,segId:h};p?p.setExtra(v):(p=new dt(this.coordinator,this.logger,u,c,h,this.httpRangeSupported,v),this._setupSynthesizer(p),this.requestingMap.set(u,c,p)),f&&(p.setForwardPeer(f),f.requestDataById(h,u,!0,{level:c})),g&&(p.setReversePeer(g),g.requestDataById(h,u,!0,{level:c,reverse:!0})),p.isEmpty()&&(d=0),i.info(`syn setTimeout ${d}`),p.setTimeout(1e3*d),this.targetPeers={}}waitPeerNotifier(){return new Promise((e=>{this.waitForPeer||e(),setTimeout(e,1e3*this.waitForPeerTimeout),this.once(t.SCH_WAIT_PEER,e)}))}addPeer(e){if(super.addPeer(e),this.waitForPeer){const{level:r,sn:i}=this.waitingSeg,s=e.remotePeerId;e.bitset.has(i,r)?(this.logger.info(`found initial seg ${r}-${i} from peer ${s}`),this.emit(t.SCH_WAIT_PEER)):this.waitingPeers===this.peersNum&&this.emit(t.SCH_WAIT_PEER)}}notifyPeersLoaded(e){this.logger.info(`notifyPeersLoaded ${e}`),this.waitForPeer&&(0===e?(this.waitForPeer=!1,this.emit(t.SCH_WAIT_PEER)):this.waitingPeers=e)}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler"),clearTimeout(this.waitForPeerTimer)}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,((t,r)=>{const{config:i,logger:s}=this,{segId:n,sn:a,data:o,level:l}=t,{speed:h,http:u,p2p:c}=r;u>0?this.httpTimeouts++:this.httpTimeouts>0&&this.httpTimeouts--;const d=this.criticalSeg&&this.criticalSeg.segId===n;if(i.validateSegment(n,new Uint8Array(o))){this.notifyAllPeers(a,l,n),this.bitset.has(a,l)||this.reportTraffic(u,c,h);const r=e.getFromPeerId();if(d){s.info(`receive criticalSeg seg_id ${n}`);let e=this.stats;e.tfirst=e.loading.first=Math.max(e.trequest,performance.now()),e.tload=e.loading.end=e.tfirst,e.loaded=e.total=o.byteLength,this.criticalSeg=null;const{frag:t}=this.context;t.fromPeerId=r,t.loadByP2P=!0,this.callbacks.onSuccess({data:o,url:this.context.url},e,this.context)}else this.bitset.has(a,l)||(this.bufMgr.putSeg(t),this.updateLoaded(a,l,n))}else s.error(`segment ${n} validate failed`),d&&this.callbacks.onTimeout(this.stats,this.context,null);this.requestingMap.delete(a,l),i.live&&!this.criticalSeg&&this.checkPeers()})).on(t.SYN_ERROR,((t,r)=>{const{logger:i}=this,{sn:s,level:n}=t;i.warn(`SYN_ERROR loading ${s} code ${r}`),this.criticalSeg&&this.criticalSeg.sn===s&&(this.criticalSeg=null,this.callbacks.onTimeout(this.stats,this.context,null)),r===ct&&e.hasPartialBuffer()?i.warn("syn abort with partial buffer"):(this.requestingMap.delete(s,n),this._handleSynError(r))}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:r,level:i})=>{this.loadingSN=e,this.loadingSegId=t})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:r,level:i})=>{this.requestingMap.delete(e,i),this.updateLoaded(e,i,t)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,r,i,s){this._notifySynthesizer(e,i,t,r,s),this.config.live&&!this.criticalSeg&&L()((()=>{this.checkPeers()}))}};const Wt=class extends ne{static get name(){return"HlsjsP2pEngine"}constructor(e,t={}){if(super(t),!e)throw new TypeError("hlsjs instance is null");this.hlsjs=e,this.HLSEvents=e.constructor.Events,this.config.isHlsV0="0"===e.constructor.version.split(".")[0],this.config.xhrSetup=e.config.xhrSetup,!0===this.config.httpStreamEnabled&&(e.config.streamEnabled=function(){if(window.fetch&&window.AbortController&&window.ReadableStream&&window.Request)try{return new window.ReadableStream({}),!0}catch(e){}return!1}());const{channelIdMaker:r,signalId:i,browserInfo:s}=this.setup();e.config.segmentId=this.config.segmentId,this.config.waitForPeer&&this.config.sourceUrl?(this.config.trickleICE=!0,this.config.httpRangeSupported=!0,this._startEngine(this.config.sourceUrl,this.config.live,s,r,i)):this.config.waitForPeer=!1;const n=(t,a)=>{if(!a)return;const{config:o}=this,l=a.details,h=l.live;this.config.waitForPeer?this.tracker&&this.tracker.scheduler.startWaitPeerTimer():this._startEngine(this.hlsjs.url,h,s,r,i,l),o.waitForPeer&&this.logger.info("waitForPeer mode"),e.off(this.HLSEvents.LEVEL_LOADED,n)};e.on(this.HLSEvents.LEVEL_LOADED,n);const a=(t,r)=>{const i=r.levels.length;this.multiBitrate=i>1,e.off(this.HLSEvents.MANIFEST_PARSED,a)};e.on(this.HLSEvents.MANIFEST_PARSED,a),e.on(this.HLSEvents.DESTROYING,(()=>{this.destroy()}))}_startEngine(e,t,r,i,s,n={}){const{config:a}=this;a.live=this.hlsjs.config.live=t,this.browserInfo={...r,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${i(e)}|${s}[${O.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsjsP2pEngine"),this.logger=this.hlsjs.config.logger=o,o.info(`channel ${this.channel}`),t||(a.startSN=n.startSN,a.endSN=n.endSN,o.info(`startSN ${n.startSN} endSN ${n.endSN}`)),this.eventListened=!1,this._init(this.channel,this.browserInfo)}async _init(e,r){const{logger:i,config:s}=this;if(!this.p2pEnabled)return;this.hlsjs.config.p2pEnabled=this.p2pEnabled,this.hlsjs.config.sharePlaylist=s.sharePlaylist,r.live||(r.tag=this.getTagForVod()),this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);let a=new We(this,s.token,encodeURIComponent(e),s.announce||"",r);this.fetcher=a;const o=new $t(this,s);this.tracker=new Ot(this,a,o,s);try{await this.initSegmentManager()}catch(e){return void i.error(e)}this.hlsjs.config.bufMgr=this.bufMgr,o.bufferManager=this.bufMgr,this.hlsjs.config.fLoader=function(e,r,i,s,a){return class extends(n()){constructor(t){super(),this.logger=t.logger,this.isHlsV0=s,this.bufMgr=t.bufMgr,this.streamEnabled=t.streamEnabled,this.httpLoader=this.streamEnabled?new Gt(t):new t.loader(t),this.p2pEnabled=t.p2pEnabled,this.isLive=t.live,this.scheduler=e,this.fetcher=r,this.segmentId=t.segmentId,this.blockTypes=i,this.forbidden=r.forbidden,this.stats=this.httpLoader.stats||Nt(),this.enableWorker=t.enableWorker,this.segmentBypass="function"==typeof a?a:()=>!1}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,r,i){const{logger:s,scheduler:n}=this,a=e.frag;this.isHlsV0||(a.stats=this.stats);let o=e.frag.segId;if(!o){let t;e.rangeEnd&&(t="bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),o=e.frag.segId=this.segmentId(String(a.level),a.sn,a.url,t)}if(!a.url||Ft(a.url,this.blockTypes,a.type)||this.segmentBypass(a.url,a.tagList))return s.info(`HTTP load blockType ${a.url}`),e.frag.loadByHTTP=!0,this.httpLoader.load(e,r,i);if(this.forbidden)return;this.fetcher.increMediaRequests(),r.maxRetry=2;const l=n.getBufferedDuration(),h=await this.bufMgr.getSegById(o);if(this.p2pEnabled&&h){s.info(`bufMgr found seg sn ${a.sn} segId ${o} level ${a.level}`);let t=g(h.data).buffer,r={url:e.url,data:t};return Bt(this.stats,h.size),a.loaded=h.size,a.loadByP2P=!0,e.frag.fromPeerId=h.fromPeerId,void L()((()=>{!this.isHlsV0&&i.onProgress&&i.onProgress(this.stats,e,r.data),i.onSuccess(r,this.stats,e)}))}if(this.p2pEnabled&&n.hasAndSetTargetPeer(a.sn,a.level,a.segId,l))this.loadFragByP2p(e,r,i,o);else if(n.waitForPeer&&(s.warn("waitPeerNotifier start"),n.waitingSeg={sn:a.sn,level:a.level},await n.waitPeerNotifier(),s.warn("waitPeerNotifier end"),this.p2pEnabled&&n.hasAndSetTargetPeer(a.sn,a.level,a.segId,l)))this.loadFragByP2p(e,r,i,o);else if(s.info(`fragLoader load ${o} at ${a.sn} level ${a.level} buffered ${1e3*l}`),this.isLive&&n.hasIdlePeers&&l>7&&n.shouldWaitForNextSeg()){let h=l-7;h>4.5&&(h=4.5);const u=s=>{s===o&&(n.off(t.SCH_DCHAVE,u),clearTimeout(this.waitTimer),n.hasAndSetTargetPeer(a.sn,a.level,a.segId,l)?this.loadFragByP2p(e,r,i,o):this.loadFragByHttp(e,r,i,o))};s.info(`wait peer have for ${h}s`),n.on(t.SCH_DCHAVE,u),this.waitTimer=setTimeout((()=>{this.loadFragByHttp(e,r,i,o),n.off(t.SCH_DCHAVE,u)}),1e3*h)}else{const t=n.requestingMap.get(a.sn,a.level);n.httpRangeSupported&&t&&t.segId===a.segId&&t.hasPartialBuffer()?(s.warn(`syn has partial buffer for ${a.segId}`),this.loadFragByP2p(e,r,i,o)):this.loadFragByHttp(e,r,i,o)}}loadFragByHttp(e,t,r,i){const{logger:s,scheduler:n}=this,{segmentBuilderMap:a}=n;n.isReceiver=!1;const o=e.frag,{sn:l,level:h}=o;if(this.streamEnabled){let e;n.isMobileNet||n.notifyAllPeers(l,h,i,Ve),r.onUpdate=(t,r,i)=>{i?a.delete(l,h):e&&e.receiveBytes(t,r)},r.onBodyStart=t=>{!e&&t>0&&(e=new pt(l,h,i,t),a.has(l,h)||a.set(l,h,e))}}const u=r.onSuccess;r.onSuccess=async(e,t,r)=>{if(!await this.bufMgr.hasSegOfId(i)){const t=g(e.data).buffer,r=new P(l,i,t,this.fetcher.peerId,h);this.bufMgr.putSeg(r)}a.delete(l,h),this.fetcher.reportFlow(t.total);let o=t.tload-t.trequest;s.info(`HTTP loaded ${i} time ${o}`),n.notifyAllPeers(l,h,i),u(e,t,r)};const c=r.onProgress;r.onProgress=(e,t,r)=>{o.loaded=e.total,c(e,t,r&&this.enableWorker?g(r).buffer:r)},e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,r)}loadFragByP2p(e,t,r,i){const{logger:s}=this,n=e.frag;this.scheduler.load(e,t,r);const a=r.onSuccess,o=r.onTimeout;r.onTimeout=(e,l)=>{s.warn(`P2P timeout switched to HTTP load ${n.relurl} at ${n.sn}`),r.onSuccess=a,this.loadFragByHttp(l,t,r,i),r.onTimeout=o},r.onSuccess=async(e,t,o)=>{if(!await this.bufMgr.hasSegOfId(i)){const t=g(e.data).buffer,r=new P(n.sn,i,t,n.fromPeerId||this.fetcher.peerId,n.level);this.bufMgr.putSeg(r)}n.loadByP2P||this.fetcher.reportFlow(t.total),n.loaded=t.loaded,s.info(`${n.loadByP2P?"P2P":"HTTP"} loaded segment id ${i}`),!this.isHlsV0&&r.onProgress&&r.onProgress(t,o,e.data),a(e,t,o)}}}}(o,a,s.p2pBlackList,s.isHlsV0,s.segmentBypass),s.sharePlaylist&&(this.hlsjs.config.pLoader=function(e){return class extends(n()){constructor(t){super(),this.logger=t.logger,this.isHlsV0=t.isHlsV0,this.xhrLoader=new t.loader(t),this.p2pEnabled=t.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||Nt()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}load(e,t,r){const{logger:i}=this,{url:s}=e,n=s.split("?")[0],a=r.onSuccess;if(r.onSuccess=(e,t,r)=>{this.scheduler&&this.scheduler.broadcastPlaylist(n,e.data),a(e,t,r)},this.scheduler&&this.scheduler.playlistInfo.has(n)){const t=this.scheduler.getPlaylistFromPeer(n);if(t&&t.data){const{data:n,seq:a}=t;i.info(`got playlist from peer seq ${a}`),Bt(this.stats,n.length);let o={url:s,data:n};return void L()((()=>{r.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,r)}}}(o)),this.trackerTried=!1,this.eventListened||(this.hlsjs.on(this.HLSEvents.FRAG_LOADING,this._onFragLoading.bind(this)),this.hlsjs.on(this.HLSEvents.FRAG_LOADED,this._onFragLoaded.bind(this)),this.hlsjs.on(this.HLSEvents.FRAG_CHANGED,this._onFragChanged.bind(this)),this.hlsjs.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)),this.eventListened=!0),this.setupWindowListeners(),this.trackerTried||this.tracker.connected||!s.p2pEnabled||(this.tracker.resumeP2P(),this.trackerTried=!0)}_onFragLoading(e,r){const i=r.frag;let{sn:s,level:n,segId:a}=i;if(!Ft(i.url,this.config.p2pBlackList,i.type)){if(this.logger.debug("loading frag "+s),this.bufMgr&&(this.bufMgr.loadingSN=s),!a){let e;i._byteRange&&(e="bytes="+i._byteRange[0]+"-"+i._byteRange[1]);let t=i.url;a=i.segId=this.config.segmentId(String(n),i.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:s,segId:a,byHttp:i.loadByHTTP,level:n})}}_onFragLoaded(e,r){const{frag:i}=r,{sn:s,segId:n,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:u,url:c}=i,{config:f,logger:g}=this;Ft(i.url,f.p2pBlackList,i.type)||(this.emit(t.FRAG_LOADED,{url:c,sn:s,level:l,segId:n,loaded:a,duration:o,byP2p:!!u,fromPeerId:h}),!this.rangeTested&&f.useHttpRange&&(d(i.url,void 0,f.xhrSetup).then((()=>{f.httpRangeSupported=!0,g.info("http range is supported")})).catch((()=>{f.httpRangeSupported=!1,g.warn("http range is not supported")})),this.rangeTested=!0))}_onFragChanged(e,r){const{frag:i}=r;if(!Ft(i.url,this.config.p2pBlackList,i.type)){this.logger.debug("frag changed: "+i.sn);const{sn:e,duration:r}=i;this.emit(t.FRAG_CHANGED,{sn:e,duration:r})}}_onHlsError(e,r){if(!r)return;const{logger:i}=this,s=`${r.type} details ${r.details} reason ${r.reason}`;r.fatal?i.error(s):i.warn(s);const n=this.hlsjs.constructor.ErrorDetails;switch(r.details){case n.BUFFER_STALLED_ERROR:this.fetcher&&this.fetcher.increRebuffers();break;case n.INTERNAL_EXCEPTION:this.fetcher&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=`${r.err.message} event ${r.event} ua ${navigator.userAgent}`),i.error(`INTERNAL_EXCEPTION event ${r.event} err ${r.err.message}`),this.emit(t.EXCEPTION,Le()(r.err,"HLSJS_EXPT"))}}get currentLevel(){const{currentLevel:e}=this.hlsjs;return e>=0?e:0}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.hlsjs.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}};function Kt(){const e=function(){if("undefined"!=typeof window)return window.MediaSource||window.WebKitMediaSource}(),t=window.SourceBuffer||window.WebKitSourceBuffer,r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!i}class qt{static get Events(){return t}static get TrackerZone(){return W.TrackerZone}static isSupported(){return W.isSupported()&&(Kt()||xt.isServiceWorkerSupported())}static isServiceWorkerSupported(){return xt.isServiceWorkerSupported()}static isMSESupported(){return Kt()}static getBrowser(){return C().getBrowser()}static get ServiceWorkerEngine(){return xt}static get HlsjsEngine(){return Wt}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance,"1"!==h("_ios")&&!e.proxyOnly&&t&&Kt()?this._realEngine=new Wt(t,e):this._realEngine=new xt(e)}get realEngine(){return this._realEngine}get engineName(){return this._realEngine.constructor.name}once(e,t){return this._realEngine.once(e,t)}on(e,t){return this._realEngine.on(e,t)}off(e,t){return this._realEngine.off(e,t)}removeListener(e,t){return this._realEngine.removeListener(e,t)}removeAllListeners(e){return this._realEngine.removeAllListeners(e)}set p2pEnabled(e){this._realEngine.p2pEnabled=e}get p2pEnabled(){return this._realEngine.p2pEnabled}enableP2P(){this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}registerServiceWorker(){return"function"==typeof this._realEngine.registerServiceWorker?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}unregisterServiceWorker(){return"function"==typeof this._realEngine.unregisterServiceWorker?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return W.version}}qt.version=W.version,qt.protocolVersion=O.VERSION,window&&(window.P2PEngineHls=qt);const Vt=qt;var zt;zt=r(305);const Yt={maxBufferLength:12},Xt={maxBufferLength:40};class Qt extends zt{static get P2PEvents(){return Vt.Events}static get P2pEngine(){return Vt}constructor(e={}){let t=e.p2pConfig||{};const r=!1===t.live?Xt:Yt;let i=JSON.parse(JSON.stringify(r));i.liveSyncDurationCount=10,i.manifestLoadingMaxRetry=3,i.manifestLoadingRetryDelay=700,i.levelLoadingRetryDelay=700,i.maxBufferSize=0;for(let t in e)"p2pConfig"!==t&&(i[t]=e[t]);super(i),this._restartEvent=()=>{this.restartP2P()},Vt.isSupported()&&(this._p2pEngine=new Vt({...t,hlsjsInstance:this}),this._p2pEngine.on(Vt.Events.RESTART_P2P,this._restartEvent)),this.on(zt.Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(Vt.Events.RESTART_P2P,this._restartEvent),this._p2pEngine.hlsjs=null,this._p2pEngine=null)}))}get p2pEngine(){return this._p2pEngine}enableP2P(){this._p2pEngine&&(this._p2pEngine=this._p2pEngine.enableP2P())}disableP2P(){this._p2pEngine&&this._p2pEngine.disableP2P()}restartP2P(){this._p2pEngine&&(this._p2pEngine.disableP2P(),setTimeout((()=>{this.enableP2P()}),2e3),this._p2pEngine.removeListener(Vt.Events.RESTART_P2P,this._restartEvent))}}Qt.engineVersion=Vt.version,Qt.protocolVersion=Vt.protocolVersion,Qt.WEBRTC_SUPPORT=Vt.isSupported();const Jt=Qt})(),i=i.default})()));