PageSourceSearch

https://www.1x.tech/_next/static/chunks/3ac42a33.7dd0209800a05e13.js

js 1x.tech collected 2026-10-02 03:14:31 UTC 525,485 bytes, 1 lines download raw bytes

1try{!function(){var t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},e=(new t.Error).stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="90e99515-b978-4ba0-ad7e-a19b3ea6112a",t._sentryDebugIdIdentifier="sentry-dbid-90e99515-b978-4ba0-ad7e-a19b3ea6112a")}()}catch(t){}"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[6184],{56429:function(t,e,i){let r;i.d(e,{ZP:function(){return a7}});let s=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},a=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=n},n=Number.MAX_SAFE_INTEGER||9007199254740991,l=((v={}).NETWORK_ERROR="networkError",v.MEDIA_ERROR="mediaError",v.KEY_SYSTEM_ERROR="keySystemError",v.MUX_ERROR="muxError",v.OTHER_ERROR="otherError",v),o=((T={}).KEY_SYSTEM_NO_KEYS="keySystemNoKeys",T.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",T.KEY_SYSTEM_NO_SESSION="keySystemNoSession",T.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",T.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",T.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",T.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",T.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",T.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",T.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",T.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",T.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",T.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",T.MANIFEST_LOAD_ERROR="manifestLoadError",T.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",T.MANIFEST_PARSING_ERROR="manifestParsingError",T.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",T.LEVEL_EMPTY_ERROR="levelEmptyError",T.LEVEL_LOAD_ERROR="levelLoadError",T.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",T.LEVEL_PARSING_ERROR="levelParsingError",T.LEVEL_SWITCH_ERROR="levelSwitchError",T.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",T.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",T.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",T.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",T.FRAG_LOAD_ERROR="fragLoadError",T.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",T.FRAG_DECRYPT_ERROR="fragDecryptError",T.FRAG_PARSING_ERROR="fragParsingError",T.FRAG_GAP="fragGap",T.REMUX_ALLOC_ERROR="remuxAllocError",T.KEY_LOAD_ERROR="keyLoadError",T.KEY_LOAD_TIMEOUT="keyLoadTimeOut",T.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",T.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",T.BUFFER_APPEND_ERROR="bufferAppendError",T.BUFFER_APPENDING_ERROR="bufferAppendingError",T.BUFFER_STALLED_ERROR="bufferStalledError",T.BUFFER_FULL_ERROR="bufferFullError",T.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",T.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",T.ASSET_LIST_LOAD_ERROR="assetListLoadError",T.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",T.ASSET_LIST_PARSING_ERROR="assetListParsingError",T.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",T.INTERNAL_EXCEPTION="internalException",T.INTERNAL_ABORTED="aborted",T.ATTACH_MEDIA_ERROR="attachMediaError",T.UNKNOWN="unknown",T),h=((S={}).MEDIA_ATTACHING="hlsMediaAttaching",S.MEDIA_ATTACHED="hlsMediaAttached",S.MEDIA_DETACHING="hlsMediaDetaching",S.MEDIA_DETACHED="hlsMediaDetached",S.MEDIA_ENDED="hlsMediaEnded",S.STALL_RESOLVED="hlsStallResolved",S.BUFFER_RESET="hlsBufferReset",S.BUFFER_CODECS="hlsBufferCodecs",S.BUFFER_CREATED="hlsBufferCreated",S.BUFFER_APPENDING="hlsBufferAppending",S.BUFFER_APPENDED="hlsBufferAppended",S.BUFFER_EOS="hlsBufferEos",S.BUFFERED_TO_END="hlsBufferedToEnd",S.BUFFER_FLUSHING="hlsBufferFlushing",S.BUFFER_FLUSHED="hlsBufferFlushed",S.MANIFEST_LOADING="hlsManifestLoading",S.MANIFEST_LOADED="hlsManifestLoaded",S.MANIFEST_PARSED="hlsManifestParsed",S.LEVEL_SWITCHING="hlsLevelSwitching",S.LEVEL_SWITCHED="hlsLevelSwitched",S.LEVEL_LOADING="hlsLevelLoading",S.LEVEL_LOADED="hlsLevelLoaded",S.LEVEL_UPDATED="hlsLevelUpdated",S.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",S.LEVELS_UPDATED="hlsLevelsUpdated",S.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",S.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",S.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",S.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",S.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",S.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",S.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUp
1dated",S.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",S.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",S.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",S.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",S.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",S.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",S.CUES_PARSED="hlsCuesParsed",S.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",S.INIT_PTS_FOUND="hlsInitPtsFound",S.FRAG_LOADING="hlsFragLoading",S.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",S.FRAG_LOADED="hlsFragLoaded",S.FRAG_DECRYPTED="hlsFragDecrypted",S.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",S.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",S.FRAG_PARSING_METADATA="hlsFragParsingMetadata",S.FRAG_PARSED="hlsFragParsed",S.FRAG_BUFFERED="hlsFragBuffered",S.FRAG_CHANGED="hlsFragChanged",S.FPS_DROP="hlsFpsDrop",S.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",S.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",S.ERROR="hlsError",S.DESTROYING="hlsDestroying",S.KEY_LOADING="hlsKeyLoading",S.KEY_LOADED="hlsKeyLoaded",S.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",S.BACK_BUFFER_REACHED="hlsBackBufferReached",S.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",S.ASSET_LIST_LOADING="hlsAssetListLoading",S.ASSET_LIST_LOADED="hlsAssetListLoaded",S.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",S.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",S.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",S.INTERSTITIAL_STARTED="hlsInterstitialStarted",S.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",S.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",S.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",S.INTERSTITIAL_ENDED="hlsInterstitialEnded",S.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",S.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",S.EVENT_CUE_ENTER="hlsEventCueEnter",S);var d,c,u,f,g,m,p,E,y,v,T,S,A,L,I={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},R={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class b{sample(t,e){let i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}}class D{update(t,e){let{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==t&&(this.slow_=new b(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.fast_=new b(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new b(t,s.getEstimate(),s.getTotalWeight()))}sample(t,e){let i=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(t){this.ttfb_.sample(Math.sqrt(2)*Math.exp(-Math.pow(t/1e3,2)/2),Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}constructor(t,e,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_
1=new b(t),this.fast_=new b(e),this.defaultTTFB_=r,this.ttfb_=new b(t)}}function k(){return(k=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)({}).hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t}).apply(null,arguments)}function _(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,r)}return i}function P(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?_(Object(i),!0).forEach(function(e){var r,s;r=e,s=i[e],(r=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e);if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(r))in t?Object.defineProperty(t,r,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[r]=s}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):_(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}class C{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i="[".concat(t,"]:");this.trace=O,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}let O=function(){},w={trace:O,debug:O,log:O,warn:O,info:O,error:O};function M(){return k({},w)}function x(t,e,i){return e[t]?e[t].bind(e):function(t,e){let i=self.console[t];return i?i.bind(self.console,"".concat(e?"["+e+"] ":"","[").concat(t,"] >")):O}(t,i)}let F=M();function N(){let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];if("undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function U(t,e){let i=Object.keys(t),r=Object.keys(e),s=i.length,a=r.length;return!s||!a||s===a&&!i.some(t=>-1===r.indexOf(t))}function B(t){let e,i,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if("undefined"!=typeof TextDecoder){let e=new TextDecoder("utf-8").decode(t);if(r){let t=e.indexOf("\x00");return -1!==t?e.substring(0,t):e}return e.replace(/\0/g,"")}let s=t.length,a="",n=0;for(;n<s&&(0!==(e=t[n++])||!r);)if(0!==e&&3!==e)switch(e>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(e);break;case 12:case 13:a+=String.fromCharCode((31&e)<<6|63&t[n++]);break;case 14:a+=String.fromCharCode((15&e)<<12|(63&t[n++])<<6|(63&t[n++])<<0)}return a}function G(t){let e="";for(let i=0;i<t.length;i++){let r=t[i].toString(16);r.length<2&&(r="0"+r),e+=r}return e}function K(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var V={exports:{}},H=(A||(A=1,d=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,c=/^(?=([^\/?#]*))\1([^]*)$/,u=/(?:\/|^)\.(?=\/)/g,f=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,g={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var r=g.parseURL(t);if(!r)throw Error("Error trying to parse base URL.");return r.path=g.normalizePath(r.path),g.buildURLFromParts(r)}var s=g.parseURL(e);if(!s)throw Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=g.normalizePath(s.path),g.buildURLFromParts(s)):e;var a=g.parseURL(t);if(!a)throw Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var n=c.exec(a.path);a.netLoc=n[1],a.path=n[2]}a.netLoc&&!a.path&&(a.path="/");var l={scheme:a.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(l.netLoc=a.netLoc,"/"!==s.path[0])){if(s.path){var o=a.path,h=o.substring(0,o.lastIndexOf("/")+1)+s.path;l.path=g.normalizePath(h)}else l.path=a.path,s.params||(l.params=a.params,s.query||(l.query=a.query))}return null===l.path&&(l.path=i.alwaysNormalize?g.normalizePath(s.path):s.path),g.buildURLFromParts(l)},parseURL:function(t){var e=d.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(u,"");t.length!==(t=t.replace(f,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}}
1,V.exports=g),V.exports);class Y{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var W={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class j{setByteRange(t,e){let i;let r=t.split("@",2);i=1===r.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[W.AUDIO]:null,[W.VIDEO]:null,[W.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new Y),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=H.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){let{elementaryStreams:t}=this;t[W.AUDIO]=null,t[W.VIDEO]=null,t[W.AUDIOVIDEO]=null}constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){let i=function t(e,i){let r=Object.getPrototypeOf(e);if(r)return Object.getOwnPropertyDescriptor(r,i)||t(r,i)}(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}}function q(t){return"initSegment"!==t.sn}class X extends j{get byteLength(){if(this.hasStats){let t=this.stats.total;if(t)return t}if(this.byteRange.length){let t=this.byteRange[0],e=this.byteRange[1];if(s(t)&&s(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;let{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(!(null!=(t=this._decryptdata)&&t.keyId)){let t=Object.keys(e);if(1===t.length){let i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;let t=s(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t,e;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){let t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!s(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return q(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){let e=this.levelkeys;if(e){var i;let r=e[t];r&&!(null!=(i=this._decryptdata)&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,r,s){let a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],{elementaryStreams:n}=this,l=n[t];if(!l){n[t]={startPTS:e,endPTS:i,startDTS:r,endDTS:s,partial:a};return}l.startPTS=Math.min(l.startPTS,e),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,s)}constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}}class Q extends j{get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}constructor(t,e,i,r,s){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=r;let a=t.enumeratedString("BYTERANGE");a&&this.setByteRange(a,s),s&&(this.fragOffset=s.fragOffset+s.duration)}}let z=[].push,$={video:1,audio:2,id3:3,text:4};function Z(t){return String.fromCharCode.apply(null,t)}function J(t,e){let i=t[e]<<8|t[e+1];return i<0?65536+i:i}function tt(t,e){let i=ti(t,e);return i<0?4294967296+i:i}function te(t,e){let i=tt(t,e);return i*=4294967296,i+=tt(t,e+4)}function ti(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function tr(t,e){let i=[];if(!e.length)return i;let r=t.byteLength;for(let s=0;s<r;){let a=tt(t,s),n=Z(t.subarray(s+4,s+8)),l=a>1?s+a:r;if(n===e[0]){if(1===e.length)i.push(t.subarray(s+8,l));else{let r=tr(t.subarray(s+8,l),e.slice(1));r.length&&z.apply(i,r)}}s=l}return i}function ts(t){let e=[],i=tr(t,["moov","trak"]);for(let t=0;t<i.length;t++){let r=i[t],s=tr(r,["tkhd"])[0];if(s){let t=s[0],i=tt(s,0===t?12:20),a=tr(r,["mdia","mdhd"])[0];if(a){t=a[0];let s=tt(a,0===t?12:20),n=tr(r,["mdia","hdlr"])[0];if(n){let t=Z(n.subarray(8,12)),a={soun:W.AUDIO,vide:W.VIDEO}[t],l=function(t){let e;let i=t.subarray(8),r=i.subarray(86),s=Z(i.subarray(4,8)),a=s,n="enca"===s||"encv"===s;if(n){let t=tr(i,[s])[0].subarray("enca"===s?28:78);
1tr(t,["sinf"]).forEach(t=>{let e=tr(t,["schm"])[0];if(e){let i=Z(e.subarray(4,8));if("cbcs"===i||"cenc"===i){let e=tr(t,["frma"])[0];e&&(a=Z(e))}}})}let l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{let t=tr(r,["avcC"])[0];t&&t.length>3&&(a+="."+tl(t[1])+tl(t[2])+tl(t[3]),e=ta("avc1"===l?"dva1":"dvav",r));break}case"mp4a":{let t=tr(i,[s])[0],e=tr(t.subarray(28),["esds"])[0];if(e&&e.length>7){let t=4;if(3!==e[t++])break;t=tn(e,t)+2;let i=e[t++];if(128&i&&(t+=2),64&i&&(t+=e[t++]),4!==e[t++])break;t=tn(e,t);let r=e[t++];if(64===r)a+="."+tl(r);else break;if(t+=12,5!==e[t++])break;t=tn(e,t);let s=e[t++],n=(248&s)>>3;31===n&&(n+=1+((7&s)<<3)+((224&e[t])>>5)),a+="."+n}break}case"hvc1":case"hev1":{let t=tr(r,["hvcC"])[0];if(t&&t.length>12){let e=t[1],i=["","A","B","C"][e>>6],r=tt(t,2),s=t[12],n=t.subarray(6,12);a+="."+i+(31&e)+"."+(function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0})(r).toString(16).toUpperCase()+"."+((32&e)>>5?"H":"L")+s;let l="";for(let t=n.length;t--;){let e=n[t];(e||l)&&(l="."+e.toString(16).toUpperCase()+l)}a+=l}e=ta("hev1"==l?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=ta(a,r)||a;break;case"vp09":{let t=tr(r,["vpcC"])[0];if(t&&t.length>6){let e=t[4],i=t[5],r=t[6]>>4&15;a+="."+to(e)+"."+to(i)+"."+to(r)}break}case"av01":{let t=tr(r,["av1C"])[0];if(t&&t.length>2){let i=t[1]>>>5,s=31&t[1],n=t[2]>>>7?"H":"M",l=(64&t[2])>>6,o=(32&t[2])>>5,h=(16&t[2])>>4,d=(8&t[2])>>3,c=(4&t[2])>>2,u=3&t[2];a+="."+i+"."+to(s)+n+"."+to(2===i&&l?o?12:10:l?10:8)+"."+h+"."+d+c+u+"."+to(1)+"."+to(1)+"."+to(1)+".0",e=ta("dav1",r)}}}return{codec:a,encrypted:n,supplemental:e}}(tr(r,["mdia","minf","stbl","stsd"])[0]);a?(e[i]={timescale:s,type:a,stsd:l},e[a]=P({timescale:s,id:i},l)):e[i]={timescale:s,type:t,stsd:l}}}}}return tr(t,["moov","mvex","trex"]).forEach(t=>{let i=e[tt(t,4)];i&&(i.default={duration:tt(t,12),flags:tt(t,20)})}),e}function ta(t,e){let i=tr(e,["dvvC"]),r=i.length?i[0]:tr(e,["dvcC"])[0];if(r){let e=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return t+"."+to(e)+"."+to(i)}}function tn(t,e){let i=e+5;for(;128&t[e++]&&e<i;);return e}function tl(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function to(t){return(t<10?"0":"")+t}function th(t,e){tr(t,["moov","trak"]).forEach(t=>{let i=tr(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;let r=i.subarray(8),s=tr(r,["enca"]),a=s.length>0;a||(s=tr(r,["encv"])),s.forEach(t=>{tr(a?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{let i=td(t);i&&e(i,a)})})})}function td(t){let e=tr(t,["schm"])[0];if(e){let i=Z(e.subarray(4,8));if("cbcs"===i||"cenc"===i){let e=tr(t,["schi","tenc"])[0];if(e)return e}}}function tc(t,e){let i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function tu(t,e){let i=[],r=e.samples,s=e.timescale,a=e.id,n=!1;
1return tr(r,["moof"]).map(l=>{let o=l.byteOffset-8;tr(l,["traf"]).map(l=>{let h=tr(l,["tfdt"]).map(t=>{let e=t[0],i=tt(t,4);return 1===e&&(i*=4294967296,i+=tt(t,8)),i/s})[0];return void 0!==h&&(t=h),tr(l,["tfhd"]).map(h=>{let d=tt(h,4),c=16777215&tt(h,0),u=0,f=0,g=8;d===a&&((1&c)!=0&&(g+=8),(2&c)!=0&&(g+=4),(8&c)!=0&&(u=tt(h,g),g+=4),(16&c)!=0&&(f=tt(h,g),g+=4),(32&c)!=0&&(g+=4),"video"===e.type&&(n=tf(e.codec)),tr(l,["trun"]).map(a=>{let l=a[0],h=16777215&tt(a,0),d=0,c=(256&h)!=0,g=0,m=(512&h)!=0,p=0,E=(1024&h)!=0,y=(2048&h)!=0,v=0,T=tt(a,4),S=8;(1&h)!=0&&(d=tt(a,S),S+=4),(4&h)!=0&&(S+=4);let A=d+o;for(let o=0;o<T;o++){if(c?(g=tt(a,S),S+=4):g=u,m?(p=tt(a,S),S+=4):p=f,E&&(S+=4),y&&(v=0===l?tt(a,S):ti(a,S),S+=4),e.type===W.VIDEO){let e=0;for(;e<p;){let a=tt(r,A);A+=4,function(t,e){if(!t)return 6==(31&e);{let t=e>>1&63;return 39===t||40===t}}(n,r[A])&&tg(r.subarray(A,A+a),n?2:1,t+v/s,i),A+=a,e+=a+4}}t+=g/s}}))})})}),i}function tf(t){if(!t)return!1;let e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function tg(t,e,i,r){let s;let a=tm(t);s=0+e;let n=0,l=0,o=0;for(;s<a.length;){n=0;do{if(s>=a.length)break;n+=o=a[s++]}while(255===o);l=0;do{if(s>=a.length)break;l+=o=a[s++]}while(255===o);let t=a.length-s,e=s;if(l<t)s+=l;else if(l>t){F.error("Malformed SEI payload. ".concat(l," is too small, only ").concat(t," bytes left to parse."));break}if(4===n){if(181===a[e++]){let t=J(a,e);if(e+=2,49===t){let t=tt(a,e);if(e+=4,1195456820===t){let t=a[e++];if(3===t){let s=a[e++],l=31&s,o=64&s,h=o?2+3*l:0,d=new Uint8Array(h);if(o){d[0]=s;for(let t=1;t<h;t++)d[t]=a[e++]}r.push({type:t,payloadType:n,pts:i,bytes:d})}}}}}else if(5===n&&l>16){let t=[];for(let i=0;i<16;i++){let r=a[e++].toString(16);t.push(1==r.length?"0"+r:r),(3===i||5===i||7===i||9===i)&&t.push("-")}let s=l-16,o=new Uint8Array(s);for(let t=0;t<s;t++)o[t]=a[e++];r.push({payloadType:n,pts:i,uuid:t.join(""),userData:B(o),userDataBytes:o})}}}function tm(t){let e=t.byteLength,i=[],r=1;for(;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return t;let s=e-i.length,a=new Uint8Array(s),n=0;for(r=0;r<s;n++,r++)n===i[0]&&(n++,i.shift()),a[r]=t[n];return a}let tp=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),tE={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ty(t,e){let i=tE[e];return!!i&&!!i[t.slice(0,4)]}function tv(t,e){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2];return!t.split(",").some(t=>!tT(t,e,i))}function tT(t,e){var i;let r=!(arguments.length>2)||void 0===arguments[2]||arguments[2],s=N(r);return null!=(i=null==s?void 0:s.isTypeSupported(tS(t,e)))&&i}function tS(t,e){return"".concat(e,"/mp4;codecs=").concat(t)}function tA(t){if(t){let e=t.substring(0,4);return tE.video[e]}return 2}function tL(t){let e=tp();return t.split(",").reduce((t,i)=>{let r=e&&tf(i)?9:tE.video[i];return r?(2*r+t)/(t?3:2):(tE.audio[i]+t)/(t?2:1)},0)}let tI={},tR=/flac|opus|mp4a\.40\.34/i;function tb(t){let e=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return t.replace(tR,t=>(function(t){let e=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(tI[t])return tI[t];let i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let s=0;s<i.length;s++){var r;if(tT(i[s],"audio",e))return tI[t]=i[s],i[s];if("mp3"===i[s]&&null!=(r=N(e))&&r.isTypeSupported("audio/mpeg"))return""}return t})(t.toLowerCase(),e))}function tD(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(tk(t,"audio")||tk(t,"video")))return t;if(e){let i=e.split(",");if(i.length>1){if(t){for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e]}return i[0]}}return e||t}function tk(t,e){return ty(t,e)&&tT(t,e)}
1function t_(t){let e=N(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function tP(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}let tC={supported:!1,smooth:!1,powerEfficient:!1},tO={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function tw(t,e){return{supported:!1,configurations:e,decodingInfoResults:[tC],error:t}}function tM(t,e,i){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},s=t.videoCodec;if(!s&&!t.audioCodec||!i)return Promise.resolve(tO);let a=[],n=function(t){var e;let i=null==(e=t.videoCodec)?void 0:e.split(","),r=tx(t),s=t.width||640,a=t.height||480,n=t.frameRate||30,l=t.videoRange.toLowerCase();return i?i.map(t=>{let e={contentType:tS(function(t){if(t.startsWith("av01.")){let e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}(t),"video"),width:s,height:a,bitrate:r,framerate:n};return"sdr"!==l&&(e.transferFunction=l),e}):[]}(t),l=n.length,o=function(t,e,i){var r;let s=null==(r=t.audioCodec)?void 0:r.split(","),a=tx(t);return s&&t.audioGroups?t.audioGroups.reduce((t,r)=>{var n;let l=r?null==(n=e.groups[r])?void 0:n.tracks:null;return l?l.reduce((t,e)=>{if(e.groupId===r){let r=parseFloat(e.channels||"");s.forEach(e=>{let s={contentType:tS(e,"audio"),bitrate:i?function(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}(e,a):a};r&&(s.channels=""+r),t.push(s)})}return t},t):t},[]):[]}(t,e,l>0),h=o.length;for(let t=l||1*h||1;t--;){let e={type:"media-source"};if(l&&(e.video=n[t%l]),h){e.audio=o[t%h];let i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}a.push(e)}if(s){let t=navigator.userAgent;if(s.split(",").some(t=>tf(t))&&tp())return Promise.resolve(tw(Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (".concat(t,")")),a))}return Promise.all(a.map(t=>{let e=function(t){let e="",{audio:i,video:r}=t;if(r){let t=tP(r.contentType);e+="".concat(t,"_r").concat(r.height,"x").concat(r.width,"f").concat(Math.ceil(r.framerate)).concat(r.transferFunction||"sd","_").concat(Math.ceil(r.bitrate/1e5))}if(i){let t=tP(i.contentType);e+="".concat(r?"_":"").concat(t,"_c").concat(i.channels)}return e}(t);return r[e]||(r[e]=i.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:a,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:a,decodingInfoResults:[],error:t}))}function tx(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}let tF=["NONE","TYPE-0","TYPE-1",null],tN=["SDR","PQ","HLG"];var tU={No:"",Yes:"YES",v2:"v2"};function tB(t){let{canSkipUntil:e,canSkipDateRanges:i,age:r}=t;return e&&r<e/2?i?tU.v2:tU.Yes:tU.No}class tG{addDirectives(t){let e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}}class tK{get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return tV(this._audioGroups,t)}hasSubtitleGroup(t){return tV(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e){if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;let i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=",".concat(i.substring(0,4)))}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}}function tV(t,e){return!!e&&!!t&&-1!==t.indexOf(e)}let tH=t=>{let e=new WeakSet;return(i,r)=>{if(t&&(r=t(i,r)),"object"==typeof r&&null!==r){if(e.has(r))return;e.add(r)}return r}},tY=(t,e)=>JSON.stringify(t,tH(e));function tW(t,e){F.log('[abr] start candidates with "'.concat(t,'" ignored because ').
1concat(e))}function tj(t){return t.reduce((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);let r=e.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function tq(t){if(!t)return t;let{lang:e,assocLang:i,characteristics:r,channels:s,audioCodec:a}=t;return{lang:e,assocLang:i,characteristics:r,channels:s,audioCodec:a}}function tX(t,e,i){if("attrs"in t){let i=e.indexOf(t);if(-1!==i)return i}for(let r=0;r<e.length;r++)if(tQ(t,e[r],i))return r;return -1}function tQ(t,e,i){let{groupId:r,name:s,lang:a,assocLang:n,default:l}=t,o=t.forced;return(void 0===r||e.groupId===r)&&(void 0===s||e.name===s)&&(void 0===a||function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"--";return t.length===e.length?t===e:t.startsWith(e)||e.startsWith(t)}(a,e.lang))&&(void 0===a||e.assocLang===n)&&(void 0===l||e.default===l)&&(void 0===o||e.forced===o)&&(!("characteristics"in t)||function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=t.split(","),r=e.split(",");return i.length===r.length&&!i.some(t=>-1===r.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function tz(t,e){let{audioCodec:i,channels:r}=t;return(void 0===i||(e.audioCodec||"").substring(0,4)===i.substring(0,4))&&(void 0===r||r===(e.channels||"2"))}function t$(t,e,i){for(let r=e;r>-1;r--)if(i(t[r]))return r;for(let r=e+1;r<t.length;r++)if(i(t[r]))return r;return -1}function tZ(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}class tJ extends C{resetEstimator(t){t&&(this.log("setting initial bwe to ".concat(t)),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let t=this.hls.config;return new D(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){let{hls:t}=this;t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.FRAG_LOADING,this.onFragLoading,this),t.on(h.FRAG_LOADED,this.onFragLoaded,this),t.on(h.FRAG_BUFFERED,this.onFragBuffered,this),t.on(h.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(h.LEVEL_LOADED,this.onLevelLoaded,this),t.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(h.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:t}=this;t&&(t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.FRAG_LOADING,this.onFragLoading,this),t.off(h.FRAG_LOADED,this.onFragLoaded,this),t.off(h.FRAG_BUFFERED,this.onFragBuffered,this),t.off(h.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(h.LEVEL_LOADED,this.onLevelLoaded,this),t.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(h.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(h.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){let i=e.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=null!=(r=e.part)?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case o.FRAG_LOAD_TIMEOUT:{let t=e.frag,{fragCurrent:i,partCurrent:r}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){let e=performance.now(),i=r?r.stats:t.stats,s=e-i.loading.start,a=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&a>-1){let t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(t,a),i.loaded)}else this.bwEstimator.sampleTTFB(s)}}}}getTimeToLoadFrag(t,e,i,r){let s=r?t+this.lastLevelLoadSec:0;return t+i/e+s}onLevelLoaded(t,e){let i=this.hls.config,{loading:r}=e.stats,a=r.end-r.first;s(a)&&(this.lastLevelLoadSec=a/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,e){let{frag:i,part:r}=e,s=r?r.stats:i.stats;if(i.type===R.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(i)){if
1(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let t=r?r.duration:i.duration,e=this.hls.levels[i.level],a=(e.loaded?e.loaded.bytes:0)+s.loaded,n=(e.loaded?e.loaded.duration:0)+t;e.loaded={bytes:a,duration:n},e.realBitrate=Math.round(8*a/n)}if(i.bitrateTest){let t={stats:s,frag:i,part:r,id:i.type};this.onFragBuffered(h.FRAG_BUFFERED,t),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(t,e){let{frag:i,part:r}=e,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;let a=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==R.MAIN||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,e,t,0,r,1,1);if(s>-1)return s;let a=this.hls.firstLevel,n=Math.min(Math.max(a,e),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(a," clamped to ").concat(n)),n}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(-1!==t&&(!e||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;let r=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){let e=this.hls.levels;if(e.length>Math.max(t,r)&&e[t].loadError<=e[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}getNextABRAutoLevel(){let{fragCurrent:t,partCurrent:e,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:s,minAutoLevel:a}=i,n=e?e.duration:t?t.duration:0,l=this.getBwEstimate(),o=this.getStarvationDelay(),h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(o){let t=this.findBestLevel(l,a,r,o,0,h,d);if(t>=0)return this.rebufferNotice=-1,t}let c=n?Math.min(n,s.maxStarvationDelay):s.maxStarvationDelay;if(!o){let t=this.bitrateTestDelay;t&&(c=(n?Math.min(n,s.maxLoadingDelay):s.maxLoadingDelay)-t,this.info("bitrate test took ".concat(Math.round(1e3*t),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*c)," ms")),h=d=1)}let u=this.findBestLevel(l,a,r,o,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info("".concat(o?"rebuffering expected":"buffer is empty",", optimal quality level ").concat(u))),u>-1)return u;let f=i.levels[a],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?a:i.loadLevel}getStarvationDelay(){let t=this.hls,e=t.media;if(!e)return 1/0;let i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,r,a,n,l){var o,h;let d;let c=r+a,u=this.lastLoadedFragLevel,f=-1===u?this.hls.firstLevel:u,{fragCurrent:g,partCurrent:m}=this,{levels:p,allAudioTracks:E,loadLevel:y,config:v}=this.hls;if(1===p.length)return 0;let T=p[f],S=!!(null!=(o=this.hls.latestLevelDetails)&&o.live),A=-1===y||-1===u,L="SDR",I=(null==T?void 0:T.frameRate)||0,{audioPreference:R,videoPreference:b}=v,D=this.audioTracksByGroup||(this.audioTracksByGroup=tj(E)),k=-1;if(A){if(-1!==this.firstSelection)return this.firstSelection;let r=function(t,e,i,r,a){let n=Object.keys(t),l=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,h=null==a?void 0:a.videoCodec,d=l&&2===parseInt(l),c=!1,u=!1,f=1/0,g=1/0,m=1/0,p=1/0,E=0,y=[],{preferHDR:v,allowedVideoRanges:T}=function(t,e){let i=!1,r=[];if(t&&(i="SDR"!==t,r=[t]),e){let t="SDR"!==(r=e.allowedVideoRanges||tN.slice(0)).join("")&&!e.videoCodec;(i=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){let t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}(e,a);for(let e=n.length;e--;){let i=t[n[e]];c||(c=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter(t=>i.videoRanges[t]>0).length>0&&(u=!0)}f=s(f)?f:0,g=s(g)?g:0;let S=Math.max(1080,f),A=Math.max(30,g);i=Math.max(m=s(m)?m:i,i),u||(e=void 0);let L=n.length>1;return{codecSet:n.reduce((e,r)=>{let s=t[r];
1if(r===e)return e;if(y=u?T.filter(t=>s.videoRanges[t]>0):[],L){if(s.minBitrate>i)return tW(r,"min bitrate of ".concat(s.minBitrate," > current estimate of ").concat(i)),e;if(!s.hasDefaultAudio)return tW(r,"no renditions with default or auto-select sound found"),e;if(o&&r.indexOf(o.substring(0,4))%5!=0)return tW(r,'audio codec preference "'.concat(o,'" not found')),e;if(l&&!d){if(!s.channels[l])return tW(r,"no renditions with ".concat(l," channel sound found (channels options: ").concat(Object.keys(s.channels),")")),e}else if((!o||d)&&c&&0===s.channels["2"])return tW(r,"no renditions with stereo sound found"),e;if(s.minHeight>S)return tW(r,"min resolution of ".concat(s.minHeight," > maximum of ").concat(S)),e;if(s.minFramerate>A)return tW(r,"min framerate of ".concat(s.minFramerate," > maximum of ").concat(A)),e;if(!y.some(t=>s.videoRanges[t]>0))return tW(r,"no variants with VIDEO-RANGE of ".concat(tY(y)," found")),e;if(h&&r.indexOf(h.substring(0,4))%5!=0)return tW(r,'video codec preference "'.concat(h,'" not found')),e;if(s.maxScore<E)return tW(r,"max score of ".concat(s.maxScore," < selected max of ").concat(E)),e}return e&&(tL(r)>=tL(e)||s.fragmentError>t[e].fragmentError)?e:(p=s.minIndex,E=s.maxScore,r)},void 0),videoRanges:y,preferHDR:v,minFramerate:g,minBitrate:m,minIndex:p}}(this.codecTiers||(this.codecTiers=p.slice(e,i+1).reduce((t,e,i)=>{if(!e.codecSet)return t;let r=e.audioGroups,s=t[e.codecSet];s||(t[e.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,e.bitrate);let a=Math.min(e.height,e.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,e.frameRate),s.minIndex=Math.min(s.minIndex,i),s.maxScore=Math.max(s.maxScore,e.score),s.fragmentError+=e.fragmentError,s.videoRanges[e.videoRange]=(s.videoRanges[e.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;let e=D.groups[t];e&&(s.hasDefaultAudio=s.hasDefaultAudio||D.hasDefaultAudio?e.hasDefault:e.hasAutoSelect||!D.hasDefaultAudio&&!D.hasAutoSelectAudio,Object.keys(e.channels).forEach(t=>{s.channels[t]=(s.channels[t]||0)+e.channels[t]}))}),t},{})),L,t,R,b),{codecSet:a,videoRanges:n,minFramerate:l,minBitrate:o,minIndex:h,preferHDR:c}=r;k=h,d=a,L=c?n[n.length-1]:n[0],I=l,t=Math.max(t,o),this.log("picked start tier ".concat(tY(r)))}else d=null==T?void 0:T.codecSet,L=null==T?void 0:T.videoRange;let _=m?m.duration:g?g.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,C=[];for(let o=i;o>=e;o--){let e;let g=p[o],E=o>f;if(!g)continue;if(v.useMediaCapabilities&&!g.supportedResult&&!g.supportedPromise){let e=navigator.mediaCapabilities;"function"==typeof(null==e?void 0:e.decodingInfo)&&function(t,e,i,r,a,n){let l=t.videoCodec,o=t.audioCodec?t.audioGroups:null,h=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,c=d?parseInt(d):h?1/0:2,u=null;if(null!=o&&o.length)try{u=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((t,i)=>{if(i){let r=e.groups[i];if(!r)throw Error("Audio track group ".concat(i," not found"));Object.keys(r.channels).forEach(e=>{t[e]=(t[e]||0)+r.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==l&&(l.split(",").some(t=>tf(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(a,8e6))||!!u&&s(c)&&Object.keys(u).some(t=>parseInt(t)>c)}(g,D,L,I,t,R)?(g.supportedPromise=tM(g,D,e,this.supportedCache),g.supportedPromise.then(t=>{if(!this.hls)return;g.supportedResult=t;let e=this.hls.levels,i=e.indexOf(g);t.error?this.warn('MediaCapabilities decodingInfo error: "'.concat(t.error,'" for level ').concat(i," ").concat(tY(t))):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log("MediaCapabilities decodingInfo for level ".concat(i," not smooth or powerEfficient: ").concat(tY(t))):(this.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(i," ").concat(tY(t))),i>-1&&e.length>1&&(this.log("Removing unsupported level ".concat(i)),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn("Error handling MediaCapabilities decodingInfo: ".concat(t))})):g.supportedResult=tO}if((d&&g.codecSet!==d||L&&g.videoRange!==L||E&&I>g.frameRate||!E&&I>0&&I<g.frameRate||null!=(h=g.supportedResult)&&null!=(h=h.decodingInfoResults)&&h.some(t=>!1===t.smooth))&&(!A||o!==k)){C.push(o);continue}let T=g.details,b=(m?null==T?void 0:T.partTarget:null==T?void 0:T.averagetargetduration)||_;e=E?l*t:n*t;let O=_&&r>=2*_&&0===a?g.averageBitrate:g.maxBitrate,w=this.getTimeToLoadFrag(P,e,O*b,void 0===T);if(e>=O&&(o===u||0===g.loadError&&0===g.fragmentError)&&(w<=P||!s(w)||S&&!this.bitrateTestDelay||w<c)){let t=this.forcedAutoLevel;return o!==y&&(-1===t||t!==y)&&(C.length&&this.trace("Skipped level(s) ".concat(C.join(",")," of ").concat(i,' max with CODECS and VIDEO-RANGE:"').concat(p[C[0]].codecs,'" ').concat(p[C[0]].videoRange,'; not compatible with "').concat(d,'" ').concat(L)),this.info("switch candidate:".concat(f,"->").concat(o," adjustedbw(").concat(Math.round(e),")-bitrate=").concat(Math.round(e-O)," ttfb:").concat(P.toFixed(1)," avgDuration:").concat(b.toFixed(1)," maxFetchDuration:").concat(c.toFixed(1)," fetchDuration:").concat(w.toFixed(1)," firstSelection:").concat(A," codecSet:").concat(g.codecSet," videoRange:").concat(g.videoRange," hls.loadLevel:").concat(y))),A&&(this.firstSelection=o),o}}return -1}set nextAutoLevel(t){let e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){let{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.co
1decTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;let i;let{fragCurrent:r,partCurrent:a,hls:n}=this,{autoLevelEnabled:l,media:o}=n;if(!r||!o)return;let d=performance.now(),c=a?a.stats:r.stats,u=a?a.duration:r.duration,f=d-c.loading.start,g=n.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||m<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!l)return;let E=p>-1&&p!==m,y=!!t||E;if(!y&&(o.paused||!o.playbackRate||!o.readyState))return;let v=n.mainForwardBufferInfo;if(!y&&null===v)return;let T=this.bwEstimator.getEstimateTTFB(),S=Math.abs(o.playbackRate);if(f<=Math.max(T,u/(2*S)*1e3))return;let A=v?v.len/S:0,L=c.loading.first?c.loading.first-c.loading.start:-1,I=c.loaded&&L>-1,R=this.getBwEstimate(),b=n.levels,D=b[m],k=Math.max(c.loaded,Math.round(u*(r.bitrate||D.averageBitrate)/8)),_=I?f-L:f;_<1&&I&&(_=Math.min(f,8*c.loaded/R));let P=I?1e3*c.loaded/_:0,C=T/1e3,O=P?(k-c.loaded)/P:8*k/R+C;if(O<=A)return;let w=P?8*P:R,M=(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live)===!0,x=this.hls.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(i=m-1;i>g;i--){let t=b[i].maxBitrate,e=!b[i].details||M;if((F=this.getTimeToLoadFrag(C,w,u*t,e))<Math.min(A,u+C))break}if(F>=O||F>10*u)return;I?this.bwEstimator.sample(f-Math.min(T,L),c.loaded):this.bwEstimator.sampleTTFB(f);let N=b[i].maxBitrate;this.getBwEstimate()*x>N&&this.resetEstimator(N);let U=this.findBestLevel(N,g,i,0,A,1,1);U>-1&&(i=U),this.warn("Fragment ".concat(r.sn).concat(a?" part "+a.index:""," of level ").concat(m," is loading too slowly;\n      Fragment duration: ").concat(r.duration.toFixed(3),"\n      Time to underbuffer: ").concat(A.toFixed(3)," s\n      Estimated load time for current fragment: ").concat(O.toFixed(3)," s\n      Estimated load time for down switch fragment: ").concat(F.toFixed(3)," s\n      TTFB estimate: ").concat(0|L," ms\n      Current BW estimate: ").concat(s(R)?0|R:"Unknown"," bps\n      New BW estimate: ").concat(0|this.getBwEstimate()," bps\n      Switching to level ").concat(i," @ ").concat(0|N," bps")),n.nextLoadLevel=n.nextAutoLevel=i,this.clearTimer();let B=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===i&&i>0){let t=this.getStarvationDelay();if(this.warn("Aborting inflight request ".concat(i>0?"and switching down":"","\n      Fragment duration: ").concat(r.duration.toFixed(3)," s\n      Time to underbuffer: ").concat(t.toFixed(3)," s")),r.abortRequests(),this.fragCurrent=this.partCurrent=null,i>g){let e=this.findBestLevel(this.hls.levels[g].bitrate,g,i,0,t,1,1);-1===e&&(e=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};E||O>2*F?B():this.timer=self.setInterval(B,1e3*F),n.trigger(h.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:a,stats:c})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}}let t0={search:function(t,e){let i=0,r=t.length-1,s=null,a=null;for(;i<=r;){let n=e(a=t[s=(i+r)/2|0]);if(n>0)i=s+1;else{if(!(n<0))return a;r=s-1}}return null}};function t1(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.005,a=null;if(t){a=e[1+t.sn-e[0].sn]||null;let r=t.endDTS-i;r>0&&r<15e-7&&(i+=15e-7),a&&t.level!==a.level&&a.end<=t.end&&(a=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(a=e[0]);if(a&&((!t||t.level===a.level)&&0===t2(i,r,a)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){let r=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),i);return t.start<=r}return!1}(a,t,Math.min(s,r))))return a;let n=t0.search(e,t2.bind(null,i,r));return n&&(n!==t||!a)?n:a}function t2(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(i.start<=t&&i.start+i.duration>t)return 0;let r=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=t?1:i.start-r>t&&i.start?-1:0}function t3(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let r,s=t.fragments,{fragmentHint:a}=t;return a&&(s=s.concat(a)),t0.search(s,t=>t.cc<e?1:t.cc>e?-1:(r=t,t.end<=i)?1:t.start>i?-1:0),r||null}return null}function t4(t){switch(t.details){case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_TIMEOUT:case o.LEVEL_LOAD_TIMEOUT:case o.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function t5(t){return t.details.startsWith("key")}function t8(t){return t5(t)&&!!t.frag&&!t.frag.decryptdata}function t6(t,e){let i=t4(e);return t.default["".concat(i?"timeout":"error","Retry")]}function t9(t,e){return Math.min(("linear"===t.backoff?1:Math.pow(2,e))*t.retryDelayMs,t.maxRetryDelayMs)}function t7(t){return P(P({},t),{errorRetry:null,timeoutRetry:null})}function et(t,e,i,r){if(!t)return!1;let s=null==r?void 0:r.code,a=e<t.maxNumRetry&&(ee(s)||!!s&&(s<400||s>499)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,r,a):a}function ee(t){return 0===t&&!1===navigator.onLine}var ei={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},er={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class es extends C{registerListeners(){let t=this.hls;t.on(h.ERROR,this.onError,this),t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let t=this.hls;t&&(t.off(h.ERROR,this.onError,this),t.off(h.ERROR,this.onErrorOut,this),t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===R.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;let e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;let r=t.audioGroups;if(r)return this.hls.allAudioTracks.filter(t=>r.indexOf(t.groupId)>=0).some(t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i,r,s;if(e.fatal)return;let a=this.hls,n=e.context;switch(e.details){case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case o.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap){e.errorAction=ea();return}case o.FRAG_GAP:case o.FRAG_DECRYPT_ERROR:e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=ei.SendAlternateToPenaltyBox;return;case o.LEVEL_EMPTY_ERROR:case o.LEVEL_PARSING_ERROR:{let t=e.parent===R.MAIN?e.level:a.loadLevel;e.details===o.LEVEL_EMPTY_ERROR&&null!=(r=e.context)&&null!=(r=r.levelDetails)&&r.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:"number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level));return;case o.AUDIO_TRACK_LOAD_ERROR:case o.AUDIO_TRACK_LOAD_TIMEOUT:case o.SUBTITLE_LOAD_ERROR:case o.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let t=a.loadLevelObj;t&&(n.type===I.AUDIO_TRACK&&t.hasAudioGroup(n.groupId)||n.type===I.SUBTITLE_TRACK&&t.hasSubtitleGroup(n.groupId))&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.loadLevel),e.errorAction.action=ei.SendAlternateToPenaltyBox,e.errorAction.flags=er.MoveAllAlternatesMatchingHost)}return;case o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:e.errorAction={action:ei.SendAlternateToPenaltyBox,flags:er.MoveAllAlternatesMatchingHDCP};return;case o.KEY_SYSTEM_SESSION_UPDATE_FAILED:case o.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case o.KEY_SYSTEM_NO_SESSION:e.errorAction={action:ei.SendAlternateToPenaltyBox,flags:er.MoveAllAlternatesMatchingKey};return;
1case o.BUFFER_ADD_CODEC_ERROR:case o.REMUX_ALLOC_ERROR:case o.BUFFER_APPEND_ERROR:e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,null!=(s=e.level)?s:a.loadLevel));return;case o.INTERNAL_EXCEPTION:case o.BUFFER_APPENDING_ERROR:case o.BUFFER_FULL_ERROR:case o.LEVEL_SWITCH_ERROR:case o.BUFFER_STALLED_ERROR:case o.BUFFER_SEEK_OVER_HOLE:case o.BUFFER_NUDGE_ON_STALL:e.errorAction=ea();return}e.type===l.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=ea())}getPlaylistRetryOrSwitchAction(t,e){let i=t6(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if(et(i,r,t4(t),t.response))return{action:ei.RetryRequest,flags:er.None,retryConfig:i,retryCount:r};let s=this.getLevelSwitchAction(t,e);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(t){let e=this.hls,i=this.getVariantLevelIndex(t.frag),r=e.levels[i],{fragLoadPolicy:s,keyLoadPolicy:a}=e.config,n=t6(t5(t)?a:s,t),l=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(r&&(t.details!==o.FRAG_GAP&&r.fragmentError++,!t8(t)&&et(n,l,t4(t),t.response)))return{action:ei.RetryRequest,flags:er.None,retryConfig:n,retryCount:l};let h=this.getLevelSwitchAction(t,i);return n&&(h.retryConfig=n,h.retryCount=l),h}getLevelSwitchAction(t,e){let i=this.hls;null==e&&(e=i.loadLevel);let r=this.hls.levels[e];if(r){var s,a,n,l;let e=t.details;r.loadError++,e===o.BUFFER_APPEND_ERROR&&r.fragmentError++;let h=-1,{levels:d,loadLevel:c,minAutoLevel:u,maxAutoLevel:f}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);let g=null==(s=t.frag)?void 0:s.type,m=(g===R.AUDIO&&e===o.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===o.BUFFER_ADD_CODEC_ERROR||e===o.BUFFER_APPEND_ERROR))&&d.some(t=>{let{audioCodec:e}=t;return r.audioCodec!==e}),p="video"===t.sourceBufferName&&(e===o.BUFFER_ADD_CODEC_ERROR||e===o.BUFFER_APPEND_ERROR)&&d.some(t=>{let{codecSet:e,audioCodec:i}=t;return r.codecSet!==e&&r.audioCodec===i}),{type:E,groupId:y}=null!=(a=t.context)?a:{};for(let i=d.length;i--;){let s=(i+c)%d.length;if(s!==c&&s>=u&&s<=f&&0===d[s].loadError){let i=d[s];if(e===o.FRAG_GAP&&g===R.MAIN&&t.frag){let e=d[s].details;if(e){let i=t1(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else if(E===I.AUDIO_TRACK&&i.hasAudioGroup(y)||E===I.SUBTITLE_TRACK&&i.hasSubtitleGroup(y))continue;else if(g===R.AUDIO&&null!=(n=r.audioGroups)&&n.some(t=>i.hasAudioGroup(t))||g===R.SUBTITLE&&null!=(l=r.subtitleGroups)&&l.some(t=>i.hasSubtitleGroup(t))||m&&r.audioCodec===i.audioCodec||p&&r.codecSet===i.codecSet||!m&&r.codecSet!==i.codecSet)continue;h=s;break}}if(h>-1&&i.loadLevel!==h)return t.levelRetry=!0,this.playlistError=0,{action:ei.SendAlternateToPenaltyBox,flags:er.None,nextAutoLevel:h}}return{action:ei.SendAlternateToPenaltyBox,flags:er.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case ei.DoNothing:break;case ei.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===o.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn('MediaSource ended after "'.concat(e.sourceBufferName,'" sourceBuffer append error. Attempting to recover from media error.')),this.hls.recoverMediaError()):e.fatal=!0;case ei.RetryRequest:}if(e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){let e=this.hls,i=t.errorAction;if(!i)return;let{flags:r}=i,s=i.nextAutoLevel;switch(r){case er.None:this.switchLevel(t,s);break;case er.MoveAllAlternatesMatchingHDCP:{let r=this.getVariantLevelIndex(t.frag),s=e.levels[r],a=null==s?void 0:s.attrs["HDCP-LEVEL"];if(i.hdcpLevel=a,"NONE"===a)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(a){e.maxHdcpLevel=tF[tF.indexOf(a)-1],i.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(e.maxHdcpLevel,'" or lower'));break}}case er.MoveAllAlternatesMatchingKey:{let e=t.decryptdata;if(e){let r=this.hls.levels,s=r.length;for(let i=s;i--;)if(this.variantHasKey(r[i],e)){var a,n;this.log("Banned key found in level ".concat(i," (").concat(r[i].bitrate,'bps) or audio group "').concat(null==(a=r[i].audioGroups)?void 0:a.join(","),'" (').concat(null==(n=t.frag)?void 0:n.type," fragment) ").concat(G(e.keyId||[]))),r[i].fragmentError++,r[i].loadError++,this.log("Removing level ".concat(i," with key error (").concat(t.error,")")),this.hls.removeLevel(i)}let l=t.frag;if(this.hls.levels.length<s)i.resolved=!0;else if(l&&l.type!==R.MAIN){let t=l.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}}}i.resolved||this.switchLevel(t,s)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn("switching to level ".concat(e," after ").concat(t.details)),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===o.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){let e=tP(t.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r]["".concat(t.sourceBufferName,"Codec")]===e&&(this.log("Removing level ".concat(r," for ").concat(t.details,' ("').concat(e,'" not supported)')),this.hls.removeLevel(r))}}constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}}function ea(t){let e={action:ei.DoNothing,flags:er.None};return t&&(e.resolved=!0),e}var en={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class el{_registerListeners(){let{hls:t}=this;t&&(t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.BUFFER_APPENDED,this.onBufferAppended,this),t.on(h.FRAG_BUFFERED,this.onFragBuffered,this),t.on(h.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:t}=this;t&&(t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.BUFFER_APPENDED,this.onBufferAppended,this),t.off(h.FRAG_BUFFERED,this.onFragBuffered,this),t.off(h.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){let i=this.activePartLists[e];if(i)for(let e=i.length;e--;){let r=i[e];if(!r)break;
1if(r.start<=t&&t<=r.end&&r.loaded)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){let{fragments:r}=this,s=Object.keys(r);for(let a=s.length;a--;){let n=r[s[a]];if((null==n?void 0:n.body.type)===e&&(!i||n.buffered)){let e=n.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,r,s){this.timeRanges&&(this.timeRanges[t]=e);let a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{let n=this.fragments[r];if(!n||a>=n.body.sn)return;if(!n.buffered&&(!n.loaded||s)){n.body.type===i&&this.removeFragment(n.body);return}let l=n.range[t];if(l){if(0===l.time.length){this.removeFragment(n.body);return}l.time.some(t=>{let i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(n.body),i})}})}detectPartialFragments(t){let e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;let i=t.frag,r=eh(i),s=this.fragments[r];if(!s||s.buffered&&i.gap)return;let a=!i.relurl;Object.keys(e).forEach(r=>{let n=i.elementaryStreams[r];if(!n)return;let l=e[r],o=a||!0===n.partial;s.range[r]=this.getBufferedTimes(i,t.part,o,l)}),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),eo(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}removeParts(t,e){let i=this.activePartLists[e];i&&(this.activePartLists[e]=ed(i,e=>e.fragment.sn>=t))}fragBuffered(t,e){let i=eh(t),r=this.fragments[i];!r&&e&&(r=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(t,e,i,r){let s={time:[],partial:i},a=t.start,n=t.end,l=t.minEndPTS||n,o=t.maxStartPTS||a;for(let t=0;t<r.length;t++){let e=r.start(t)-this.bufferPadding,i=r.end(t)+this.bufferPadding;if(o>=e&&l<=i){s.time.push({startPTS:Math.max(a,r.start(t)),endPTS:Math.min(n,r.end(t))});break}if(a<i&&n>e){let e=Math.max(a,r.start(t)),i=Math.min(n,r.end(t));i>e&&(s.partial=!0,s.time.push({startPTS:e,endPTS:i}))}else if(n<=e)break}return s}getPartialFragment(t){let e,i,r,s=null,a=0,{bufferPadding:n,fragments:l}=this;return Object.keys(l).forEach(o=>{let h=l[o];h&&eo(h)&&(i=h.body.start-n,r=h.body.end+n,t>=i&&t<=r&&a<=(e=Math.min(t-i,r-t))&&(s=h.body,a=e))}),s}isEndListAppended(t){let e=this.endListFragments[t];return void 0!==e&&(e.buffered||eo(e))}getState(t){let e=eh(t),i=this.fragments[e];return i?i.buffered?eo(i)?en.PARTIAL:en.OK:en.APPENDING:en.NOT_LOADED}isTimeBuffered(t,e,i){let r,s;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,s=i.end(a)+this.bufferPadding,t>=r&&e<=s)return!0;if(e<=r)break}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;let i=e.frag,r=e.part?null:e,s=eh(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){let{frag:i,part:r,timeRanges:s,type:a}=e;if("initSegment"===i.sn)return;let n=i.type;if(r){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(r)}this.timeRanges=s;let l=s[a];this.detectEvictedFragments(a,l,n,r)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){let e=eh(t);return!!this.fragments[e]}hasFragments(t){let{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let r=i.length;r--;){let s=e[i[r]];if((null==s?void 0:s.body.type)===t)return!0}return!1}hasParts(t){var e;return!!(null!=(e=this.activePartLists[t])&&e.length)}removeFragmentsInRange(t,e,i,r,s){(!r||this.hasGaps)&&Object.keys(this.fragments).forEach(a=>{let n=this.fragments[a];if(!n)return;let l=n.body;l.type===i&&(!r||l.gap)&&l.start<e&&l.end>t&&(n.buffered||s)&&this.removeFragment(l)})}removeFragment(t){let e=eh(t);t.clearElementaryStreamInfo();let i=this.activePartLists[t.type];if(i){let e=t.sn;this.activePartLists[t.type]=ed(i,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}}function eo(t){var e,i,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(r=t.range.audiovideo)&&r.partial)}function eh(t){return"".concat(t.type,"_").concat(t.level,"_").concat(t.sn)}function ed(t,e){return t.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var ec={cbc:0,ctr:1};class eu{decrypt(t,e){switch(this.aesMode){case ec.cbc:return this.subtle.decrypt({
1name:"AES-CBC",iv:this.aesIV},e,t);case ec.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw Error("[AESCrypto] invalid aes mode ".concat(this.aesMode))}}constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}}class ef{uint8ArrayToUint32Array_(t){let e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){let t=this.sBox,e=this.invSBox,i=this.subMix,r=i[0],s=i[1],a=i[2],n=i[3],l=this.invSubMix,o=l[0],h=l[1],d=l[2],c=l[3],u=new Uint32Array(256),f=0,g=0,m=0;for(m=0;m<256;m++)m<128?u[m]=m<<1:u[m]=m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;let l=u[f],m=u[l],p=u[m],E=257*u[i]^16843008*i;r[f]=E<<24|E>>>8,s[f]=E<<16|E>>>16,a[f]=E<<8|E>>>24,n[f]=E,E=16843009*p^65537*m^257*l^16843008*f,o[i]=E<<24|E>>>8,h[i]=E<<16|E>>>16,d[i]=E<<8|E>>>24,c[i]=E,f?(f=l^u[u[u[p^l]]],g^=u[u[g]]):f=g=1}}expandKey(t){let e,i,r,s;let a=this.uint8ArrayToUint32Array_(t),n=!0,l=0;for(;l<a.length&&n;)n=a[l]===this.key[l],l++;if(n)return;this.key=a;let o=this.keySize=a.length;if(4!==o&&6!==o&&8!==o)throw Error("Invalid aes key size="+o);let h=this.ksRows=(o+6+1)*4,d=this.keySchedule=new Uint32Array(h),c=this.invKeySchedule=new Uint32Array(h),u=this.sBox,f=this.rcon,g=this.invSubMix,m=g[0],p=g[1],E=g[2],y=g[3];for(e=0;e<h;e++){if(e<o){r=d[e]=a[e];continue}s=r,e%o==0?s=(u[(s=s<<8|s>>>24)>>>24]<<24|u[s>>>16&255]<<16|u[s>>>8&255]<<8|u[255&s])^f[e/o|0]<<24:o>6&&e%o==4&&(s=u[s>>>24]<<24|u[s>>>16&255]<<16|u[s>>>8&255]<<8|u[255&s]),d[e]=r=(d[e-o]^s)>>>0}for(i=0;i<h;i++)e=h-i,s=3&i?d[e]:d[e-4],i<4||e<=4?c[i]=s:c[i]=m[u[s>>>24]]^p[u[s>>>16&255]]^E[u[s>>>8&255]]^y[u[255&s]],c[i]=c[i]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){let r,s,a,n,l,o,h,d,c,u,f,g,m,p;let E=this.keySize+6,y=this.invKeySchedule,v=this.invSBox,T=this.invSubMix,S=T[0],A=T[1],L=T[2],I=T[3],R=this.uint8ArrayToUint32Array_(i),b=R[0],D=R[1],k=R[2],_=R[3],P=new Int32Array(t),C=new Int32Array(P.length),O=this.networkToHostOrderSwap;for(;e<P.length;){for(p=1,c=O(P[e]),u=O(P[e+1]),f=O(P[e+2]),g=O(P[e+3]),l=c^y[0],o=g^y[1],h=f^y[2],d=u^y[3],m=4;p<E;p++)r=S[l>>>24]^A[o>>16&255]^L[h>>8&255]^I[255&d]^y[m],s=S[o>>>24]^A[h>>16&255]^L[d>>8&255]^I[255&l]^y[m+1],a=S[h>>>24]^A[d>>16&255]^L[l>>8&255]^I[255&o]^y[m+2],n=S[d>>>24]^A[l>>16&255]^L[o>>8&255]^I[255&h]^y[m+3],l=r,o=s,h=a,d=n,m+=4;r=v[l>>>24]<<24^v[o>>16&255]<<16^v[h>>8&255]<<8^v[255&d]^y[m],s=v[o>>>24]<<24^v[h>>16&255]<<16^v[d>>8&255]<<8^v[255&l]^y[m+1],a=v[h>>>24]<<24^v[d>>16&255]<<16^v[l>>8&255]<<8^v[255&o]^y[m+2],n=v[d>>>24]<<24^v[l>>16&255]<<16^v[o>>8&255]<<8^v[255&h]^y[m+3],C[e]=O(r^b),C[e+1]=O(n^D),C[e+2]=O(a^k),C[e+3]=O(s^_),b=c,D=u,k=f,_=g,e+=4}return C.buffer}constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}}class eg{expandKey(){let t=function(t){switch(t){case ec.cbc:return"AES-CBC";case ec.ctr:return"AES-CTR";default:throw Error("[FastAESKey] invalid aes mode ".concat(t))}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}}class em{destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;let i=new Uint8Array(t);return(this.reset(),this.removePKCS7Padding)?function(t){let e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,r){return this.useSoftware?new Promise((s,a)=>{let n=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(n,e,i,r);let l=this.flush();l?s(l.buffer):a(Error("[softwareDecrypt] Failed to decrypt data"))}
1):this.webCryptoDecrypt(new Uint8Array(t),e,i,r)}softwareDecrypt(t,e,i,r){let{currentIV:s,currentResult:a,remainderData:n}=this;if(r!==ec.cbc||16!==e.byteLength)return F.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),n&&(t=tc(n,t),this.remainderData=null);let l=this.getValidChunk(t);if(!l.length)return null;s&&(i=s);let o=this.softwareDecrypter;return(o||(o=this.softwareDecrypter=new ef),o.expandKey(e),this.currentResult=o.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,a)?a:null}webCryptoDecrypt(t,e,i,r){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,r));this.key=e,this.fastAesKey=new eg(this.subtle,e,r)}return this.fastAesKey.expandKey().then(e=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new eu(this.subtle,new Uint8Array(i),r).decrypt(t.buffer,e)):Promise.reject(Error("web crypto not initialized"))).catch(s=>(F.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(s.name,": ").concat(s.message)),this.onWebCryptoError(t,e,i,r)))}onWebCryptoError(t,e,i,r){let s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,r);let s=this.flush();if(s)return s.buffer}throw Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t,i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(F.log("[decrypter]: ".concat(t)),this.logEnabled=!1)}constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{let t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}}class ep{destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){let i=t.url;if(!i)return Promise.reject(new ev({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:Error("Fragment does not have a ".concat(i?"part list":"url")),networkDetails:null}));this.abort();let r=this.config,s=r.fLoader,a=r.loader;return new Promise((n,h)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0])){h(ey(t));return}t.gap=!1}let d=this.loader=s?new s(r):new a(r),c=eE(t);t.loader=d;let u=t7(r.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:131072};t.stats=d.stats;let g={onSuccess:(e,i,r,s)=>{this.resetLoader(t,d);let a=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),n({frag:t,part:null,payload:a,networkDetails:s})},onError:(e,r,s,a)=>{this.resetLoader(t,d),h(new ev({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:P({url:i,data:void 0},e),error:Error("HTTP Error ".concat(e.code," ").concat(e.text)),networkDetails:s,stats:a}))},onAbort:(e,i,r)=>{this.resetLoader(t,d),h(new ev({type:l.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:t,error:Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,i,r)=>{this.resetLoader(t,d),h(new ev({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:Error("Timeout after ".concat(f.timeout,"ms")),networkDetails:r,stats:e}))}};e&&(g.onProgress=(i,r,s,a)=>e({frag:t,part:null,payload:s,networkDetails:a})),d.load(c,f,g)})}loadPart(t,e,i){this.abort();let r=this.config,s=r.fLoader,a=r.loader;return new Promise((n,h)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){h(ey(t,e));return}let d=this.loader=s?new s(r):new a(r),c=eE(t,e);t.loader=d;let u=t7(r.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:131072};e.stats=d.stats,d.load(c,f,{onSuccess:(r,s,a,l)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,e);let o={frag:t,part:e,payload:r.data,networkDetails:l};i(o),n(o)},onError:(i,r,s,a)=>
1{this.resetLoader(t,d),h(new ev({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:P({url:c.url,data:void 0},i),error:Error("HTTP Error ".concat(i.code," ").concat(i.text)),networkDetails:s,stats:a}))},onAbort:(i,r,s)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,d),h(new ev({type:l.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(t,d),h(new ev({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:Error("Timeout after ".concat(f.timeout,"ms")),networkDetails:s,stats:i}))}})})}updateStatsFromPart(t,e){let i=t.stats,r=e.stats,s=r.total;if(i.loaded+=r.loaded,s){let r=Math.round(t.duration/e.duration),a=Math.min(Math.round(i.loaded/s),r),n=(r-a)*Math.round(i.loaded/a);i.total=i.loaded+n}else i.total=Math.max(i.loaded,i.total);let a=i.loading,n=r.loading;a.start?a.first+=n.first-n.start:(a.start=n.start,a.first=n.first),a.end=n.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}}function eE(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},a=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(s(a)&&s(n)){var l,o;let e=a,i=n;
1if("initSegment"===t.sn&&("AES-128"===(o=null==(l=t.decryptdata)?void 0:l.method)||"AES-256"===o)){let t=n-a;t%16&&(i=n+(16-t%16)),0!==a&&(r.resetIV=!0,e=a-16)}r.rangeStart=e,r.rangeEnd=i}return r}function ey(t,e){let i=Error("GAP ".concat(t.gap?"tag":"attribute"," found")),r={type:l.MEDIA_ERROR,details:o.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new ev(r)}class ev extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class eT extends C{destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}}class eS{constructor(t,e,i,r=0,s=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=eA(),this.buffering={audio:eA(),video:eA(),audiovideo:eA()},this.level=t,this.sn=e,this.id=i,this.size=r,this.part=s,this.partial=a}}function eA(){return{start:0,executeStart:0,executeEnd:0,end:0}}let eL={length:0,start:()=>0,end:()=>0};class eI{static isBuffered(t,e){if(t){let i=eI.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){let e=eI.getBuffered(t);return eI.timeRangesToArray(e)}return[]}static timeRangesToArray(t){let e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){let r=eI.bufferedRanges(t);if(r.length)return eI.bufferedInfo(r,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){let r;e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let s=-1,a=[];if(i)for(let r=0;r<t.length;r++){e>=t[r].start&&e<=t[r].end&&(s=r);let n=a.length;if(n){let e=a[n-1].end;t[r].start-e<i?t[r].end>e&&(a[n-1].end=t[r].end):a.push(t[r])}else a.push(t[r])}else a=t;let n=0,l=e,o=e;for(let t=0;t<a.length;t++){let h=a[t].start,d=a[t].end;if(-1===s&&e>=h&&e<=d&&(s=t),e+i>=h&&e<d)l=h,n=(o=d)-e;else if(e+i<h){r=h;break}}return{len:n,start:l||0,end:o||0,nextStart:r,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||eL}catch(t){return F.log("failed to get media.buffered",t),eL}}}let eR=/\{\$([a-zA-Z0-9-_]+)\}/g;function eb(t,e){if(null!==t.variableList||t.hasVariableRefs){let i=t.variableList;return e.replace(eR,e=>{let r=e.substring(2,e.length-1),s=null==i?void 0:i[r];return void 0===s?(t.playlistParsingError||(t.playlistParsingError=Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(r,'"'))),e):s})}return e}function eD(t,e,i){let r,s,a=t.variableList;if(a||(t.variableList=a={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{let t=new self.URL(i).searchParams;if(t.has(r))s=t.get(r);else throw Error('"'.concat(r,'" does not match any query parameter in URI: "').concat(i,'"'))}catch(e){t.playlistParsingError||(t.playlistParsingError=Error("EXT-X-DEFINE QUERYPARAM: ".concat(e.message)))}}else r=e.NAME,s=e.VALUE;r in a?t.playlistParsingError||(t.playlistParsingError=Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(r,'"'))):a[r]=s||""}let ek=/^(\d+)x(\d+)$/,e_=/(.+?)=(".*?"|.*?)(?:,|$)/g;class eP{get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){let e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;let i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){let e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){let i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){let i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){let e=ek.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;let r={};for(e_.lastIndex=0;null!==(i=e_.exec(t));){let s=i[1].trim(),a=i[2],n=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,l=!1;if(n)a=a.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(e&&(n||l))a=eb(e,a);else if(!l&&!n)switch(s){case"CLOSED-CAPTIONS":if("NONE"===a)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":F.warn("".concat(t,": attribute ").
1concat(s," is missing quotes"))}r[s]=a}return r}constructor(t,e){"string"==typeof t&&(t=eP.parseAttrList(t,e)),k(this,t)}}class eC{get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){let{tagAnchor:t}=this;return null===t||null===t.programDateTime?(F.warn('Expected tagAnchor Fragment with PDT set for DateRange "'.concat(this.id,'": ').concat(t)),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let t=this._endDate||this._dateAtEnd;if(t)return t;let e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){let t=this.attr.decimalFloatingPoint("DURATION");if(s(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&s(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}constructor(t,e,i=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(r=null==e?void 0:e.tagOrder)?r:i,e){let i=e.attr;for(let e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){F.warn('DATERANGE tag attribute: "'.concat(e,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=e;break}t=k(new eP({}),i,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){let t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);s(t.getTime())&&(this._endDate=t)}}}class eO{reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}let e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&s(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}
1get drift(){let t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let t=this.partList;if(t){let e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}}function ew(t,e){return t.length===e.length&&!t.some((t,i)=>t!==e[i])}function eM(t,e){return!t&&!e||!!t&&!!e&&ew(t,e)}function ex(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function eF(t){switch(t){case"AES-128":case"AES-256":return ec.cbc;case"AES-256-CTR":return ec.ctr;default:throw Error("invalid full segment method ".concat(t))}}function eN(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function eU(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function eB(t){let e=function(t,e,i){let r=t[e];t[e]=t[i],t[i]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function eG(t){let e=t.split(":"),i=null;if("data"===e[0]&&2===e.length){let t=e[1].split(";"),r=t[t.length-1].split(",");if(2===r.length){let e="base64"===r[0],s=r[1];e?(t.splice(-1,1),i=eN(s)):i=function(t){let e=eU(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(s)}}return i}let eK="undefined"!=typeof self?self:void 0;var eV={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},eH={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function eY(t){switch(t){case eH.FAIRPLAY:return eV.FAIRPLAY;case eH.PLAYREADY:return eV.PLAYREADY;case eH.WIDEVINE:return eV.WIDEVINE;case eH.CLEARKEY:return eV.CLEARKEY}}function eW(t){switch(t){case eV.FAIRPLAY:return eH.FAIRPLAY;case eV.PLAYREADY:return eH.PLAYREADY;case eV.WIDEVINE:return eH.WIDEVINE;case eV.CLEARKEY:return eH.CLEARKEY}}function ej(t){let{drmSystems:e,widevineLicenseUrl:i}=t,r=e?[eV.FAIRPLAY,eV.WIDEVINE,eV.PLAYREADY,eV.CLEARKEY].filter(t=>!!e[t]):[];return!r[eV.WIDEVINE]&&i&&r.push(eV.WIDEVINE),r}let eq=null!=eK&&null!=(m=eK.navigator)&&m.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function eX(t){let e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(e)),r=i.substring(i.indexOf("<"),i.length),s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){let t=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(t){let e=eN(t).subarray(0,16);return eB(e),e}}return null}let eQ={};class ez{static clearKeyUriToKeyIdMap(){eQ={}}static setKeyIdForUri(t,e){eQ[t]=e}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&ew(t.keyFormatVersions,this.keyFormatVersions)&&eM(t.iv,this.iv)&&eM(t.keyId,this.keyId)}isSupported(){if(this.method){if(ex(this.method)||"NONE"===this.method)return!0;
1if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case eH.FAIRPLAY:case eH.WIDEVINE:case eH.PLAYREADY:case eH.CLEARKEY:return -1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(ex(this.method)){let e=this.iv;return e||("number"!=typeof t&&(F.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),e=function(t){let e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t)),new ez(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){let t=eQ[this.uri];if(t&&!ew(this.keyId,t)&&ez.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let i=eG(this.uri);if(i)switch(this.keyFormat){case eH.WIDEVINE:if(this.pssh=i,!this.keyId){let t=function(t){let e=[];if(t instanceof ArrayBuffer){let i=t.byteLength,r=0;for(;r+32<i;){let i=function(t){let e=t.getUint32(0),i=t.byteOffset,r=t.byteLength;if(r<e)return{offset:i,size:r};if(1886614376!==t.getUint32(4))return{offset:i,size:e};let s=t.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:e};let a=t.buffer,n=G(new Uint8Array(a,i+12,16)),l=null,o=0;if(0===s)o=28;else{let s=t.getUint32(28);if(!s||r<32+16*s)return{offset:i,size:e};l=[];for(let t=0;t<s;t++)l.push(new Uint8Array(a,i+32+16*t,16));o=32+16*s}if(!o)return{offset:i,size:e};let h=t.getUint32(o);return e-32<h?{offset:i,size:e}:{version:s,systemId:n,kids:l,data:new Uint8Array(a,i+o+4,h),offset:i,size:e}}(new DataView(t,r));e.push(i),r+=i.size}}return e}(i.buffer);if(t.length){var r;let e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=e$(e));break;case eH.PLAYREADY:{let t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(t,e,i){let r,s;if(16!==t.byteLength)throw RangeError("Invalid system id");r=new Uint8Array,s=new Uint8Array;let a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t){for(var e=arguments.length,i=Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];let s=i.length,a=8,n=s;for(;n--;)a+=i[n].byteLength;let l=new Uint8Array(a);for(l[0]=a>>24&255,l[1]=a>>16&255,l[2]=a>>8&255,l[3]=255&a,l.set(t,4),n=0,a=8;n<s;n++)l.set(i[n],a),a+=i[n].byteLength;return l}([112,115,115,104],new Uint8Array([0,0,0,0]),t,s,r,a,i)}(t,0,i),this.keyId=eX(i);break}default:{let t=i.subarray(0,16);if(16!==t.length){let e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t}}if(!this.keyId||16!==this.keyId.byteLength){let t;(t=function(t){let e=null==t?void 0:t[eH.WIDEVINE];return e?e.keyId:null}(e))||(t=e$(e))||(t=eQ[this.uri]),t&&(this.keyId=t,ez.setKeyIdForUri(this.uri,t))}return this}constructor(t,e,i,r=[1],s=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ex(t),null!=a&&a.startsWith("0x")&&(this.keyId=new Uint8Array(K(a)))}}function e$(t){let e=null==t?void 0:t[eH.PLAYREADY];if(e){let t=eG(e.uri);if(t)return eX(t)}return null}let eZ=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,eJ=/#EXT-X-MEDIA:(.*)/g,e0=/^#EXT(?:INF|-X-TARGETDURATION):/m,e1=RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),e2=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class e3{static findGroup(t,e){for(let i=0;i<t.length;i++){let r=t[i];if(r.id===e)return r}}static resolve(t,e){return H.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return e0.test(t)}static parseMasterPlaylist(t,e){var i;let r;let s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:eR.test(t)},a=[];if(eZ.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=Error("no EXTM3U delimiter"),s;for(;null!=(r=eZ.exec(t));)if(r[1]){let t=new eP(r[1],s),n=eb(s,r[2]),l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:e3.resolve(n,e)},o=t.decimalResolution("RESOLUTION");o&&(l.width=o.width,l.height=o.height),e6(t.CODECS,l);let h=t["SUPPLEMENTAL-CODECS"];h&&(l.supplemental={},e6(h,l.supplemental)),null!=(i=l.unknownCodecs)&&i.length||a.push(l),s.levels.push(l)}else if(r[3]){let t=r[3],i=r[4];switch(t){case"SESSION-DATA":{let t=new eP(i,s),e=t["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=t);break}
1case"SESSION-KEY":{let t=e5(i,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):F.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(i,'"'));break}case"DEFINE":{let t=new eP(i,s);eD(s,t,e)}break;case"CONTENT-STEERING":{let t=new eP(i,s);s.contentSteering={uri:e3.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=e8(i)}}let n=a.length>0&&a.length<s.levels.length;return s.levels=n?a:s.levels,0===s.levels.length&&(s.playlistParsingError=Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,i){let r;let s={},a=i.levels,n={AUDIO:a.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:a.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(eJ.lastIndex=0;null!==(r=eJ.exec(t));){let t=new eP(r[1],i),a=t.TYPE;if(a){let i=n[a],r=s[a]||[];s[a]=r;let o=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],d=t.CHANNELS,c=t.CHARACTERISTICS,u=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:l++,groupId:t["GROUP-ID"]||"",name:t.NAME||o||"",type:a,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:o,url:t.URI?e3.resolve(t.URI,e):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=i&&i.length){let t=e3.findGroup(i,f.groupId)||i[0];e9(f,t,"audioCodec"),e9(f,t,"textCodec")}r.push(f)}}return s}static parseLevelPlaylist(t,e,i,r,a,n){var l;let o,h,d,c;let u={url:e},f=new eO(e),g=f.fragments,m=[],p=null,E=0,y=0,v=0,T=0,S=0,A=null,L=new X(r,u),I=-1,R=!1,b=null;if(e1.lastIndex=0,f.m3u8=t,f.hasVariableRefs=eR.test(t),(null==(l=e1.exec(t))?void 0:l[0])!=="#EXTM3U")return f.playlistParsingError=Error("Missing format identifier #EXTM3U"),f;for(;null!==(o=e1.exec(t));){R&&(R=!1,(L=new X(r,u)).playlistOffset=v,L.setStart(v),L.sn=E,L.cc=T,S&&(L.bitrate=S),L.level=i,p&&(L.initSegment=p,p.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),b&&(L.setByteRange(b),b=null)));let t=o[1];if(t){L.duration=parseFloat(t);let e=(" "+o[2]).slice(1);L.title=e||null,L.tagList.push(e?["INF",t,e]:["INF",t])}else if(o[3]){if(s(L.duration)){L.playlistOffset=v,L.setStart(v),d&&ie(L,d,f),L.sn=E,L.level=i,L.cc=T,g.push(L);let t=(" "+o[3]).slice(1);L.relurl=eb(f,t),e7(L,A,m),A=L,v+=L.duration,E++,y=0,R=!0}}else{if(!(o=o[0].match(e2))){F.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<o.length&&void 0===o[h];h++);let t=(" "+o[h]).slice(1),a=(" "+o[h+1]).slice(1),l=o[h+2]?(" "+o[h+2]).slice(1):null;switch(t){case"BYTERANGE":A?L.setByteRange(a,A):L.setByteRange(a);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=a,L.tagList.push(["PROGRAM-DATE-TIME",a]),-1===I&&(I=g.length);break;case"PLAYLIST-TYPE":f.type&&ii(f,t,o),f.type=a.toUpperCase();break;case"MEDIA-SEQUENCE":0!==f.startSN?ii(f,t,o):g.length>0&&ir(f,t,o),E=f.startSN=parseInt(a);break;case"SKIP":{f.skippedSegments&&ii(f,t,o);let e=new eP(a,f),i=e.decimalInteger("SKIPPED-SEGMENTS");if(s(i)){f.skippedSegments+=i;for(let t=i;t--;)g.push(null);E+=i}let r=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(r.split("	")));break}case"TARGETDURATION":0!==f.targetduration&&ii(f,t,o),f.targetduration=Math.max(parseInt(a),1);break;case"VERSION":null!==f.version&&ii(f,t,o),f.version=parseInt(a);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":f.live||ii(f,t,o),f.live=!1;break;case"#":(a||l)&&L.tagList.push(l?[a,l]:[a]);break;case"DISCONTINUITY":T++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([t]);break;case"BITRATE":L.tagList.push([t,a]),s(S=1e3*parseInt(a))?L.bitrate=S:S=0;break;case"DATERANGE":{let t=new eP(a,f),e=new eC(t,f.dateRanges[t.ID],f.dateRangeTagCount);f.dateRangeTagCount++,e.isValid||f.skippedSegments?f.dateRanges[e.id]=e:F.warn('Ignoring invalid DATERANGE tag: "'.concat(a,'"')),L.tagList.push(["EXT-X-DATERANGE",a]);break}case"DEFINE":{let t=new eP(a,f);"IMPORT"in t?function(t,e,i){let r=e.IMPORT;if(i&&r in i){let e=t.variableList;e||(t.variableList=e={}),e[r]=i[r]}else t.playlistParsingError||(t.playlistParsingError=Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(r,'"')))}(f,t,n):eD(f,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==f.startCC?ii(f,t,o):g.length>0&&ir(f,t,o),f.startCC=T=parseInt(a);break;case"KEY":{let t=e5(a,e,f);
1if(t.isSupported()){if("NONE"===t.method){d=void 0;break}d||(d={});let e=d[t.keyFormat];null!=e&&e.matches(t)||(e&&(d=k({},d)),d[t.keyFormat]=t)}else F.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(a,'"'));break}case"START":f.startTimeOffset=e8(a);break;case"MAP":{let t=new eP(a,f);if(L.duration){let e=new X(r,u);it(e,t,i,d),p=e,L.initSegment=p,p.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime)}else{let e=L.byteRangeEndOffset;if(e){let t=L.byteRangeStartOffset;b="".concat(e-t,"@").concat(t)}else b=null;it(L,t,i,d),p=L,R=!0}p.cc=T;break}case"SERVER-CONTROL":c&&ii(f,t,o),c=new eP(a),f.canBlockReload=c.bool("CAN-BLOCK-RELOAD"),f.canSkipUntil=c.optionalFloat("CAN-SKIP-UNTIL",0),f.canSkipDateRanges=f.canSkipUntil>0&&c.bool("CAN-SKIP-DATERANGES"),f.partHoldBack=c.optionalFloat("PART-HOLD-BACK",0),f.holdBack=c.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{f.partTarget&&ii(f,t,o);let e=new eP(a);f.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=f.partList;t||(t=f.partList=[]);let e=y>0?t[t.length-1]:void 0,i=y++,r=new Q(new eP(a,f),L,u,i,e);t.push(r),L.duration+=r.duration;break}case"PRELOAD-HINT":{let t=new eP(a,f);f.preloadHint=t;break}case"RENDITION-REPORT":{let t=new eP(a,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(t);break}default:F.warn("line parsed but not handled: ".concat(o))}}}A&&!A.relurl?(g.pop(),v-=A.duration,f.partList&&(f.fragmentHint=A)):f.partList&&(e7(L,A,m),L.cc=T,f.fragmentHint=L,d&&ie(L,d,f)),f.targetduration||(f.playlistParsingError=Error("Missing Target Duration"));let D=g.length,_=g[0],P=g[D-1];if((v+=f.skippedSegments*f.targetduration)>0&&D&&P){f.averagetargetduration=v/D;let t=P.sn;f.endSN="initSegment"!==t?t:0,f.live||(P.endList=!0),I>0&&(function(t,e){let i=t[e];for(let r=e;r--;){let e=t[r];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(g,I),_&&m.unshift(_))}return f.fragmentHint&&(v+=f.fragmentHint.duration),f.totalduration=v,m.length&&f.dateRangeTagCount&&_&&e4(m,f),f.endCC=T,f}}function e4(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{let r=e.fragments[e.fragments.length-1];t.push(r),i++}}let r=t[i-1],s=e.live?1/0:e.totalduration,a=Object.keys(e.dateRanges);for(let l=a.length;l--;){let o=e.dateRanges[a[l]],h=o.startDate.getTime();o.tagAnchor=r.ref;for(let r=i;r--;){var n;if((null==(n=t[r])?void 0:n.sn)<e.startSN)break;let i=function(t,e,i,r,s){let a=i[r];if(a){let l=a.programDateTime;if(e>=l||0===r){var n;if(e<=l+1e3*(((null==(n=i[r+1])?void 0:n.start)||s)-a.start)){let s=i[r].sn-t.startSN;if(s<0)return -1;let a=t.fragments;if(a.length>i.length){let n=(i[r+1]||a[a.length-1]).sn-t.startSN;for(let t=n;t>s;t--){let i=a[t].programDateTime;if(e>=i&&e<i+1e3*a[t].duration)return t}}return s}}}return -1}(e,h,t,r,s);if(-1!==i){o.tagAnchor=e.fragments[i].ref;break}}}}function e5(t,e,i){var r,s;let a=new eP(t,i),n=null!=(r=a.METHOD)?r:"",l=a.URI,o=a.hexadecimalInteger("IV"),h=a.KEYFORMATVERSIONS,d=null!=(s=a.KEYFORMAT)?s:"identity";return l&&a.IV&&!o&&F.error("Invalid IV: ".concat(a.IV)),new ez(n,l?e3.resolve(l,e):"",d,(h||"1").split("/").map(Number).filter(Number.isFinite),o,a.KEYID)}function e8(t){let e=new eP(t).decimalFloatingPoint("TIME-OFFSET");return s(e)?e:null}function e6(t,e){let i=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{let r=i.filter(e=>ty(e,t));r.length&&(e["".concat(t,"Codec")]=r.map(t=>t.split("/")[0]).join(","),i=i.filter(t=>-1===r.indexOf(t)))}),e.unknownCodecs=i}function e9(t,e,i){let r=e[i];r&&(t[i]=r)}function e7(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function it(t,e,i,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function ie(t,e,i){t.levelkeys=e;let{encryptedFragments:r}=i;(!r.length||r[r.length-1].levelkeys!==e)&&Object.keys(e).some(t=>e[t].isCommonEncryption)&&r.push(t)}function ii(t,e,i){t.playlistParsingError=Error("#EXT-X-".concat(e," must not appear more than once (").concat(i[0],")"))}function ir(t,e,i){t.playlistParsingError=Error("#EXT-X-".concat(e," must appear before the first Media Segment (").concat(i[0],")"))}function is(t,e){let i=e.startPTS;if(s(i)){let r,s=0;e.sn>t.sn?(s=i-t.start,r=t):(s=t.start-i,r=e),r.duration!==s&&r.setDuration(s)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration):e.setStart(Math.max(t.start-e.duration,0))}function ia(t,e,i,r,a,n,l){let o;r-i<=0&&(l.warn("Fragment should have a positive duration",e),r=i+e.duration,n=a+e.duration);let h=i,d=r,c=e.startPTS,u=e.endPTS;if(s(c)){let o=Math.abs(c-i);t&&o>t.totalduration?l.warn("media timestamps and playlist times differ by ".concat(o,"s for level ").concat(e.level," ").concat(t.url)):s(e.deltaPTS)?e.deltaPTS=Math.max(o,e.deltaPTS):e.deltaPTS=o,h=Math.max(i,c),i=Math.min(i,c),a=void 0!==e.startDTS?Math.min(a,e.startDTS):a,d=Math.min(r,u),r=Math.max(r,u),n=void 0!==e.endDTS?Math.max(n,e.endDTS):n}let f=i-e.start;0!==e.start&&e.setStart(i),e.setDuration(r-e.start),e.startPTS=i,e.maxStartPTS=h,e.startDTS=a,e.endPTS=r,e.minEndPTS=d,e.endDTS=n;let g=e.sn;if(!t||g<t.startSN||g>t.endSN)return 0;let m=g-t.startSN,p=t.fragments;for(p[m]=e,o=m;o>0;o--)is(p[o],p[o-1]);for(o=m;o<p.length-1;o++)is(p[o],p[o+1]);return t.fragmentHint&&is(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,f}function il(t,e,i,r,s){return Error("".concat(t," ").concat(s.url,"\nPlaylist starting @").concat(e.startSN,"\n").concat(e.m3u8,"\n\nPlaylist starting @").concat(i.startSN,"\n").concat(i.m3u8))}function io(t,e){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=e.startSN+e.skippedSegments-t.startSN,s=t.fragments,a=r>=0,n=0;if(a&&r<s.length)n=s[r].start;else if(a&&e.startSN===t.endSN+1)n=t.fragmentEnd;else if(a&&i)n=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;n=t.fragmentStart}ih(e,n)}function ih(t,e){if(e){let i=t.fragments;for(let r=t.skippedSegments;r<i.length;r++)i[r].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function id(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,i=1e3*t.targetduration;if(t.updated){let r=t.fragments;if(r.length&&4*i>e){let t=1e3*r[r.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}function ic(t,e,i){if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint)&&r.sn===e?r:e<t.startSN&&i&&i.sn===e?i:null}function iu(t,e,i){return t?ig(t.partList,e,i):null}function ig(t,e,i){if(t)for(let r=t.length;r--;){let s=t[r];
1if(s.index===i&&s.fragment.sn===e)return s}return null}function im(t){t.forEach((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function ip(t){return t.replace(/\?[^?]*$/,"")}function iE(t,e){for(let r=0,s=t.length;r<s;r++){var i;if((null==(i=t[r])?void 0:i.cc)===e)return t[r]}return null}function iy(t,e){let i=t.start+e;t.startPTS=i,t.setStart(i),t.endPTS=i+t.duration}function iv(t,e){let i=e.fragments;for(let e=0,r=i.length;e<r;e++)iy(i[e],t);e.fragmentHint&&iy(e.fragmentHint,t),e.alignedSliding=!0}function iT(t,e){if(!e||!(t.startCC<e.endCC)||!(t.endCC>e.startCC))return;let i=Math.min(e.endCC,t.endCC),r=iE(e.fragments,i),s=iE(t.fragments,i);r&&s&&(F.log("Aligning playlist at start of dicontinuity sequence ".concat(i)),iv(r.start-s.start,t))}function iS(t,e){let i,r;if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;let s=t.fragments,a=e.fragments;if(!s.length||!a.length)return;let n=Math.min(e.endCC,t.endCC);e.startCC<n&&t.startCC<n&&(i=iE(a,n),r=iE(s,n)),i&&r||(r=iE(s,(i=a[Math.floor(a.length/2)]).cc)||s[Math.floor(s.length/2)]);let l=i.programDateTime,o=r.programDateTime;l&&o&&iv((o-l)/1e3-(r.start-i.start),t)}
1function iA(t,e,i){iL(t,e,i),t.addEventListener(e,i)}function iL(t,e,i){t.removeEventListener(e,i)}let iI={toString:function(t){let e="",i=t.length;for(let r=0;r<i;r++)e+="[".concat(t.start(r).toFixed(3),"-").concat(t.end(r).toFixed(3),"]");return e}},iR={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class ib extends eT{registerListeners(){let{hls:t}=this;t.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:t}=this;t.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(h.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===iR.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=iR.STOPPED}get startPositionValue(){let{nextLoadPosition:t,startPosition:e}=this;return -1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;let i=t.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;let s=t.buffered;this.config.maxBufferHole&&s&&s.length>1&&(t=eI.bufferedInfo(s,t.start,0));let a=t.nextStart;if(a&&a>r&&a<e.edge||this.media.currentTime<t.start)return!1;let n=e.partList;if(null!=n&&n.length){let t=n[n.length-1];return eI.isBuffered(this.media,t.start+t.duration/2)}let l=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){let t=this.config.timelineOffset;if(t){var e;return(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t}return 0}onMediaAttached(t,e){let i=this.media=this.mediaBuffer=e.media;iA(i,"seeking",this.onMediaSeeking),iA(i,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===iR.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(t,e){let i=!!e.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),iL(r,"seeking",this.onMediaSeeking),iL(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=iR.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,t=>{let e=t.frag;if(this.fragContextChanged(e)){this.warn("".concat(e.type," sn: ").concat(e.sn).c
1oncat(t.part?" part: "+t.part.index:""," of ").concat(this.fragInfo(e,!1,t.part),") was dropped during download.")),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;let e=this.state,i=t.frag;if(this.fragContextChanged(i)){e!==iR.FRAG_LOADING&&(this.fragCurrent||e!==iR.PARSING)||(this.fragmentTracker.removeFragment(i),this.state=iR.IDLE);return}"payload"in t&&(this.log("Loaded ".concat(i.type," sn: ").concat(i.sn," of ").concat(this.playlistLabel()," ").concat(i.level)),this.hls.trigger(h.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t)}).catch(e=>{this.state!==iR.STOPPED&&this.state!==iR.ERROR&&(this.warn("Frag error: ".concat((null==e?void 0:e.message)||e)),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;let{fragmentTracker:i}=this;if(i.getState(t)===en.APPENDING){let e=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,e),s=Math.max(t.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?t.sn-a.sn:0)||this.reduceMaxBufferLength(s,t.duration))&&i.removeFragment(t)}else(null==(e=this.mediaBuffer)?void 0:e.buffered.length)===0?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===en.PARTIAL&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){let e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){let e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;t-e&&this.hls.trigger(h.BUFFER_FLUSHING,{startOffset:t,endOffset:e,type:i})}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{let e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw Error("init load aborted");return t}).then(t=>{let{hls:e}=this,{frag:i,payload:r}=t,s=i.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&ex(s.method)){let a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,eF(s.method)).catch(t=>{throw e.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t}).then(r=>{let s=self.performance.now();return e.trigger(h.FRAG_DECRYPTED,{frag:i,payload:r,stats:{tstart:a,tdecrypt:s}}),t.payload=r,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==iR.STOPPED&&this.state!==iR.ERROR&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){let{levels:e}=this;if(!e)throw Error("init load aborted, missing levels");let i=t.frag.stats;this.state!==iR.STOPPED&&(this.state=iR.IDLE),t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var i,r;let s=t.tracks;if(s&&!e.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let t=this.media,i=Error("Encrypted track with no key in ".concat(this.fragInfo(e)," (media ").concat(t?"attached mediaKeys: "+t.mediaKeys:"detached",")"));return this.warn(i.message),!!t&&!t.mediaKeys&&(this.hls.trigger(h.ERROR,{type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){let{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(t.type," sn: ").concat(t.sn).concat(e?" part: "+e.index:""," of ").concat(this.fragInfo(t,!1,e)," > buffer:").concat(i?iI.toString(eI.getBuffered(i)):"(detached)",")")),q(t)){var r;if(t.type!==R.SUBTITLE){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t])){this.state=iR.IDLE;return}}let e=null==(r=this.levels)?void 0:r[t.level];null!=e&&e.fragmentError&&(this.log("Resetting level fragment error count of ".concat(e.fragmentError," on frag buffered")),e.fragmentError=0)}this.state=iR.IDLE}_handleFragmentLoadComplete(t){let{transmuxer:e}=this;if(!e)return;let{frag:i,part:r,partsLoaded:s}=t,a=!s||0===s.length||s.some(t=>!t),n=new eS(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);e.flush(n)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e){var i,r;let a,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,l=arguments.length>3?arguments[3]:void 0;this.fragCurrent=t;let o=e.details;if(!this.levels||!o)throw Error("frag load aborted, missing level".concat(o?"":" detail","s"));let d=null;if(t.encrypted&&!(null!=(i=t.decryptdata)&&i.key)){if(this.log("Loading key for ".concat(t.sn," of [").concat(o.startSN,"-").concat(o.endSN,"], ").
1concat(this.playlistLabel()," ").concat(t.level)),this.state=iR.KEY_LOADING,this.fragCurrent=t,d=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(h.KEY_LOADED,t),this.state===iR.KEY_LOADING&&(this.state=iR.IDLE),t}),this.hls.trigger(h.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else!t.encrypted&&(d=this.keyLoader.loadClear(t,o.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");let c=this.fragPrevious;if(q(t)&&(!c||t.sn!==c.sn)){let i=this.shouldLoadParts(e.details,t.end);i!==this.loadingParts&&(this.log("LL-Part loading ".concat(i?"ON":"OFF"," loading sn ").concat(null==c?void 0:c.sn,"->").concat(t.sn)),this.loadingParts=i)}if(n=Math.max(t.start,n||0),this.loadingParts&&q(t)){let i=o.partList;if(i&&l){n>o.fragmentEnd&&o.fragmentHint&&(t=o.fragmentHint);let r=this.getNextPart(i,t,n);if(r>-1){let s;let a=i[r];return(t=this.fragCurrent=a.fragment,this.log("Loading ".concat(t.type," sn: ").concat(t.sn," part: ").concat(a.index," (").concat(r,"/").concat(i.length-1,") of ").concat(this.fragInfo(t,!1,a),") cc: ").concat(t.cc," [").concat(o.startSN,"-").concat(o.endSN,"], target: ").concat(parseFloat(n.toFixed(3)))),this.nextLoadPosition=a.start+a.duration,this.state=iR.FRAG_LOADING,s=d?d.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(t,a,e,l)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,a,e,l).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(h.FRAG_LOADING,{frag:t,part:a,targetBufferTime:n}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts")):s}if(!t.url||this.loadedEndOfParts(i,n))return Promise.resolve(null)}}if(q(t)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(n.toFixed(2)," Check buffer at sn: ").concat(t.sn," loaded parts: ").concat(null==(r=o.partList)?void 0:r.filter(t=>t.loaded).map(t=>"[".concat(t.start,"-").concat(t.end,"]")))),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log("Loading ".concat(t.type," sn: ").concat(t.sn," of ").concat(this.fragInfo(t,!1),") cc: ").concat(t.cc," ").concat("["+o.startSN+"-"+o.endSN+"]",", target: ").concat(parseFloat(n.toFixed(3)))),s(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=iR.FRAG_LOADING;let u=this.config.progressive;return(a=u&&d?d.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,l)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,u?l:void 0),d]).then(t=>{let[e]=t;return!u&&l&&l(e),e}).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(h.FRAG_LOADING,{frag:t,targetBufferTime:n}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING")):a}doFragPartsLoad(t,e,i,r){return new Promise((s,a)=>{var n;let l=[],o=null==(n=i.details)?void 0:n.partList,d=e=>{this.fragmentLoader.loadPart(t,e,r).then(r=>{l[e.index]=r;let a=r.part;this.hls.trigger(h.FRAG_LOADED,r);let n=iu(i.details,t.sn,e.index+1)||ig(o,t.sn,e.index+1);if(!n)return s({frag:t,part:a,partsLoaded:l});d(n)}).catch(a)};d(e)})}handleFragLoadError(t){if("data"in t){let e=t.data;e.frag&&e.details===o.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===l.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(h.ERROR,e)}else this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){let e=this.getCurrentContext(t);if(!e||this.state!==iR.PARSING){this.fragCurrent||this.state===iR.STOPPED||this.state===iR.ERROR||(this.state=iR.IDLE);return}let{frag:i,part:r,level:s}=e,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let n=this.getLevelDetails(),l=n&&i.sn>n.endSN||this.shouldLoadParts(n,i.end);l!==this.loadingParts&&(this.log("LL-Part loading ".concat(l?"ON":"OFF"," after parsing segment ending @").concat(i.end.toFixed(2))),this.loadingParts=l),this.updateLevelTiming(i,r,s,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i,r;let s=t.partList[0];if(s.fragment.type===R.SUBTITLE)return!1;if(e>=s.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}return!1}getCurrentContext(t){let{levels:e,fragCurrent:i}=this,{level:r,sn:s,part:a}=t;if(!(null!=e&&e[r]))return this.warn("Levels object was unset while buffering fragment ".concat(s," of ").concat(this.playlistLabel()," ").concat(r,". The current chunk will not be buffered.")),null;let n=e[r],l=n.details,o=a>-1?iu(l,s,a):null,h=o?o.fragment:ic(l,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:o,level:n}):null}
1bufferFragmentData(t,e,i,r,s){if(this.state!==iR.PARSING)return;let{data1:a,data2:n}=t,l=a;if(n&&(l=tc(a,n)),!l.length)return;let o=this.initPTS[e.cc],d=o?-o.baseTime/o.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:r,offset:d,parent:e.type,data:l};if(this.hls.trigger(h.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(s)return;this.flushBufferGap(e)}}flushBufferGap(t){let e=this.media;if(!e)return;if(!eI.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}let i=e.currentTime,r=eI.bufferInfo(e,i,0),s=t.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),n=Math.max(Math.min(t.start-a,r.end-a),i+a);t.start-n>a&&this.flushMainBuffer(n,t.start)}getFwdBufferInfo(t,e){var i;let r=this.getLoadPosition();if(!s(r))return null;let a=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,r,e,a)}getFwdBufferInfoAtPos(t,e,i,r){let s=eI.bufferInfo(t,e,r);if(0===s.len&&void 0!==s.nextStart){let a=this.fragmentTracker.getBufferedFrag(e,i);if(a&&(s.nextStart<=a.end||a.gap)){let i=Math.max(Math.min(s.nextStart,a.end)-e,r);return eI.bufferInfo(t,e,i)}}return s}getMaxBufferLength(t){let{config:e}=this;return Math.min(t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){let i=this.config,r=Math.max(Math.min(t-e,i.maxBufferLength),e),s=Math.max(t-3*e,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn("Reduce max buffer length to ".concat(s,"s")),!0)}getAppendedFrag(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:R.MAIN,i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){let i=e.fragments,r=i.length;if(!r)return null;let{config:s}=this,a=i[0].start,n=s.lowLatencyMode&&!!e.partList,l=null;if(e.live){let i=s.initialLiveManifestSize;if(r<i)return this.warn("Not enough fragments to start playback (have: ".concat(r,", need: ").concat(i,")")),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<a){var o;n&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(e);let i=this.hls.startPosition,r=this.hls.liveSyncPosition,s=l?(-1!==i&&i>=a?i:r)||l.start:t;this.log("Setting startPosition to ".concat(s," to match start frag at live edge. mainStart: ").concat(i," liveSyncPosition: ").concat(r," frag.start: ").concat(null==(o=l)?void 0:o.start)),this.startPosition=this.nextLoadPosition=s}}else t<=a&&(l=i[0]);if(!l){let i=this.loadingParts?e.partEnd:e.fragmentEnd;l=this.getFragmentAtPosition(t,i,e)}let h=this.filterReplacedPrimary(l,e);if(!h&&l){let t=l.sn-e.startSN;h=this.filterReplacedPrimary(i[t+1]||null,e)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(t,e){let i=this.fragmentTracker.getState(t);return(i===en.OK||i===en.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,r,s){let a=null;if(t.gap&&(a=this.getNextFragment(this.nextLoadPosition,e))&&!a.gap&&i.nextStart){let t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==t&&i.len+t.len>=s){let t=a.sn;return this.loopSn!==t&&(this.log('buffer full after gaps in "'.concat(r,'" playlist starting at sn: ').concat(t)),this.loopSn=t),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(iD(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(iD(this.config)&&t.type!==R.SUBTITLE){let i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){let i=r.event;if(i){if(i.appendInPlace||Math.abs(t.start-r.start)>1||0===r.start)return null}else if(t.end<=r.start&&(null==e?void 0:e.live)===!1||t.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||t.start-r.end>1))return null}let s=null==i?void 0:i.playerQueue;if(s)for(let e=s.length;e--;){let i=s[e].interstitial;if(i.appendInPlace&&t.start>=i.startTime&&t.end<=i.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let r=-1,s=!1,a=!0;for(let n=0,l=t.length;n<l;n++){let l=t[n];
1if(a=a&&!l.independent,r>-1&&i<l.start)break;let o=l.loaded;o?r=-1:(s||(l.independent||a)&&l.fragment===e)&&(l.fragment!==e&&this.warn("Need buffer at ".concat(i," but next unloaded part starts at ").concat(l.start)),r=n),s=o}return r}loadedEndOfParts(t,e){let i;for(let r=t.length;r--&&(i=t[r]).loaded;)if(e>i.start)return!0;return!1}getInitialLiveFragment(t){let e=t.fragments,i=this.fragPrevious,r=null;if(i){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(i.programDateTime)),r=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!s(e)||e<(t[0].programDateTime||0)||e>=(t[t.length-1].endProgramDateTime||0))return null;for(let r=0;r<t.length;++r){let s=t[r];if(function(t,e,i){let r=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>t}(e,i,s))return s}return null}(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let s=i.sn+1;if(s>=t.startSN&&s<=t.endSN){let a=e[s-t.startSN];i.cc===a.cc&&(r=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(r.sn)))}!r&&(r=t3(t,i.cc,i.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(r.sn))}}else{let e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,i){let r;let{config:s}=this,{fragPrevious:a}=this,{fragments:n,endSN:l}=i,{fragmentHint:o}=i,{maxFragLookUpTolerance:h}=s,d=i.partList,c=!!(this.loadingParts&&null!=d&&d.length&&o);if(c&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),l=o.sn),t<e){var u;let i=t<this.lastCurrentTime||t>e-h||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:h;r=t1(a,n,t,i)}else r=n[n.length-1];if(r){let t=r.sn-i.startSN,e=this.fragmentTracker.getState(r);if((e===en.OK||e===en.PARTIAL&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!c||d[0].fragment.sn>r.sn||!i.live)&&r.level===a.level){let e=n[t+1];r=r.sn<l&&this.fragmentTracker.getState(e)!==en.OK?e:null}}return r}alignPlaylists(t,e,i){let r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let a=t.fragmentStart,n=t.alignedSliding&&s(a);if(!e||!n&&!a){i&&(iT(t,i),t.alignedSliding||iS(t,i),t.alignedSliding||t.skippedSegments||io(i,t,!1));let s=t.fragmentStart;return this.log("Live playlist sliding: ".concat(s.toFixed(2)," start-sn: ").concat(e?e.startSN:"na","->").concat(t.startSN," fragments: ").concat(r)),s}return a}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let i=this.startPosition;i<e&&(i=-1);let r=this.timelineOffset;if(-1===i){let a=null!==this.startTimeOffset,n=a?this.startTimeOffset:t.startTimeOffset;null!==n&&s(n)?(i=e+n,n<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log("Setting startPosition to ".concat(i," for start time offset ").concat(n," found in ").concat(a?"multivariant":"media"," playlist")),this.startPosition=i):t.live?(i=this.hls.liveSyncPosition||e,this.log("Setting startPosition to -1 to start at live edge ".concat(i)),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}getLoadPosition(){var t;let{media:e}=this,i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&q(t)&&t.stats.aborted&&(this.log("Fragment ".concat(t.sn).concat(e?" part "+e.index:""," of ").concat(this.playlistLabel()," ").concat(t.level," was aborted")),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===iR.FRAG_LOADING_WAITING_RETRY)||(this.state=iR.IDLE)}onFragmentOrKeyLoadError(t,e){var i,r,s;if(e.chunkMeta&&!e.frag){let t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}let a=e.frag;if(!a||a.type!==t||!this.levels)return;if(this.fragContextChanged(a)){this.warn("Frag load error must match current frag to retry ".concat(a.url," > ").concat(null==(r=this.fragCurrent)?void 0:r.url));return}let n=e.details===o.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(a,!0);let l=e.errorAction;if(!l){this.state=iR.ERROR;return}let{action:h,flags:d,retryCount:c=0,retryConfig:u}=l,f=!!u,g=f&&h===ei.RetryRequest,m=f&&!l.resolved&&d===er.MoveAllAlternatesMatchingHost,p=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!g&&m&&q(a)&&!a.endList&&p&&!t8(e))this.resetFragmentErrors(t),this.treatAsGap(a),l.resolved=!0;else if((g||m)&&c<u.maxNumRetry){let i=ee(null==(s=e.response)?void 0:s.code),r=t9(u,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=iR.FRAG_LOADING_WAITING_RETRY,l.resolved=!0,i){this.log("Waiting for connection (offline)"),this.retryDate=1/0,e.reason="offline";return}this.warn("Fragment ".concat(a.sn," of ").concat(t," ").concat(a.level," errored with ").concat(e.details,", retrying loading ").concat(c+1,"/").concat(u.maxNumRetry," in ").concat(r,"ms"))}else if(u){if(this.resetFragmentErrors(t),c<u.maxNumRetry)n||h===ei.RemoveAlternatePermanently||(l.resolved=!0);else{this.warn("".concat(e.details," reached or exceeded max retry (").concat(c,")"));return}}else h===ei.SendAlternateToPenaltyBox?this.state=iR.WAITING_LEVEL:this.state=iR.ERROR;this.tickImmediate()}checkRetryDate(){let t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!ee(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=iR.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===iR.PARSING||this.state===iR.PARSED){let e=t.frag,i=t.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==e?void 0:e.duration)||10);let a=!s;return a&&this.warn("Buffer full error while media.currentTime (".concat(this.getLoadPosition(),") is not buffered, flush ").concat(i," buffer")),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(t){t===R.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==iR.STOPPED&&(this.state=iR.IDLE)}afterBufferFlushed(t,e,i){if(!t)return;let r=eI.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,i),this.state===iR.ENDED&&this.resetLoadingState()}
1resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==iR.STOPPED&&(this.state=iR.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log("Loading context changed while buffering sn ".concat(t.sn," of ").concat(this.playlistLabel()," ").concat(-1===t.level?"<removed>":t.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,r){let s=i.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((e,a)=>{let n=t.elementaryStreams[a];if(n){let l=n.endPTS-n.startPTS;if(l<=0)return this.warn("Could not parse fragment ".concat(t.sn," ").concat(a," duration reliably (").concat(l,")")),e||!1;let o=r?0:ia(s,t,n.startPTS,n.endPTS,n.startDTS,n.endDTS,this);return this.hls.trigger(h.LEVEL_PTS_UPDATED,{details:s,level:i,drift:
1o,type:a,frag:t,start:n.startPTS,end:n.endPTS}),!0}return e},!1)){var a;if(0===i.fragmentError&&this.treatAsGap(t,i),(null==(a=this.transmuxer)?void 0:a.error)===null){let e=Error("Found no media in fragment ".concat(t.sn," of ").concat(this.playlistLabel()," ").concat(t.level," resetting transmuxer to fallback to playlist timing"));if(this.warn(e.message),this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:"Found no media in msn ".concat(t.sn," of ").concat(this.playlistLabel(),' "').concat(i.url,'"')}),!this.hls)return;this.resetTransmuxer()}}this.state=iR.PARSED,this.log("Parsed ".concat(t.type," sn: ").concat(t.sn).concat(e?" part: "+e.index:""," of ").concat(this.fragInfo(t,!1,e),")")),this.hls.trigger(h.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===R.MAIN?"level":"track"}fragInfo(t){var e,i;let r=!(arguments.length>1)||void 0===arguments[1]||arguments[1],s=arguments.length>2?arguments[2]:void 0;return"".concat(this.playlistLabel()," ").concat(t.level," (").concat(s?"part":"frag",":[").concat((null!=(e=r&&!s?t.startPTS:(s||t).start)?e:NaN).toFixed(3),"-").concat((null!=(i=r&&!s?t.endPTS:(s||t).end)?i:NaN).toFixed(3),"]").concat(s&&"main"===t.type?"INDEPENDENT="+(s.independent?"YES":"NO"):"")}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){let e=this._state;e!==t&&(this._state=t,this.log("".concat(e,"->").concat(t)))}get state(){return this._state}constructor(t,e,i,r,a){super(r,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=iR.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:t,fragCurrent:e,media:i,mediaBuffer:r,state:a}=this,n=i?i.currentTime:0,l=eI.bufferInfo(r||i,n,t.maxBufferHole),o=!l.len;if(this.log("Media seeking to ".concat(s(n)?n.toFixed(3):n,", state: ").concat(a,", ").concat(o?"out of":"in"," buffer")),this.state===iR.ENDED)this.resetLoadingState();else if(e){let i=t.maxFragLookUpTolerance,r=e.start-i,s=e.start+e.duration+i;if(o||s<l.start||r>l.end){let t=n>s;(n<r||t)&&(t&&e.loader&&(this.log("Cancelling fragment load for seek (sn: ".concat(e.sn,")")),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts)){let t=Math.max(l.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log("LL-Part loading ON after seeking to ".concat(n.toFixed(2)," with buffer @").concat(t.toFixed(2))),this.loadingParts=e)}!this.hls.hasEnoughToStart&&(this.log("Setting ".concat(o?"startPosition":"nextLoadPosition"," to ").concat(n," for seek without enough to start")),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===iR.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=a,this.hls=t,this.fragmentLoader=new ep(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new em(t.config)}}function iD(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class ik{push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){let t;let{chunks:e,dataLength:i}=this;return e.length?(t=1===e.length?e[0]:function(t,e){let i=new Uint8Array(e),r=0;for(let e=0;e<t.length;e++){let s=t[e];i.set(s,r),r+=s.length}return i}(e,i),this.reset(),t):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}constructor(){this.chunks=[],this.dataLength=0}}var i_={exports:{}},iP=(L||(L=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function r(){}function s(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function a(t,e,r,a,n){if("function"!=typeof r)throw TypeError("The listener must be a function");var l=new s(r,a||t,n),o=i?i+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],l]:t._events[o].push(l):(t._events[o]=l,t._eventsCount++),t}function n(t,e){0==--t._eventsCount?t._events=new r:delete t._events[e]}function l(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(i=!1)),l.prototype.eventNames=function(){var t,r,s=[];if(0===this._eventsCount)return s;for(r in t=this._events)e.call(t,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(t)):s},l.prototype.listeners=function(t){var e=i?i+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,a=r.length,n=Array(a);s<a;s++)n[s]=r[s].fn;return n},l.prototype.listenerCount=function(t){var e=i?i+t:t,r=this._events[e];return r?r.fn?1:r.length:0},l.prototype.emit=function(t,e,r,s,a,n){var l=i?i+t:t;if(!this._events[l])return!1;var o,h,d=this._events[l],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,r),!0;case 4:return d.fn.call(d.context,e,r,s),!0;case 5:return d.fn.call(d.context,e,r,s,a),!0;case 6:return d.fn.call(d.context,e,r,s,a,n),!0}for(h=1,o=Array(c-1);h<c;h++)o[h-1]=arguments[h];d.fn.apply(d.context,o)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h
1].context);break;case 2:d[h].fn.call(d[h].context,e);break;case 3:d[h].fn.call(d[h].context,e,r);break;case 4:d[h].fn.call(d[h].context,e,r,s);break;default:if(!o)for(u=1,o=Array(c-1);u<c;u++)o[u-1]=arguments[u];d[h].fn.apply(d[h].context,o)}}return!0},l.prototype.on=function(t,e,i){return a(this,t,e,i,!1)},l.prototype.once=function(t,e,i){return a(this,t,e,i,!0)},l.prototype.removeListener=function(t,e,r,s){var a=i?i+t:t;if(!this._events[a])return this;if(!e)return n(this,a),this;var l=this._events[a];if(l.fn)l.fn!==e||s&&!l.once||r&&l.context!==r||n(this,a);else{for(var o=0,h=[],d=l.length;o<d;o++)(l[o].fn!==e||s&&!l[o].once||r&&l[o].context!==r)&&h.push(l[o]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},l.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&n(this,e)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=i,l.EventEmitter=l,t.exports=l}(i_)),(p=i_.exports)&&p.__esModule&&Object.prototype.hasOwnProperty.call(p,"default"))?p.default:p;let iC="1.6.13",iO={};function iw(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function iM(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function ix(t,e){return(127&t[e])<<21|(127&t[e+1])<<14|(127&t[e+2])<<7|127&t[e+3]}function iF(t,e){let i=e,r=0;for(;iM(t,e);)r+=10+ix(t,e+6),iw(t,e+10)&&(r+=10),e+=r;if(r>0)return t.subarray(i,i+r)}function iN(t,e){return 255===t[e]&&(246&t[e+1])==240}function iU(t,e){return 1&t[e+1]?7:9}function iB(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function iG(t,e){return e+1<t.length&&iN(t,e)}function iK(t,e,i,r,s){if(!t.samplerate){let a=function(t,e,i,r){let s=e[i+2],a=s>>2&15;if(a>12){let e=Error("invalid ADTS sampling index:".concat(a));t.emit(h.ERROR,h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message});return}let n=(s>>6&3)+1,d=e[i+3]>>6&3|(1&s)<<2,c="mp4a.40."+n,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],f=a;(5===n||29===n)&&(f-=3);let g=[n<<3|(14&f)>>1,(1&f)<<7|d<<3];return F.log("manifest codec:".concat(r,", parsed codec:").concat(c,", channels:").concat(d,", rate:").concat(u," (ADTS object type:").concat(n," sampling index:").concat(a,")")),{config:g,samplerate:u,channelCount:d,codec:c,parsedCodec:c,manifestCodec:r}}(e,i,r,s);a&&k(t,a)}}function iV(t,e,i,r,s){let a;let n=r+9216e4/t.samplerate*s,l=function(t,e){let i=iU(t,e);if(e+i<=t.length){let r=iB(t,e)-i;if(r>0)return{headerLength:i,frameLength:r}}}(e,i);if(l){let{frameLength:r,headerLength:s}=l,o=s+r,h=Math.max(0,i+o-e.length);h?(a=new Uint8Array(o-s)).set(e.subarray(i+s,e.length),0):a=e.subarray(i+s,i+o);let d={unit:a,pts:n};return h||t.samples.push(d),{sample:d,length:o,missing:h}}let o=e.length-i;return(a=new Uint8Array(o)).set(e.subarray(i,e.length),0),{sample:{unit:a,pts:n},length:o,missing:-1}}function iH(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0;return function(t,e,i,r){let s=t instanceof ArrayBuffer?t:t.buffer,a=1;"BYTES_PER_ELEMENT"in r&&(a=r.BYTES_PER_ELEMENT);let n=t&&t.buffer instanceof ArrayBuffer&&void 0!==t.byteLength&&void 0!==t.byteOffset?t.byteOffset:0,l=(n+t.byteLength)/a,o=Math.floor(Math.max(0,Math.min((n+e)/a,l))),h=Math.floor(Math.min(o+Math.max(i,0),l));return new r(s,o,h-o)}(t,e,i,Uint8Array)}function iY(t){let e=0,i=[];for(;iM(t,e);){let r=ix(t,e+6);t[e+5]>>6&1&&(e+=10);let s=(e+=10)+r;for(;e+10<s;){let r=function(t){let e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=ix(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}(t.subarray(e)),s="PRIV"===r.type?function(t){if(t.size<2)return;let e=B(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(r):"W"===r.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1,i=B(t.data.subarray(e),!0);e+=i.length+1;let r=B(t.data.subarray(e));return{key:t.type,info:i,data:r}}let e=B(t.data);return{key:t.type,info:"",data:e}}(r):"APIC"===r.type?function(t){let e;let i={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0]){console.log("Ignore frame with unrecognized character encoding");return}let r=t.data.subarray(1).indexOf(0);if(-1===r)return;let s=B(iH(t.data,1,r)),a=t.data[2+r],n=t.data.subarray(3+r).indexOf(0);if(-1===n)return;
1let l=B(iH(t.data,3+r,n));if("-->"===s)e=B(iH(t.data,4+r+n));else{var o;e=(o=t.data.subarray(4+r+n))instanceof ArrayBuffer?o:0==o.byteOffset&&o.byteLength==o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer}return i.mimeType=s,i.pictureType=a,i.description=l,i.data=e,i}(r):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1,i=B(t.data.subarray(e),!0);e+=i.length+1;let r=B(t.data.subarray(e));return{key:t.type,info:i,data:r}}let e=B(t.data.subarray(1));return{key:t.type,info:"",data:e}}(r);s&&i.push(s),e+=r.size+10}iw(t,e)&&(e+=10)}return i}function iW(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function ij(t){let e=iY(t);for(let t=0;t<e.length;t++){let i=e[t];if(iW(i))return function(t){if(8===t.data.byteLength){let e=new Uint8Array(t.data),i=1&e[3],r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}(i)}}let iq=((E={}).audioId3="org.id3",E.dateRange="com.apple.quicktime.HLS",E.emsg="https://aomedia.org/emsg/ID3",E.misbklv="urn:misb:KLV:bin:1910.1",E);function iX(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4;return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class iQ{resetInitSegment(t,e,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){let i;this.cachedData&&(t=tc(this.cachedData,t),this.cachedData=null);let r=iF(t,0),a=r?r.length:0,n=this._audioTrack,l=this._id3Track,o=r?ij(r):void 0,h=t.length;for((null===this.basePTS||0===this.frameIndex&&s(o))&&(this.basePTS=iz(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:iq.audioId3,duration:Number.POSITIVE_INFINITY});a<h;){if(this.canParse(t,a)){let e=this.appendFrame(n,t,a);e?(this.frameIndex++,this.lastPTS=e.sample.pts,a+=e.length,i=a):a=h}else{var d,c;iM(d=t,c=a)&&ix(d,c+6)+10<=d.length-c?(r=iF(t,a),l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:iq.audioId3,duration:Number.POSITIVE_INFINITY}),a+=r.length,i=a):a++}if(a===h&&i!==h){let e=t.slice(i);this.cachedData?this.cachedData=tc(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:iX(),id3Track:l,textTrack:iX()}}demuxSampleAes(t,e,i){return Promise.reject(Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}flush(t){let e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:iX(),id3Track:this._id3Track,textTrack:iX()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}}let iz=(t,e,i)=>s(t)?90*t:9e4*e+(i?9e4*i.baseTime/i.timescale:0),i$=null,iZ=[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],iJ=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],i0=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],i1=[0,1,1,4];function i2(t,e,i,r,s){if(i+24>e.length)return;let a=i3(e,i);if(a&&i+a.frameLength<=e.length){let n=r+9e4*a.samplesPerFrame/a.sampleRate*s,l={unit:e.subarray(i,i+a.frameLength),pts:n,dts:n};return t.config=[],t.channelCount=a.channelCount,t.samplerate=a.sampleRate,t.samples.push(l),{sample:l,length:a.frameLength,missing:0}}}function i3(t,e){let i=t[e+1]>>3&3,r=t[e+1]>>1&3,s=t[e+2]>>4&15,a=t[e+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==a){let n=t[e+2]>>1&1,l=t[e+3]>>6,o=1e3*iZ[14*(3===i?3-r:3===r?3:4)+s-1],h=iJ[3*(3===i?0:2===i?1:2)+a],d=i0[i][r],c=i1[r],u=Math.floor(d*o/h+n)*c;if(null===i$){let t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);i$=t?parseInt(t[1]):0}return i$&&i$<=87&&2===r&&o>=224e3&&0===l&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:3===l?1:2,frameLength:u,samplesPerFrame:8*d*c}}}function i4(t,e){return 255===t[e]&&(224&t[e+1])==224&&(6&t[e+1])!=0}function i5(t,e){return e+1<t.length&&i4(t,e)}function i8(t,e){if(e+1<t.length&&i4(t,e)){let i=i3(t,e),r=4;null!=i&&i.frameLength&&(r=i.frameLength);let s=e+r;return s===t.length||i5(t,s)}return!1}class i6 extends iQ{resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;let i=iF(t,0),r=(null==i?void 0:i.length)||0;if(i8(t,r))return!1;for(let i=t.length;r<i;r++)if(function(t,e){if(iG(t,e)){let i=iU(t,e);if(e+i>=t.length)return!1;let r=iB(t,e);if(r<=i)return!1;let s=e+r;return s===t.length||iG(t,s)}return!1}(t,r))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return e+5<t.length&&iN(t,e)&&iB(t,e)<=t.length-e}appendFrame(t,e,i){iK(t,this.observer,e,i,t.manifestCodec);
1let r=iV(t,e,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}}let i9=(t,e)=>{let i=0,r=5;e+=5;let s=new Uint32Array(1),a=new Uint32Array(1),n=new Uint8Array(1);for(;r>0;){n[0]=t[e];let l=Math.min(r,8),o=8-l;a[0]=4278190080>>>24+o<<o,s[0]=(n[0]&a[0])>>o,i=i?i<<l|s[0]:s[0],e+=1,r-=l}return i};class i7 extends iQ{resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){let r=rt(t,e,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:t.samples[t.samples.length-1],length:r,missing:0}}static probe(t){if(!t)return!1;let e=iF(t,0);if(!e)return!1;let i=e.length;return!!(11===t[i]&&119===t[i+1]&&void 0!==ij(e)&&16>i9(t,i))}constructor(t){super(),this.observer=void 0,this.observer=t}}function rt(t,e,i,r,s){if(i+8>e.length||11!==e[i]||119!==e[i+1])return -1;let a=e[i+4]>>6;if(a>=3)return -1;let n=[48e3,44100,32e3][a],l=63&e[i+4],o=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*l+a];if(i+o>e.length)return -1;let h=e[i+6]>>5,d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));let c=(e[i+6]<<8|e[i+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([a<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|l>>4,l<<4&224]),p=e.subarray(i,i+o);return t.config=m,t.channelCount=u,t.samplerate=n,t.samples.push({unit:p,pts:r+1536/n*9e4*s}),o}class re extends iQ{resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;let e=iF(t,0),i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==ij(e)&&16>=i9(t,i))return!1;for(let e=t.length;i<e;i++)if(i8(t,i))return F.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return i4(t,e)&&4<=t.length-e}appendFrame(t,e,i){if(null!==this.basePTS)return i2(t,e,i,this.basePTS,this.frameIndex)}}let ri=/\/emsg[-/]ID3/i;class rr{resetTimeStamp(){}resetInitSegment(t,e,i,r){let s=this.videoTrack=iX("video",1),a=this.audioTrack=iX("audio",1),n=this.txtTrack=iX("text",1);if(this.id3Track=iX("id3",1),this.timeOffset=0,!(null!=t&&t.byteLength))return;let l=ts(t);if(l.video){let{id:t,timescale:e,codec:i,supplemental:r}=l.video;s.id=t,s.timescale=n.timescale=e,s.codec=i,s.supplemental=r}if(l.audio){let{id:t,timescale:e,codec:i}=l.audio;a.id=t,a.timescale=e,a.codec=i}n.id=4,s.sampleDuration=0,s.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(t){return function(t){let e=t.byteLength;for(let i=0;i<e;){let r=tt(t,i);if(r>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=r>1?i+r:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=tc(this.remainderData,t));let e=function(t){let e={valid:null,remainder:null},i=tr(t,["moof"]);if(i.length<2)return e.remainder=t,e;let r=i[i.length-1];return e.valid=t.slice(0,r.byteOffset-8),e.remainder=t.slice(r.byteOffset-8),e}(i);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=i;let a=this.extractID3Track(r,e);return s.samples=tu(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(e,this.timeOffset);return i.samples=tu(t,e),{videoTrack:e,audioTrack:iX(),id3Track:r,textTrack:iX()}}extractID3Track(t,e){let i=this.id3Track;if(t.samples.length){let r=tr(t.samples,["emsg"]);r&&r.forEach(t=>{let r=function(t){let e=t[0],i="",r="",s=0,n=0,l=0,o=0,h=0,d=0;if(0===e){for(;"\x00"!==Z(t.subarray(d,d+1));)i+=Z(t.subarray(d,d+1)),d+=1;for(i+=Z(t.subarray(d,d+1)),d+=1;"\x00"!==Z(t.subarray(d,d+1));)r+=Z(t.subarray(d,d+1)),d+=1;r+=Z(t.subarray(d,d+1)),d+=1,s=tt(t,12),n=tt(t,16),o=tt(t,20),h=tt(t,24),d=28}else if(1===e){d+=4,s=tt(t,d);let e=tt(t,d+=4),n=tt(t,d+=4);for(d+=4,a(l=4294967296*e+n)||(l=Number.MAX_SAFE_INTEGER,F.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=tt(t,d),d+=4,h=tt(t,d),d+=4;"\x00"!==Z(t.subarray(d,d+1));)i+=Z(t.subarray(d,d+1)),d+=1;for(i+=Z(t.subarray(d,d+1)),d+=1;"\x00"!==Z(t.subarray(d,d+1));)r+=Z(t.subarray(d,d+1)),d+=1;r+=Z(t.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:l,presentationTimeDelta:n,eventDuration:o,id:h,payload:t.subarray(d,t.byteLength)}}(t);if(ri.test(r.schemeIdUri)){let t=rs(r,e),s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);let a=r.payload;i.samples.push({data:a,len:a.byteLength,dts:t,pts:t,type:iq.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let t=rs(r,e);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:t,pts:t,type:iq.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(t,e,i){return Promise.reject(Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}}function rs(t,e){return s(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class ra{decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,ec.cbc)}decryptAacSample(t,e,i){let r=t[e].unit;if(r.length<=16)return;let s=r.subarray(16,r.length-r.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then(s=>{let a=new Uint8Array(s);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length){i();return}if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){let e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e),r=0;for(let e=32;e<t.length-16;e+=160,r+=16)i.set(t.subarray(e,e+16),r);return i}getAvcDecryptedUnit(t,e){let i=new Uint8Array(e),r=0;for(let e=32;e<t.length-16;e+=160,r+=16)t.set(i.subarray(r,r+16),e);return t}decryptAvcSample(t,e,i,r,s){let a=tm(s.data),n=this.getAvcEncryptedData(a);this.decryptBuffer(n.buffer).then(n=>{s.data=this.getAvcDecryptedUnit(a,n),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,r)}).catch(r)}decryptAvcSamples(t,e,i,r){if(t instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length){r();return}let s=t[e].units;for(;!(i>=s.length);i++){let a=s[i];if(!(a.data.length<=48)&&(1===a.type||5===a.type)&&(this.decryptAvcSample(t,e,i,r,a),!this.decrypter.isSync()))return}}}constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new em(e,{removePKCS7Padding:!1})}}class rn{createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i;let r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){let t=r.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){let i=e.samples,r=i.length;if(r){let e=i[r-1];t.pts=e.pts,t.dts=e.dts}else{e.dropped++;return}}e.samples.push(t)}}parseNALu(t,e,i){let r,s,a;let n=e.byteLength,l=t.naluState||0,o=l,h=[],d=0,c=-1,u=0;for(-1===l&&(c=0,u=this.getNALuType(e,0),l=0,d=1);d<n;){if(r=e[d++],!l){l=r?0:1;continue}if(1===l){l=r?0:2;continue}if(r){if(1===r){if(s=d-l-1,c>=0){let t={data:e.subarray(c,s),type:u};h.push(t)}else{let i=this.getLastNalUnit(t.samples);i&&(o&&d<=4-o&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-o)),s>0&&(i.data=tc(i.data,e.subarray(0,s)),i.state=0))}d<n?(a=this.getNALuType(e,d),c=d,u=a,l=0):l=-1}else l=0}else l=3}if(c>=0&&l>=0){let t={data:e.subarray(c,n),type:u,state:l};h.push(t)}if(0===h.length){let i=this.getLastNalUnit(t.samples);i&&(i.data=tc(i.data,e))}return t.naluState=l,h}constructor(){this.VideoSample=null}}class rl{loadWord(){let t=this.data,e=this.bytesAvailable,i=t.byteLength-e,r=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw Error("no bytes available");r.set(t.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t||(t-=this.bitsAvailable,e=t>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord()),this.word<<=t,this.bitsAvailable-=t}readBits(t){let e=Math.min(this.bitsAvailable,t),i=this.word>>>32-e;if(t>32&&F.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw Error("no bits available");return(e=t-e)>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if((this.word&2147483648>>>t)!=0)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let t=this.skipLZ();return this.readBits(t+1)-1}readEG(){let t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}}class ro extends rn{parsePES(t,e,i,r){let s;let a=this.parseNALu(t,i.data,r),n=this.VideoSample,l=!1;i.data=null,n&&a.length&&!t.audFound&&(this.pushAccessUnit(n,t),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach(r=>{var a,o,h,d,c;switch(r.type){case 1:{let e=!1;s=!0;let a=r.data;if(l&&a.length>4){let t=this.readSliceType(a);(2===t||4===t||7===t||9===t)&&(e=!0)}
1e&&null!=(h=n)&&h.frame&&!n.key&&(this.pushAccessUnit(n,t),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.frame=!0,n.key=e;break}case 5:s=!0,null!=(a=n)&&a.frame&&!n.key&&(this.pushAccessUnit(n,t),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 6:s=!0,tg(r.data,1,i.pts,e.samples);break;case 7:{s=!0,l=!0;let e=r.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(d=t.pixelRatio)?void 0:d[0])!==i.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];let r=e.subarray(1,4),s="avc1.";for(let t=0;t<3;t++){let e=r[t].toString(16);e.length<2&&(e="0"+e),s+=e}t.codec=s}break}case 8:s=!0,t.pps=[r.data];break;case 9:s=!0,t.audFound=!0,null!=(o=n)&&o.frame&&(this.pushAccessUnit(n,t),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:s=!0;break;default:s=!1}n&&s&&n.units.push(r)}),r&&n&&(this.pushAccessUnit(n,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){let e=new rl(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i=8,r=8;for(let s=0;s<t;s++)0!==r&&(r=(i+e.readEG()+256)%256),i=0===r?i:r}readSPS(t){let e,i,r;let s=new rl(t),a=0,n=0,l=0,o=0,h=s.readUByte.bind(s),d=s.readBits.bind(s),c=s.readUEG.bind(s),u=s.readBoolean.bind(s),f=s.skipBits.bind(s),g=s.skipEG.bind(s),m=s.skipUEG.bind(s),p=this.skipScalingList.bind(this);h();let E=h();if(d(5),f(3),h(),m(),100===E||110===E||122===E||244===E||44===E||83===E||86===E||118===E||128===E){let t=c();if(3===t&&f(1),m(),m(),f(1),u())for(r=0,i=3!==t?8:12;r<i;r++)u()&&p(r<6?16:64,s)}m();let y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),e=c(),r=0;r<e;r++)g();m(),f(1);let v=c(),T=c(),S=d(1);0===S&&f(1),f(1),u()&&(a=c(),n=c(),l=c(),o=c());let A=[1,1];if(u()&&u())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil((v+1)*16-2*a-2*n),height:(2-S)*(T+1)*16-(S?2:4)*(l+o),pixelRatio:A}}}class rh extends rn{parsePES(t,e,i,r){let s;let a=this.parseNALu(t,i.data,r),n=this.VideoSample,l=!1;i.data=null,n&&a.length&&!t.audFound&&(this.pushAccessUnit(n,t),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach(r=>{var a,o,h;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),n.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:s=!0,l&&null!=(h=n)&&h.frame&&!n.key&&(this.pushAccessUnit(n,t),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:s=!0,null!=(a=n)&&a.frame&&!n.key&&(this.pushAccessUnit(n,t),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0,n.frame=!0;break;case 39:s=!0,tg(r.data,2,i.pts,e.samples);break;case 32:s=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=k(t.params,this.readVPS(r.data)),this.initVPS=r.data),t.vps=[r.data];break;case 33:if(s=!0,l=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],r.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){let e=this.readSPS(r.data);for(let i in t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={}),e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,r.data,t.vps),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0;break;case 34:if(s=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];let e=this.readPPS(r.data);for(let i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,r.data,t.vps)}break;case 35:s=!0,t.audFound=!0,null!=(o=n)&&o.frame&&(this.pushAccessUnit(n,t),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:s=!1}n&&s&&n.units.push(r)}),r&&n&&(this.pushAccessUnit(n,t),this.VideoSample=null)}pushParameterSet(t,e,i){(!i||i[0]!==this.initVPS)&&(i||t.length)||t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){let e=new Uint8Array(t.byteLength),i=0;for(let r=0;r<t.byteLength;r++)(!(r>=2)||3!==t[r]||0!==t[r-1]||0!==t[r-2])&&(e[i]=t[r],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){let e=new rl(t);return e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6),{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){let e=new rl(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);let i=e.readBits(3);e.readBoolean();let r=e.readBits(2),s=e.readBoolean(),a=e.readBits(5),n=e.readUByte(),l=e.readUByte(),o=e.readUByte(),h=e.readUByte(),d=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),E=[],y=[];for(let t=0;t<i;t++)E.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)E[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();let v=e.readUEG();3==v&&e.skipBits(1);let T=e.readUEG(),S=e.readUEG(),A=e.readBoolean(),L=0,I=0,R=0,b=0;A&&(L+=e.readUEG(),I+=e.readUEG(),R+=e.readUEG(),b+=e.readUEG());let D=e.readUEG(),k=e.readUEG(),_=e.readUEG(),P=e.readBoolean();for(let t=P?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.readBoolean()&&e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++)if(e.readBoolean()){let i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG();e.readBoolean(),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());let C=e.readUEG(),O=0;for(let t=0;t<C;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===C&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=O;t++){let t=e.readBoolean(),r=!1;t||(r=e.readBoolean()),(t||r)&&i++}O=i}else{let t=e.readUEG(),i=e.readUEG();O=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){let t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<_+4;t++)e.readBits(1);e.readBits(1)}}let w=0,M=1,x=1,F=!0,N=1,U=0;e.readBoolean(),e.readBoolean();if(e.readBoolean()){if(e.readBoolean()){let t=e.readUByte();t>0&&t<16?(M=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],x=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(M=e.readBits(16),x=e.readBits(16))}if(e.readBoolean()&&e.readBoolean(),e.readBoolean()&&(e.readBits(3),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())),e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),e.readBoolean()&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG()),e.readBoolean()&&(N=e.readBits(32),U=e.readBits(32),e.readBoolean()&&e.readUEG(),e.readBoolean())){let t=e.readBoolean(),r=e.readBoolean(),s=!1;(t||r)&&((s=e.readBoolean())&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let a=0;a<=i;a++){let i=(F=e.readBoolean())||e.readBoolean(),a=!1;i?e.readEG():a=e.readBoolean();let n=a?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),s&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(r)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),s&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),w=e.readUEG())}let B=T,G=S;if(A){let t=1,e=1;1===v?t=e=2:2==v&&(t=2),B=T-t*I-t*L,G=S-e*b-e*R}let K=r?["A","B","C"][r]:"",V=n<<24|l<<16|o<<8|h,H=0;for(let t=0;t<32;t++)H=(H|(V>>t&1)<<31-t)>>>0;let Y=H.toString(16);return 1===a&&"2"===Y&&(Y="6"),{codecString:"hvc1.".concat(K).concat(a,".").concat(Y,".").concat(s?"H":"L").concat(p,".B0"),params:{general_tier_flag:s,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[n,l,o,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:
1p,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:w,chroma_format_idc:v,frame_rate:{fixed:F,fps:U/N}},width:B,height:G,pixelRatio:[M,x]}}readPPS(t){let e=new rl(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2),e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);let i=e.readBoolean(),r=e.readBoolean(),s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}constructor(...t){super(...t),this.initVPS=null}}class rd{static probe(t,e){let i=rd.syncOffset(t);return i>0&&e.warn("MPEG2-TS detected but first sync word found @ offset ".concat(i)),-1!==i}static syncOffset(t){let e=t.length,i=Math.min(940,e-188)+1,r=0;for(;r<i;){let s=!1,a=-1,n=0;for(let l=r;l<e;l+=188)if(71===t[l]&&(e-l==188||71===t[l+188])){if(n++,-1===a&&0!==(a=l)&&(i=Math.min(a+18612,t.length-188)+1),s||(s=0===rc(t,l)),s&&n>1&&(0===a&&n>2||l+188>i))return a}else if(n)return -1;else break;r++}return -1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:$[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=rd.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=rd.createTrack("audio",r),this._id3Track=rd.createTrack("id3"),this._txtTrack=rd.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){let{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e){let i,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];r||(this.sampleAes=null);let a=this._videoTrack,n=this._audioTrack,l=this._id3Track,o=this._txtTrack,h=a.pid,d=a.pesData,c=n.pid,u=l.pid,f=n.pesData,g=l.pesData,m=null,p=this.pmtParsed,E=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=tc(this.remainderData,t)).length,this.remainderData=null),y<188&&!s)return this.remainderData=t,{audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};let v=Math.max(0,rd.syncOffset(t));(y-=(y-v)%188)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=v;e<y;e+=188)if(71===t[e]){let s;let y=!!(64&t[e+1]),T=rc(t,e);if((48&t[e+3])>>4>1){if((s=e+5+t[e+4])===e+188)continue}else s=e+4;switch(T){case h:y&&(d&&(i=rg(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,o,i,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(s,e+188)),d.size+=e+188-s);break;case c:if(y){if(f&&(i=rg(f,this.logger)))switch(n.segmentCodec){case"aac":this.parseAACPES(n,i);break;case"mp3":this.parseMPEGPES(n,i);break;case"ac3":this.parseAC3PES(n,i)}f={data:[],size:0}}f&&(f.data.push(t.subarray(s,e+188)),f.size+=e+188-s);break;case u:y&&(g&&(i=rg(g,this.logger))&&this.parseID3PES(l,i),g={data:[],size:0}),g&&(g.data.push(t.subarray(s,e+188)),g.size+=e+188-s);break;case 0:var S,A;y&&(s+=t[s]+1),E=this._pmtId=(31&(S=t)[(A=s)+10])<<8|S[A+11];break;case E:{y&&(s+=t[s]+1);let i=function(t,e,i,r,s,a){let n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(15&t[e+1])<<8|t[e+2],o=e+3+l-4,h=(15&t[e+10])<<8|t[e+11];for(e+=12+h;e<o;){let l=rc(t,e),o=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){rf("ADTS AAC",a);break}case 15:-1===n.audioPid&&(n.audioPid=l);break;case 21:-1===n.id3Pid&&(n.id3Pid=l);break;case 219:if(!r){rf("H.264",a);break}case 27:-1===n.videoPid&&(n.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===n.audioPid&&(n.audioPid=l,n.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){rf("AC-3",a);break}case 129:i.ac3?-1===n.audioPid&&(n.audioPid=l,n.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===n.audioPid&&o>0){let r=e+5,s=o;for(;s>2;){106===t[r]&&(!0!==i.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=l,n.segmentAudioCodec="ac3"));let e=t[r+1]+2;r+=e,s-=e}}break;case 194:case 135:return ru(s,Error("Unsupported EC-3 in M2TS found"),void 0,a),n;case 36:-1===n.videoPid&&(n.videoPid=l,n.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}e+=o+5}return n}
1(t,s,this.typeSupported,r,this.observer,this.logger);(h=i.videoPid)>0&&(a.pid=h,a.segmentCodec=i.segmentVideoCodec),(c=i.audioPid)>0&&(n.pid=c,n.segmentCodec=i.segmentAudioCodec),(u=i.id3Pid)>0&&(l.pid=u),null===m||p||(this.logger.warn("MPEG-TS PMT found at ".concat(e," after unknown PID '").concat(m,"'. Backtracking to sync byte @").concat(v," to parse all TS packets.")),m=null,e=v-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=T}}else T++;T>0&&ru(this.observer,Error("Found ".concat(T," TS packet/s that do not start with 0x47")),void 0,this.logger),a.pesData=d,n.pesData=f,l.pesData=g;let L={audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};return s&&this.extractRemainingSamples(L),L}flush(){let t;let{remainderData:e}=this;return(this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes)?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(t){let e;let{audioTrack:i,videoTrack:r,id3Track:s,textTrack:a}=t,n=r.pesData,l=i.pesData,o=s.pesData;if(n&&(e=rg(n,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,a,e,!0),r.pesData=null)):r.pesData=n,l&&(e=rg(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,e);break;case"mp3":this.parseMPEGPES(i,e);break;case"ac3":this.parseAC3PES(i,e)}i.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;o&&(e=rg(o,this.logger))?(this.parseID3PES(s,e),s.pesData=null):s.pesData=o}demuxSampleAes(t,e,i){let r=this.demux(t,i,!0,!this.config.progressive),s=this.sampleAes=new ra(this.observer,this.config,e);return this.decrypt(r,s)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new ro:"hevc"===t&&(this.videoParser=new rh))}decrypt(t,e){return new Promise(i=>{let{audioTrack:r,videoTrack:s}=t;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,()=>{s.samples?e.decryptAvcSamples(s.samples,0,0,()=>{i(t)}):i(t)}):s.samples&&e.decryptAvcSamples(s.samples,0,0,()=>{i(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let i,r,s,a,n=0,l=this.aacOverFlow,o=e.data;if(l){this.aacOverFlow=null;let e=l.missing,i=l.sample.unit.byteLength;-1===e?o=tc(l.sample.unit,o):(l.sample.unit.set(o.subarray(0,e),i-e),t.samples.push(l.sample),n=l.missing)}for(i=n,r=o.length;i<r-1&&!iG(o,i);i++);if(i!==n){let t;let e=i<r-1;if(t=e?"AAC PES did not start with ADTS header,offset:".concat(i):"No ADTS header found in AAC PES",ru(this.observer,Error(t),e,this.logger),!e)return}if(iK(t,this.observer,o,i,this.audioCodec),void 0!==e.pts)s=e.pts;else if(l){let e=9216e4/t.samplerate;s=l.sample.pts+e}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0;for(;i<r;){if(a=iV(t,o,i,s,h),i+=a.length,a.missing){this.aacOverFlow=a;break}for(h++;i<r-1&&!iG(o,i);i++);}}parseMPEGPES(t,e){let i=e.data,r=i.length,s=0,a=0,n=e.pts;if(void 0===n){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(i5(i,a)){let e=i2(t,i,a,n,s);if(e)a+=e.length,s++;else break}else a++}parseAC3PES(t,e){{let i;let r=e.data,s=e.pts;if(void 0===s){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let a=r.length,n=0,l=0;for(;l<a&&(i=rt(t,r,l,s,n++))>0;)l+=i}}parseID3PES(t,e){if(void 0===e.pts){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=k({},e,{type:this._videoTrack?iq.emsg:iq.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}constructor(t,e,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupp
1orted=i,this.logger=r,this.videoParser=null}}function rc(t,e){return((31&t[e+1])<<8)+t[e+2]}function ru(t,e,i,r){r.warn("parsing error: ".concat(e.message)),t.emit(h.ERROR,h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function rf(t,e){e.log("".concat(t," with AES-128-CBC encryption found in unencrypted stream"))}function rg(t,e){let i,r,s,a,n,l=0,o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=tc(o[0],o[1]),o.splice(1,1);if(1===((i=o[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>t.size-6)return null;let h=i[7];192&h&&(a=(14&i[9])*536870912+(255&i[10])*4194304+(254&i[11])*16384+(255&i[12])*128+(254&i[13])/2,64&h?a-(n=(14&i[14])*536870912+(255&i[15])*4194304+(254&i[16])*16384+(255&i[17])*128+(254&i[18])/2)>54e5&&(e.warn("".concat(Math.round((a-n)/9e4),"s delta between PTS and DTS, align them")),a=n):n=a);let d=(s=i[8])+9;if(t.size<=d)return null;t.size-=d;let c=new Uint8Array(t.size);for(let t=0,e=o.length;t<e;t++){let e=(i=o[t]).byteLength;if(d){if(d>e){d-=e;continue}i=i.subarray(d),e-=d,d=0}c.set(i,l),l+=e}return r&&(r-=s+3),{data:c,pts:a,dts:n,len:r}}return null}class rm{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);else if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e||3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}class rp{static init(){let t;for(t in rp.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},rp.types)rp.types.hasOwnProperty(t)&&(rp.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);let e=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]);rp.HDLR_TYPES={video:e,audio:i};let r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);rp.STTS=rp.STSC=rp.STCO=s,rp.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rp.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rp.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),rp.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let a=new Uint8Array([105,115,111,109]),n=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);rp.FTYP=rp.box(rp.types.ftyp,a,l,a,n),rp.DINF=rp.box(rp.types.dinf,rp.box(rp.types.dref,r))}static box(t){for(var e=arguments.length,i=Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];let s=8,a=i.length,n=a;for(;a--;)s+=i[a].byteLength;let l=new Uint8Array(s);for(l[0]=s>>24&255,l[1]=s>>16&255,l[2]=s>>8&255,l[3]=255&s,l.set(t,4),a=0,s=8;a<n;a++)l.set(i[a],s),s+=i[a].byteLength;return l}static hdlr(t){return rp.box(rp.types.hdlr,rp.HDLR_TYPES[t])}static mdat(t){return rp.box(rp.types.mdat,t)}static mdhd(t,e){let i=Math.floor((e*=t)/4294967296),r=Math.floor(e%4294967296);return rp.box(rp.types.mdhd,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,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return rp.box(rp.types.mdia,rp.mdhd(t.timescale||0,t.duration||0),rp.hdlr(t.type),rp.minf(t))}static mfhd(t){return rp.box(rp.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?rp.box(rp.types.minf,rp.box(rp.types.smhd,rp.SMHD),rp.DINF,rp.stbl(t)):rp.box(rp.types.minf,rp.box(rp.types.vmhd,rp.VMHD),rp.DINF,rp.stbl(t))}static moof(t,e,i){return rp.box(rp.types.moof,rp.mfhd(t),rp.traf(i,e))}static moov(t){let e=t.length,i=[];for(;e--;)i[e]=rp.trak(t[e]);return rp.box.apply(null,[rp.types.moov,rp.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).c
1oncat(rp.mvex(t)))}static mvex(t){let e=t.length,i=[];for(;e--;)i[e]=rp.trex(t[e]);return rp.box.apply(null,[rp.types.mvex,...i])}static mvhd(t,e){let i=Math.floor((e*=t)/4294967296),r=Math.floor(e%4294967296),s=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,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,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 rp.box(rp.types.mvhd,s)}static sdtp(t){let e,i;let r=t.samples||[],s=new Uint8Array(4+r.length);for(e=0;e<r.length;e++)i=r[e].flags,s[e+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return rp.box(rp.types.sdtp,s)}static stbl(t){return rp.box(rp.types.stbl,rp.stsd(t),rp.box(rp.types.stts,rp.STTS),rp.box(rp.types.stsc,rp.STSC),rp.box(rp.types.stsz,rp.STSZ),rp.box(rp.types.stco,rp.STCO))}static avc1(t){let e,i,r,s=[],a=[];for(e=0;e<t.sps.length;e++)r=(i=t.sps[e]).byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)r=(i=t.pps[e]).byteLength,a.push(r>>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(i));let n=rp.box(rp.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(a))),l=t.width,o=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return rp.box(rp.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,o>>8&255,255&o,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]),n,rp.box(rp.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rp.box(rp.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){let e=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...e,6,1,2])}static audioStsd(t){let e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return rp.box(rp.types.mp4a,rp.audioStsd(t),rp.box(rp.types.esds,rp.esds(t)))}static mp3(t){return rp.box(rp.types[".mp3"],rp.audioStsd(t))}static ac3(t){return rp.box(rp.types["ac-3"],rp.audioStsd(t),rp.box(rp.types.dac3,t.config))}static stsd(t){let{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return rp.box(rp.types.stsd,rp.STSD,rp.mp4a(t));if("ac3"===e&&t.config)return rp.box(rp.types.stsd,rp.STSD,rp.ac3(t));if("mp3"===e&&"mp3"===t.codec)return rp.box(rp.types.stsd,rp.STSD,rp.mp3(t))}else if(t.pps&&t.sps){if("avc"===e)return rp.box(rp.types.stsd,rp.STSD,rp.avc1(t));if("hevc"===e&&t.vps)return rp.box(rp.types.stsd,rp.STSD,rp.hvc1(t))}else throw Error("video track missing pps or sps");throw Error("unsupported ".concat(t.type," segment codec (").concat(e,"/").concat(t.codec,")"))}static tkhd(t){let e=t.id,i=(t.duration||0)*(t.timescale||0),r=t.width||0,s=t.height||0,a=Math.floor(i/4294967296),n=Math.floor(i%4294967296);return rp.box(rp.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,n>>24,n>>16&255,n>>8&255,255&n,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,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(t,e){let i=rp.sdtp(t),r=t.id,s=Math.floor(e/4294967296),a=Math.floor(e%4294967296);return rp.box(rp.types.traf,rp.box(rp.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),rp.box(rp.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),rp.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,rp.box(rp.types.trak,rp.tkhd(t),rp.mdia(t))}static trex(t){let e=t.id;return rp.box(rp.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){let i,r,s,a,n,l;let o=t.samples||[],h=o.length,d=12+16*h,c=new Uint8Array(d);for(e+=8+d,c.set(["video"===t.type?1:0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),i=0;i<h;i++)s=(r=o[i]).duration,a=r.size,n=r.flags,l=r.cts,c.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,n.isLeading<<2|n.dependsOn,n.isDependedOn<<6|n.hasRedundancy<<4|n.paddingValue<<1|n.isNonSync,61440&n.degradPrio,15&n.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return rp.box(rp.types.trun,c)}static initSegment(t){rp.types||rp.init();let e=rp.moov(t);return tc(rp.FTYP,e)}
1static hvc1(t){let e=t.params,i=[t.vps,t.sps,t.pps],r=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]),s=r.length;for(let t=0;t<i.length;t+=1){s+=3;for(let e=0;e<i[t].length;e+=1)s+=2+i[t][e].length}let a=new Uint8Array(s);a.set(r,0),s=r.length;let n=i.length-1;for(let t=0;t<i.length;t+=1){a.set(new Uint8Array([32+t|(t===n?128:0),0,i[t].length]),s),s+=3;for(let e=0;e<i[t].length;e+=1)a.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),s),s+=2,a.set(i[t][e],s),s+=i[t][e].length}let l=rp.box(rp.types.hvcC,a),o=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return rp.box(rp.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,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]),l,rp.box(rp.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rp.box(rp.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}}function rE(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=t*e*i;return r?Math.round(s):s}function ry(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return rE(t,1e3,11111111111111112e-21,e)}function rv(t){let{baseTime:e,timescale:i,trackId:r}=t;return"".concat(e/i," (").concat(e,"/").concat(i,") trackId: ").concat(r)}rp.types=void 0,rp.HDLR_TYPES=void 0,rp.STTS=void 0,rp.STSC=void 0,rp.STCO=void 0,rp.STSZ=void 0,rp.VMHD=void 0,rp.SMHD=void 0,rp.STSD=void 0,rp.FTYP=void 0,rp.DINF=void 0;let rT=null,rS=null;function rA(t,e,i,r){return{duration:e,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class rL extends C{destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){let e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log("Reset initPTS: ".concat(e?rv(e):e," > ").concat(t?rv(t):t)),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1,i=t[0].pts,r=t.reduce((t,r)=>{let s=r.pts,a=s-t;return(a<-4294967296&&(e=!0,a=(s=rI(s,i))-t),a>0)?t:s},i);return e&&this.debug("PTS rollover detected"),r}remux(t,e,i,r,s,a,n,l){let o,h,d,c,u,f;let g=s,m=s,p=t.pid>-1,E=e.pid>-1,y=e.samples.length,v=t.samples.length>0,T=n&&y>0||y>1;if((!p||v)&&(!E||T)||this.ISGenerated||n){let i;if(this.ISGenerated){var S,A,L,I;let t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(S=e.pixelRatio)?void 0:S[0])!==(null==(A=t.pixelRatio)?void 0:A[0])||(null==(L=e.pixelRatio)?void 0:L[1])!==(null==(I=t.pixelRatio)?void 0:I[1]))||!t&&T||null===this.nextAudioTs&&v)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(t,e,s,a));let r=this.isVideoContiguous,n=-1;if(T&&(n=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return -1}(e.samples),!r&&this.config.forceKeyFrameOnDiscontinuity)){if(f=!0,n>0){this.warn("Dropped ".concat(n," out of ").concat(y," video samples due to a missing keyframe"));let t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(n),e.dropped+=n,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else -1===n&&(this.warn("No keyframe found out of ".concat(y," video samples")),f=!1)}if(this.ISGenerated){if(v&&T){let i=this.getVideoStartPts(e.samples),r=(rI(t.samples[0].pts,i)-i)/e.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(v){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(t,e,s,a)),h=this.remuxAudio(t,g,this.isAudioContiguous,a,E||T||l===R.AUDIO?m:void 0),T){let i=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(t,e,s,a)),o=this.remuxVideo(e,m,r,i)}}else T&&(o=this.remuxVideo(e,m,r,0));o&&(o.firstKeyFrame=n,o.independent=-1!==n,o.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=rR(i,s,this._initPTS,this._initDTS)),r.samples.length&&(c=rb(r,s,this._initPTS))),{audio:h,video:o,initSegment:d,independent:f,text:c,id3:u}}computeInitPts(t,e,i,r){let s=Math.round(i*e),a=rI(t,s);if(a<s+e)for(this.log("Adjusting PTS for rollover in timeline near ".concat((s-a)/e," ").concat(r));a<s+e;)a+=8589934592;return a-s}generateIS(t,e,i,r){let s,a,n;
1let l=t.samples,o=e.samples,h=this.typeSupported,d={},c=this._initPTS,u=!c||r,f="audio/mp4",g=-1;if(u&&(s=a=1/0),t.config&&l.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}d.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&h.mpeg?new Uint8Array(0):rp.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(g=t.id,n=t.inputTimeScale,c&&n===c.timescale?u=!1:s=a=this.computeInitPts(l[0].pts,n,i,"audio"))}if(e.sps&&e.pps&&o.length){if(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:rp.initSegment([e]),metadata:{width:e.width,height:e.height}},u){if(g=e.id,n=e.inputTimeScale,c&&n===c.timescale)u=!1;else{let t=this.getVideoStartPts(o),e=rI(o[0].dts,t),r=this.computeInitPts(e,n,i,"video"),l=this.computeInitPts(t,n,i,"video");a=Math.min(a,r),s=Math.min(s,l)}}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,u?(c&&this.warn("Timestamps at playlist time: ".concat(r?"":"~").concat(i," ").concat(s/n," != initPTS: ").concat(c.baseTime/c.timescale," (").concat(c.baseTime,"/").concat(c.timescale,") trackId: ").concat(c.trackId)),this.log("Found initPTS at playlist time: ".concat(i," offset: ").concat(s/n," (").concat(s,"/").concat(n,") trackId: ").concat(g)),this._initPTS={baseTime:s,timescale:n,trackId:g},this._initDTS={baseTime:a,timescale:n,trackId:g}):s=n=void 0,{tracks:d,initPTS:s,timescale:n,trackId:g}}remuxVideo(t,e,i,r){let s,a,n;let d=t.inputTimeScale,c=t.samples,u=[],f=c.length,g=this._initPTS,m=g.baseTime*d/g.timescale,p=this.nextVideoTs,E=8,y=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!i||null===p){let t=m+e*d,r=c[0].pts-rI(c[0].dts,c[0].pts);rT&&null!==p&&15e3>Math.abs(t-r-(p+m))?i=!0:p=t-r-m}let A=p+m;for(let t=0;t<f;t++){let e=c[t];e.pts=rI(e.pts,A),e.dts=rI(e.dts,A),e.dts<c[t>0?t-1:t].dts&&(S=!0)}S&&c.sort(function(t,e){let i=t.dts-e.dts,r=t.pts-e.pts;return i||r}),s=c[0].dts;let L=(a=c[c.length-1].dts)-s,I=L?Math.round(L/(f-1)):y||t.inputTimeScale/30;if(i){let i=s-A,r=i>I,a=i<-1;if((r||a)&&(r?this.warn("".concat((t.segmentCodec||"").toUpperCase(),": ").concat(ry(i,!0)," ms (").concat(i,"dts) hole between fragments detected at ").concat(e.toFixed(3))):this.warn("".concat((t.segmentCodec||"").toUpperCase(),": ").concat(ry(-i,!0)," ms (").concat(i,"dts) overlapping between fragments detected at ").concat(e.toFixed(3))),!a||A>=c[0].pts||rT)){s=A;let t=c[0].pts-i;if(r)c[0].dts=s,c[0].pts=t;else{let e=!0;for(let r=0;r<c.length&&(!(c[r].dts>t)||!e);r++){let t=c[r].pts;if(c[r].dts-=i,c[r].pts-=i,r<c.length-1){let i=c[r+1].pts;e=i<=c[r].pts==i<=t}}}this.log("Video: Initial PTS/DTS adjusted: ".concat(ry(t,!0),"/").concat(ry(s,!0),", delta: ").concat(ry(i,!0)," ms"))}}let R=0,b=0,D=s=Math.max(0,s);for(let t=0;t<f;t++){let e=c[t],i=e.units,r=i.length,s=0;for(let t=0;t<r;t++)s+=i[t].data.length;b+=s,R+=r,e.length=s,e.dts<D?(e.dts=D,D+=I/4|0||1):D=e.dts,v=Math.min(e.pts,v),T=Math.max(e.pts,T)}a=c[f-1].dts;let _=b+4*R+8;try{n=new Uint8Array(_)}catch(t){this.observer.emit(h.ERROR,h.ERROR,{type:l.MUX_ERROR,details:o.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:_,reason:"fail allocating video mdat ".concat(_)});return}let P=new DataView(n.buffer);P.setUint32(0,_),n.set(rp.types.mdat,4);let C=!1,O=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let t=0;t<f;t++){let e;let i=c[t],s=i.units,a=0;for(let t=0,e=s.length;t<e;t++){let e=s[t],i=e.data,r=e.data.byteLength;P.setUint32(E,r),E+=4,n.set(i,E),E+=r,a+=4+r}if(t<f-1)y=c[t+1].dts-i.dts,e=c[t+1].pts-i.pts;else{let s=this.config,a=t>0?i.dts-c[t-1].dts:I;if(e=t>0?i.pts-c[t-1].pts:I,s.stretchShortVideoTrack&&null!==this.nextAudioTs){let t=Math.floor(s.maxBufferHole*d),e=(r?v+r*d:this.nextAudioTs+m)-i.pts;e>t?((y=e-a)<0?y=a:C=!0,this.log("It is approximately ".concat(e/90," ms to the next segment; using duration ").concat(y/90," ms for the last video frame."))):y=a}else y=a}let l=Math.round(i.pts-i.dts);O=Math.min(O,y),M=Math.max(M,y),w=Math.min(w,e),x=Math.max(x,e),u.push(rA(i.key,y,a,l))}if(u.length){if(rT){if(rT<70){let t=u[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(rS&&x-w<M-O&&I/M<.025&&0===u[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=s;for(let e=0,i=u.length;e<i;e++){let r=t+u[e].duration,s=t+u[e].cts;if(e<i-1){let t=r+u[e+1].cts;u[e].duration=t-s}else u[e].duration=e?u[e-1].duration:I;u[e].cts=0,t=r}}}let F=a+(y=C||!y?I:y);this.nextVideoTs=p=F-m,this.videoSampleDuration=y,this.isVideoContiguous=!0;let N={data1:rp.moof(t.sequenceNumber++,s,k(t,{samples:u})),data2:n,startPTS:(v-m)/d,endPTS:(T+y-m)/d,startDTS:(s-m)/d,endDTS:p/d,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}
1getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,r,s){let a;let n=t.inputTimeScale,d=t.samplerate?t.samplerate:n,c=n/d,u=this.getSamplesPerFrame(t),f=u*c,g=this._initPTS,m="mp3"===t.segmentCodec&&this.typeSupported.mpeg,p=[],E=void 0!==s,y=t.samples,v=m?0:8,T=this.nextAudioTs||-1,S=g.baseTime*n/g.timescale,A=S+e*n;if(this.isAudioContiguous=i=i||y.length&&T>0&&(r&&9e3>Math.abs(A-(T+S))||Math.abs(rI(y[0].pts,A)-(T+S))<20*f),y.forEach(function(t){t.pts=rI(t.pts,A)}),!i||T<0){let t=y.length;if(t!==(y=y.filter(t=>t.pts>=0)).length&&this.warn("Removed ".concat(y.length-t," of ").concat(t," samples (initPTS ").concat(S," / ").concat(n,")")),!y.length)return;T=0===s?0:r&&!E?Math.max(0,A-S):y[0].pts-S}if("aac"===t.segmentCodec){let e=this.config.maxAudioFramesDrift;for(let i=0,r=T+S;i<y.length;i++){let s=y[i],a=s.pts,l=a-r,o=Math.abs(1e3*l/n);if(l<=-e*f&&E)0===i&&(this.warn("Audio frame @ ".concat((a/n).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*l/n)," ms.")),this.nextAudioTs=T=a-S,r=a);else if(l>=e*f&&o<1e4&&E){let e=Math.round(l/f);for(r=a-e*f;r<0&&e&&f;)e--,r+=f;0===i&&(this.nextAudioTs=T=r-S),this.warn("Injecting ".concat(e," audio frames @ ").concat(((r-S)/n).toFixed(3),"s due to ").concat(Math.round(1e3*l/n)," ms gap."));for(let a=0;a<e;a++){let e=rm.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=s.unit.subarray()),y.splice(i,0,{unit:e,pts:r}),r+=f,i++}}s.pts=r,r+=f}}let L=null,I=null,R=0,b=y.length;for(;b--;)R+=y[b].unit.byteLength;for(let e=0,r=y.length;e<r;e++){let r=y[e],s=r.unit,n=r.pts;if(null!==I)p[e-1].duration=Math.round((n-I)/c);else{if(i&&"aac"===t.segmentCodec&&(n=T+S),L=n,!(R>0))return;R+=v;try{a=new Uint8Array(R)}catch(t){this.observer.emit(h.ERROR,h.ERROR,{type:l.MUX_ERROR,details:o.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:R,reason:"fail allocating audio mdat ".concat(R)});return}m||(new DataView(a.buffer).setUint32(0,R),a.set(rp.types.mdat,4))}a.set(s,v);let d=s.byteLength;v+=d,p.push(rA(!0,u,d,0)),I=n}let D=p.length;if(!D)return;let _=p[p.length-1];T=I-S,this.nextAudioTs=T+c*_.duration;let P=m?new Uint8Array(0):rp.moof(t.sequenceNumber++,L/c,k({},t,{samples:p}));t.samples=[];let C=(L-S)/n,O=T/n,w={data1:P,data2:a,startPTS:C,endPTS:O,startDTS:C,endDTS:O,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,w}constructor(t,e,i,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===rT){let t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);rT=t?parseInt(t[1]):0}if(null===rS){let t=navigator.userAgent.match(/Safari\/(\d+)/i);rS=t?parseInt(t[1]):0}}}function rI(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function rR(t,e,i,r){let s=t.samples.length;if(!s)return;let a=t.inputTimeScale;for(let n=0;n<s;n++){let s=t.samples[n];s.pts=rI(s.pts-i.baseTime*a/i.timescale,e*a)/a,s.dts=rI(s.dts-r.baseTime*a/r.timescale,e*a)/a}let n=t.samples;return t.samples=[],{samples:n}}function rb(t,e,i){let r=t.samples.length;if(!r)return;let s=t.inputTimeScale;for(let a=0;a<r;a++){let r=t.samples[a];r.pts=rI(r.pts-i.baseTime*s/i.timescale,e*s)/s}t.samples.sort((t,e)=>t.pts-e.pts);let a=t.samples;return t.samples=[],{samples:a}}class rD extends C{destroy(){}resetTimeStamp(t){this.lastEndTime=null;let e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,r){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,r),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:i,videoCodec:r}=this;if(!(null!=t&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:s,video:a}=this.initData=ts(t);if(e)!function(t,e){if(!t||!e)return;let i=e.keyId;i&&e.isCommonEncryption&&th(t,(t,e)=>{let r=t.subarray(8,24);r.some(t=>0!==t)||(F.log("[eme] Patching keyId in 'enc".concat(e?"a":"v",">sinf>>tenc' box: ").concat(G(r)," -> ").concat(G(i))),t.set(i,8))})}(t,e);else{let t=s||a;null!=t&&t.encrypted&&this.warn('Init segment with encrypted track with has no key ("'.concat(t.codec,'")!'))}s&&(i=r_(s,W.AUDIO,this)),a&&(r=r_(a,W.VIDEO,this));let n={};s&&a?n.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:s?n.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:t,id:"audio"}:a?n.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=n}
1remux(t,e,i,r,a,n){var l,o;let{initPTS:h,lastEndTime:d}=this,c={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};s(d)||(d=this.lastEndTime=a||0);let u=e.samples;if(!u.length)return c;let f={initPTS:void 0,timescale:void 0,trackId:void 0},g=this.initData;if(null!=(l=g)&&l.length||(this.generateInitSegment(u),g=this.initData),!(null!=(o=g)&&o.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let m=function(t,e,i){let r={},a=tr(t,["moof","traf"]);for(let t=0;t<a.length;t++){let n=a[t],l=tr(n,["tfhd"])[0],o=tt(l,4),h=e[o];if(!h)continue;r[o]||(r[o]={start:NaN,duration:0,sampleCount:0,timescale:h.timescale,type:h.type});let d=r[o],c=tr(n,["tfdt"])[0];if(c){let t=c[0],e=tt(c,4);1===t&&(4294967295===e?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=4294967296,e+=tt(c,8))),s(e)&&(!s(d.start)||e<d.start)&&(d.start=e)}let u=h.default,f=tt(l,0)|(null==u?void 0:u.flags),g=(null==u?void 0:u.duration)||0;8&f&&(g=2&f?tt(l,12):tt(l,8));let m=tr(n,["trun"]),p=d.start||0,E=0,y=g;for(let t=0;t<m.length;t++){let e=m[t],i=tt(e,4),r=d.sampleCount;d.sampleCount+=i;let s=1&e[3],a=4&e[3],n=1&e[2],l=2&e[2],o=4&e[2],h=8&e[2],c=8,u=i;for(s&&(c+=4),a&&i&&(1&e[c+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=r),c+=4,n?(y=tt(e,c),c+=4):y=g,l&&(c+=4),h&&(c+=4),p+=y,E+=y,u--);u--;)n?(y=tt(e,c),c+=4):y=g,l&&(c+=4),o&&(1&e[c+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=d.sampleCount-(u+1),d.keyFrameStart=p),c+=4),h&&(c+=4),p+=y,E+=y;!E&&g&&(E+=g*i)}d.duration+=E}if(!Object.keys(r).some(t=>r[t].duration)){let e=1/0,i=0,a=tr(t,["sidx"]);for(let t=0;t<a.length;t++){let r=function(t){let e=[],i=t[0],r=8,s=tt(t,8);r+=4;let a=0,n=0;0===i?(a=tt(t,r),n=tt(t,r+4),r+=8):(a=te(t,r),n=te(t,r+8),r+=16),r+=2;let l=t.length+n,o=J(t,r);r+=2;for(let i=0;i<o;i++){let i=r,a=tt(t,i);i+=4;let n=2147483647&a;if(1==(2147483648&a)>>>31)return F.warn("SIDX has hierarchical references (not supported)"),null;let o=tt(t,i);i+=4,e.push({referenceSize:n,subsegmentDuration:o,info:{duration:o/s,start:l,end:l+n-1}}),l+=n,i+=4,r=i}return{earliestPresentationTime:a,timescale:s,version:i,referencesCount:o,references:e}}(a[t]);if(null!=r&&r.references){e=Math.min(e,r.earliestPresentationTime/r.timescale);let t=r.references.reduce((t,e)=>t+e.info.duration||0,0);i=Math.max(i,t+r.earliestPresentationTime/r.timescale)}}i&&s(i)&&Object.keys(r).forEach(t=>{r[t].duration||(r[t].duration=i*r[t].timescale-r[t].start)})}return r}(u,g,this),p=g.audio?m[g.audio.id]:null,E=g.video?m[g.video.id]:null,y=rk(E,1/0),v=rk(p,1/0),T=rk(E,0,!0),S=rk(p,0,!0),A=a,L=0,I=p&&(!E||!h&&v<y||h&&h.trackId===g.audio.id),R=I?p:E;if(R){let t=R.timescale,e=R.start-a*t,i=I?g.audio.id:g.video.id;A=R.start/t,L=I?S-v:T-y,(n||!h)&&(function(t,e,i,r){if(null===t)return!0;let s=Math.max(r,1);return Math.abs(e-t.baseTime/t.timescale-i)>s}(h,A,a,L)||t!==h.timescale)&&(h&&this.warn("Timestamps at playlist time: ".concat(n?"":"~").concat(a," ").concat(e/t," != initPTS: ").concat(h.baseTime/h.timescale," (").concat(h.baseTime,"/").concat(h.timescale,") trackId: ").concat(h.trackId)),this.log("Found initPTS at playlist time: ".concat(a," offset: ").concat(A-a," (").concat(e,"/").concat(t,") trackId: ").concat(i)),h=null,f.initPTS=e,f.timescale=t,f.trackId=i)}else this.warn("No audio or video samples found for initPTS at playlist time: ".concat(a));h?(f.initPTS=h.baseTime,f.timescale=h.timescale,f.trackId=h.trackId):(f.timescale&&void 0!==f.trackId&&void 0!==f.initPTS||(this.warn("Could not set initPTS"),f.initPTS=A,f.timescale=1,f.trackId=-1),this.initPTS=h={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let b=A-h.baseTime/h.timescale,D=b+L;L>0?this.lastEndTime=D:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let k=!!g.audio,_=!!g.video,P="";k&&(P+="audio"),_&&(P+="video");let C={data1:u,startPTS:b,startDTS:b,endPTS:D,endDTS:D,type:P,hasAudio:k,hasVideo:_,nb:1,dropped:0,encrypted:!!g.audio&&g.audio.encrypted||!!g.video&&g.video.encrypted};c.audio=k&&!_?C:void 0,c.video=_?C:void 0;let O=null==E?void 0:E.sampleCount;if(O){let t=E.keyFrameIndex,e=-1!==t;C.nb=O,C.dropped=0===t||this.isVideoContiguous?0:e?t:O,C.independent=e,C.firstKeyFrame=t,e&&E.keyFrameStart&&(C.firstKeyFramePTS=(E.keyFrameStart-h.baseTime)/h.timescale),this.isVideoContiguous||(c.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),C.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(t,"/").concat(O," dropped: ").concat(C.dropped," start: ").concat(C.firstKeyFramePTS||"NA"))}return c.initSegment=f,c.id3=rR(i,a,h,h),r.samples.length&&(c.text=rb(r,a,h)),c}constructor(t,e,i,r){super("passthrough-remuxer",r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}}function rk(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return(null==t?void 0:t.start)!==void 0?(t.start+(i?t.duration:0))/t.timescale:e}function r_(t,e,i){let r=t.codec;return r&&r.length>4?r:e===W.AUDIO?"ec-3"===r||"ac-3"===r||"alac"===r?r:"fLaC"===r||"Opus"===r?tb(r,!1):(i.warn('Unhandled audio codec "'.concat(r,'" in mp4 MAP')),r||"mp4a"):(i.warn('Unhandled video codec "'.concat(r,'" in mp4 MAP')),r||"avc1")}try{r=self.performance.now.bind(self.performance)}catch(t){r=Date.now}let rP=[{demux:rr,remux:rD},{demux:rd,remux:rL},{demux:i6,remux:rL},{demux:re,remux:rL}];rP.splice(2,0,{demux:i7,remux:rL});class rC{configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){let a;let n=i.transmuxing;n.executeStart=r();let d=new Uint8Array(t),{currentTransmuxState:c,transmuxConfig:u}=this;s&&(this.currentTransmuxState=s);
1let{contiguous:f,discontinuity:g,trackSwitch:m,accurateTimeOffset:p,timeOffset:E,initSegmentChange:y}=s||c,{audioCodec:v,videoCodec:T,defaultInitPts:S,duration:A,initSegmentData:L}=u,I=(a=null,d.byteLength>0&&(null==e?void 0:e.key)!=null&&null!==e.iv&&null!=e.method&&(a=e),a);if(I&&ex(I.method)){let t=this.getDecrypter(),e=eF(I.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(d,I.key.buffer,I.iv.buffer,e).then(t=>{let e=this.push(t,null,i);return this.decryptionPromise=null,e}),this.decryptionPromise;{let s=t.softwareDecrypt(d,I.key.buffer,I.iv.buffer,e);if(i.part>-1){let e=t.flush();s=e?e.buffer:e}if(!s)return n.executeEnd=r(),rO(i);d=new Uint8Array(s)}}let R=this.needsProbing(g,m);if(R){let t=this.configureTransmuxer(d);if(t)return this.logger.warn("[transmuxer] ".concat(t.message)),this.observer.emit(h.ERROR,h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),n.executeEnd=r(),rO(i)}(g||m||y||R)&&this.resetInitSegment(L,v,T,A,e),(g||y||R)&&this.resetInitialTimestamp(S),f||this.resetContiguity();let b=this.transmux(d,I,E,p,i);this.asyncResult=rw(b);let D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,n.executeEnd=r(),b}flush(t){let e=t.transmuxing;e.executeStart=r();let{decrypter:i,currentTransmuxState:s,decryptionPromise:a}=this;if(a)return this.asyncResult=!0,a.then(()=>this.flush(t));let n=[],{timeOffset:l}=s;if(i){let e=i.flush();e&&n.push(this.push(e.buffer,null,t))}let{demuxer:o,remuxer:h}=this;if(!o||!h){e.executeEnd=r();let i=[rO(t)];return this.asyncResult?Promise.resolve(i):i}let d=o.flush(l);return rw(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult)?Promise.resolve(n):n}flushRemux(t,e,i){let{audioTrack:s,videoTrack:a,id3Track:n,textTrack:l}=e,{accurateTimeOffset:o,timeOffset:h}=this.currentTransmuxState;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(i.sn).concat(i.part>-1?" part: "+i.part:""," of ").concat(this.id===R.MAIN?"level":"track"," ").concat(i.level));let d=this.remuxer.remux(s,a,n,l,h,o,!0,this.id);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=r()}resetInitialTimestamp(t){let{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){let{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,r,s){let{demuxer:a,remuxer:n}=this;a&&n&&(a.resetInitSegment(t,e,i,r),n.resetInitSegment(t,e,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,r,s){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,r,s):this.transmuxUnencrypted(t,i,r,s)}transmuxUnencrypted(t,e,i,r){let{audioTrack:s,videoTrack:a,id3Track:n,textTrack:l}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,a,n,l,e,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(t,e,i,r,s){return this.demuxer.demuxSampleAes(t,e,i).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,r,!1,this.id),chunkMeta:s}))}configureTransmuxer(t){let e;
1let{config:i,observer:r,typeSupported:s}=this;for(let i=0,r=rP.length;i<r;i++){var a;if(null!=(a=rP[i].demux)&&a.probe(t,this.logger)){e=rP[i];break}}if(!e)return Error("Failed to find demuxer by probing fragment data");let n=this.demuxer,l=this.remuxer,o=e.remux,h=e.demux;l&&l instanceof o||(this.remuxer=new o(r,i,s,this.logger)),n&&n instanceof h||(this.demuxer=new h(r,i,s,this.logger),this.probe=h.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new em(this.config)),t}constructor(t,e,i,r,s,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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.observer=t,this.typeSupported=e,this.config=i,this.id=s,this.logger=a}}let rO=t=>({remuxResult:{},chunkMeta:t});function rw(t){return"then"in t&&t.then instanceof Function}class rM{constructor(t,e,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class rx{constructor(t,e,i,r,s,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=a}}let rF=0;class rN{reset(){if(this.frag=null,this.part=null,this.workerContext){let t=this.instanceNo;this.instanceNo=rF++;let e=this.hls.config,i=t_(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,c
1onfig:tY(e)})}}terminateWorker(){if(this.workerContext){let{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){let e=iO[t||iC];if(e&&1==e.clientCount--){let{worker:i,objectURL:r}=e;delete iO[t||iC],r&&self.URL.revokeObjectURL(r),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,r,s,a,n,l,o,h){var d,c;o.transmuxing.start=self.performance.now();let{instanceNo:u,transmuxer:f}=this,g=a?a.start:s.start,m=s.decryptdata,p=this.frag,E=!(p&&s.cc===p.cc),y=!(p&&o.level===p.level),v=p?o.sn-p.sn:-1,T=this.part?o.part-this.part.index:-1,S=0===v&&o.id>1&&o.id===(null==p?void 0:p.stats.chunkCount),A=!y&&(1===v||0===v&&(1===T||S&&T<=0)),L=self.performance.now();(y||v||0===s.stats.parsing.start)&&(s.stats.parsing.start=L),a&&(T||!A)&&(a.stats.parsing.start=L);let I=!(p&&(null==(d=s.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),b=new rx(E,A,l,y,g,I);if(!A||E||I){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for ".concat(s.type," sn: ").concat(o.sn).concat(o.part>-1?" part: "+o.part:""," ").concat(this.id===R.MAIN?"level":"track",": ").concat(o.level," id: ").concat(o.id,"\n        discontinuity: ").concat(E,"\n        trackSwitch: ").concat(y,"\n        contiguous: ").concat(A,"\n        accurateTimeOffset: ").concat(l,"\n        timeOffset: ").concat(g,"\n        initSegmentChange: ").concat(I));let t=new rM(i,r,e,n,h);this.configureTransmuxer(t)}if(this.frag=s,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:m,chunkMeta:o,state:b},t instanceof ArrayBuffer?[t]:[]);else if(f){let e=f.push(t,m,o,b);rw(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,o,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();let{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){let e=i.flush(t);rw(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){let{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}constructor(t,e,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=rF++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{let e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var r;let t=null==(r=this.workerContext)?void 0:r.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;let e=Error("".concat(t.message,"  (").concat(t.filename,":").concat(t.lineno,")"));this.hls.config.enableWorker=!1,this.hls.logger.warn('Error in "'.concat(this.id,'" Web Worker, fallback to inline')),this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};let s=t.config;this.hls=t,this.id=e,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let a=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===h.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new iP,this.observer.on(h.FRAG_DECRYPTED,a),this.observer.on(h.ERROR,a);let n=t_(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){let i=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(i.log("loading Web Worker ".concat(s.workerPath,' for "').concat(e,'"')),this.workerContext=function(t){let e=iO[t];if(e)return e.clientCount++,e;let i=new self.URL(t,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return iO[t]=r,r}(s.workerPath)):(i.log('injecting Web Worker for "'.concat(e,'"')),this.workerContext=function(){let t=iO[iC];if(t)return t.clientCount++,t;let e=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{type:"text/javascript"}
1),i=self.URL.createObjectURL(e),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return iO[iC]=r,r}());let{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:n,id:e,config:tY(s)})}catch(r){i.warn('Error setting up "'.concat(e,'" Web Worker, fallback to inline'),r),this.terminateWorker(),this.error=null,this.transmuxer=new rC(this.observer,n,s,"",e,t.logger)}return}}this.transmuxer=new rC(this.observer,n,s,"",e,t.logger)}}class rU extends ib{onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:t}=this;t.on(h.LEVEL_LOADED,this.onLevelLoaded,this),t.on(h.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(h.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(h.BUFFER_RESET,this.onBufferReset,this),t.on(h.BUFFER_CREATED,this.onBufferCreated,this),t.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(h.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(h.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(h.FRAG_LOADING,this.onFragLoading,this),t.on(h.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:t}=this;t&&(super.unregisterListeners(),t.off(h.LEVEL_LOADED,this.onLevelLoaded,this),t.off(h.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(h.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(h.BUFFER_RESET,this.onBufferReset,this),t.off(h.BUFFER_CREATED,this.onBufferCreated,this),t.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(h.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(h.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(h.FRAG_LOADING,this.onFragLoading,this),t.off(h.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,e){let{frag:i,id:r,initPTS:s,timescale:a,trackId:n}=e;if(r===R.MAIN){let t=i.cc,e=this.fragCurrent;if(this.initPTS[t]={baseTime:s,timescale:a,trackId:n},this.log("InitPTS for cc: ".concat(t," found from main: ").concat(s/a," (").concat(s,"/").concat(a,") trackId: ").concat(n)),this.mainAnchor=i,this.state===iR.WAITING_INIT_PTS){let e=this.waitingData;(e||this.loadingParts)&&(!e||e.frag.cc===t)||this.syncWithAnchor(i,null==e?void 0:e.frag)}else!this.hls.hasEnoughToStart&&e&&e.cc!==t?(e.abortRequests(),this.syncWithAnchor(i,e)):this.state===iR.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;let r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==r?void 0:r.cc)===e.cc)return;let s=(r||t).cc,a=t3(this.getLevelDetails(),s,this.getLoadPosition());a&&(this.log("Syncing with main frag at ".concat(a.start," cc ").concat(a.cc)),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===iR.IDLE&&this.doTickIdle())}startLoad(t,e){if(!this.levels){this.startPosition=t,this.state=iR.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log("Override startPosition with lastCurrentTime @".concat(i.toFixed(3))),t=i,this.state=iR.IDLE):this.state=iR.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case iR.IDLE:this.doTickIdle();break;case iR.WAITING_TRACK:{let{levels:t,trackId:e}=this,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=iR.WAITING_INIT_PTS}break}case iR.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case iR.WAITING_INIT_PTS:{let t=this.waitingData;if(t){let{frag:e,part:i,cache:r,complete:s}=t,a=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=iR.FRAG_LOADING;let t={frag:e,part:i,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),s&&super._handleFragmentLoadComplete(t)}
1else a&&a.cc!==t.frag.cc&&this.syncWithAnchor(a,t.frag)}else this.state=iR.IDLE}}this.onTickEnd()}resetLoadingState(){let t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;let{hls:e,levels:i,media:r,trackId:s}=this,a=e.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(null!=i&&i[s]))return;let n=i[s],l=n.details;if(!l||this.waitForLive(n)||this.waitForCdnTuneIn(l)){this.state=iR.WAITING_TRACK,this.startFragRequested=!1;return}let o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,W.AUDIO,R.AUDIO));let d=this.getFwdBufferInfo(o,R.AUDIO);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,l)){e.trigger(h.BUFFER_EOS,{type:"audio"}),this.state=iR.ENDED;return}let c=d.len,u=e.maxBufferLength,f=l.fragments,g=f[0].start,m=this.getLoadPosition(),p=this.flushing?m:d.end;if(this.switchingTrack&&r&&l.PTSKnown&&m<g&&(d.end>g||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=g+.05),c>=u&&!this.switchingTrack&&p<f[f.length-1].start)return;let E=this.getNextFragment(p,l);if(E&&this.isLoopLoading(E,p)&&(E=this.getNextFragmentLoopLoading(E,l,d,R.MAIN,u)),!E){this.bufferFlushed=!0;return}let y=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&q(E)&&!E.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===en.OK&&(this.mainFragLoading=y=null),y&&q(y))){if(E.start>y.end){let t=this.fragmentTracker.getFragAtPos(p,R.MAIN);t&&t.end>y.end&&(y=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(E.start>y.end)return}this.loadFragment(E,n,p)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,e){let{audioTracks:i}=e;this.resetTransmuxer(),this.levels=i.map(t=>new tK(t))}onAudioTrackSwitching(t,e){let i=!!e.url;this.trackId=e.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==iR.STOPPED&&(this.setInterval(100),this.state=iR.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(h.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i,r;let{levels:s}=this,{details:a,id:n,groupId:l,track:o}=e;if(!s){this.warn("Audio tracks reset while loading track ".concat(n,' "').concat(o.name,'" of "').concat(l,'"'));return}let d=this.mainDetails;if(!d||a.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=e,this.state!==iR.STOPPED&&(this.state=iR.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log("Audio track ".concat(n,' "').concat(o.name,'" of "').concat(l,'" loaded [').concat(a.startSN,",").concat(a.endSN,"]").concat(a.lastPartSn?"[part-".concat(a.lastPartSn,"-").concat(a.lastPartIndex,"]"):"",",duration:").concat(a.totalduration));let c=s[n],u=0;if(a.live||null!=(i=c.details)&&i.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c.details&&(u=this.alignPlaylists(a,c.details,null==(r=this.levelLastLoaded)?void 0:r.details)),a.alignedSliding||(iT(a,d),a.alignedSliding||iS(a,d),u=a.fragmentStart)}c.details=a,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(d,u),this.hls.trigger(h.AUDIO_TRACK_UPDATED,{details:a,id:n,groupId:e.groupId}),this.state!==iR.WAITING_TRACK||this.waitForCdnTuneIn(a)||(this.state=iR.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;let i=t.frag,{part:r,payload:s}=t,{config:a,trackId:n,levels:l}=this;if(!l){this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(i.sn," of level ").concat(i.level," will not be buffered"));return}let o=l[n];if(!o){this.warn("Audio track is undefined on fragment load progress");return}let h=o.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let d=a.defaultAudioCodec||o.audioCodec||"mp4a.40.2",c=this.transmuxer;c||(c=this.transmuxer=new rN(this.hls,R.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let u=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==u){let t=r?r.index:-1,e=new eS(i.level,i.sn,i.stats.chunkCount,s.byteLength,t,-1!==t);c.push(s,f,d,"",i,r,h.totalduration,!1,e,u)}else{this.log("Unknown video PTS for cc ".concat(i.cc,", waiting for video PTS before demuxing audio frag ").concat(i.sn," of [").concat(h.startSN," ,").concat(h.endSN,"],track ").concat(n));let{cache:t}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new ik,complete:!1};t.push(new Uint8Array(s)),this.state!==iR.STOPPED&&(this.state=iR.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;let i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===R.MAIN&&q(e.frag)&&(this.mainFragLoading=e,this.state===iR.IDLE&&this.tick())}onFragBuffered(t,e){let{frag:i,part:r}=e;if(i.type!==R.AUDIO){this.audioOnly||i.type!==R.MAIN||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn("Fragment ".concat(i.sn).concat(r?" p: "+r.index:""," of level ").concat(i.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));return}if(q(i)){this.fragPrevious=i;let t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(h.AUDIO_TRACK_SWITCHED,P({},t)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}onError(t,e){var i;if(e.fatal){this.state=iR.ERROR;return}switch(e.details){case o.FRAG_GAP:case o.FRAG_PARSING_ERROR:case o.FRAG_DECRYPT_ERROR:case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(R.AUDIO,e);break;case o.AUDIO_TRACK_LOAD_ERROR:case o.AUDIO_TRACK_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==iR.WAITING_TRACK||(null==(i=e.context)?void 0:i.type)!==I.AUDIO_TRACK||(this.state=iR.IDLE);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;
1case o.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,e){let{type:i}=e;i!==W.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,e){let{type:i}=e;if(i!==W.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===iR.ENDED&&(this.state=iR.IDLE);let t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,i,R.AUDIO),this.tick())}}_handleTransmuxComplete(t){var e;let i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:a}=t,n=this.getCurrentContext(a);if(!n){this.resetWhenMissingContext(a);return}let{frag:l,part:o,level:d}=n,{details:c}=d,{audio:u,text:f,id3:g,initSegment:m}=s;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=iR.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){let t=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(d,m.tracks,t,a),r.trigger(h.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:m.tracks})}if(u){let{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=u;o&&(o.elementaryStreams[W.AUDIO]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(W.AUDIO,t,e,i,r),this.bufferFragmentData(u,l,o,a)}if(null!=g&&null!=(e=g.samples)&&e.length){let t=k({id:i,frag:l,details:c},g);r.trigger(h.FRAG_PARSING_METADATA,t)}if(f){let t=k({id:i,frag:l,details:c},f);r.trigger(h.FRAG_PARSING_USERDATA,t)}}_bufferInitSegment(t,e,i,r){if(this.state!==iR.PARSING||(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio))return;let s=e.audio;s.id=R.AUDIO;let a=t.audioCodec;this.log("Init audio buffer, container:".concat(s.container,", codecs[level/parsed]=[").concat(a,"/").concat(s.codec,"]")),a&&1===a.split(",").length&&(s.levelCodec=a),this.hls.trigger(h.BUFFER_CODECS,e);let n=s.initSegment;if(null!=n&&n.byteLength){let t={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:n};this.hls.trigger(h.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){let r=this.fragmentTracker.getState(t);if(this.switchingTrack||r===en.NOT_LOADED||r===en.PARTIAL){var s;if(q(t)){if(null!=(s=e.details)&&s.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter ".concat(t.cc," of live stream before loading audio fragment ").concat(t.sn," of level ").concat(this.trackId)),this.state=iR.WAITING_INIT_PTS;let i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&iS(e.details,i)}else super.loadFragment(t,e,i)}else this._loadInitSegment(t,e)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){let{name:e,lang:i,assocLang:r,characteristics:s,audioCodec:a,channels:n}=this.bufferedTrack;tQ({name:e,lang:i,assocLang:r,characteristics:s,audioCodec:a,channels:n},t,tz)||(tZ(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){let{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(h.AUDIO_TRACK_SWITCHED,P({},t))}constructor(t,e,i){super(t,e,i,"audio-stream-controller",R.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}}class rB extends C{destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){let r=null==e?void 0:e.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){let a;let n=r[i];try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn("Could not construct new URL for Rendition Report: ".concat(t)),a=n.URI||""}if(a===t){s=i;break}a===t.substring(0,a.length)&&(s=i)}if(-1!==s){let t=r[s],a=parseInt(t["LAST-MSN"])||e.lastPartSn,n=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){let t=Math.min(e.age-e.partTarget,e.targetduration);n>=0&&t>e.partTarget&&(n+=1)}return new tG(a,n>=0?n:void 0,i&&tB(i))}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(t))}return t}playlistLoaded(t,e,i){let{details:r,stats:a}=e,n=self.performance.now(),d=a.loading.first?Math.max(0,n-a.loading.first):0;r.advancedDateTime=Date.now()-d;let c=this.hls.config.timelineOffset;
1if(c!==r.appliedTimelineOffset){let t=Math.max(c||0,0);r.appliedTimelineOffset=t,r.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(r.live||null!=i&&i.live){let c,f,g;let m="levelInfo"in e?e.levelInfo:e.track;if(r.reloaded(i),i&&r.fragments.length>0){!function(t,e,i){let r;if(t===e)return;let a=null,n=t.fragments;for(let t=n.length-1;t>=0;t--){let e=n[t].initSegment;if(e){a=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){let r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,n=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let c=s;c<=a;c++){let s=o[n+c],a=l[c];if(r&&!a&&s&&(a=e.fragments[c]=s),s&&a){var h,d;i(s,a,c,l);let r=s.relurl,n=a.relurl;if(r&&(h=r)!==(d=n)&&d&&ip(h)!==ip(d)){e.playlistParsingError=il("media sequence mismatch ".concat(a.sn,":"),t,e,s,a);return}if(s.cc!==a.cc){e.playlistParsingError=il("discontinuity sequence mismatch (".concat(s.cc,"!=").concat(a.cc,")"),t,e,s,a);return}}}}(t,e,(t,i,n,l)=>{if((!e.startCC||e.skippedSegments)&&i.cc!==t.cc){let r=t.cc-i.cc;for(let t=n;t<l.length;t++)l[t].cc+=r;e.endCC=l[l.length-1].cc}s(t.startPTS)&&s(t.endPTS)&&(i.setStart(i.startPTS=t.startPTS),i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.setDuration(t.endPTS-t.startPTS),i.duration&&(r=i),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(i.elementaryStreams=t.elementaryStreams),i.loader=t.loader,t.hasStats&&(i.stats=t.stats),t.initSegment&&(i.initSegment=t.initSegment,a=t.initSegment)});let l=e.fragments,o=e.fragmentHint?l.concat(e.fragmentHint):l;if(a&&o.forEach(t=>{var e;t&&(!t.initSegment||t.initSegment.relurl===(null==(e=a)?void 0:e.relurl))&&(t.initSegment=a)}),e.skippedSegments){if(e.deltaUpdateFailed=l.some(t=>!t),e.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments ski
1pped in delta playlist");for(let t=e.skippedSegments;t--;)l.shift();e.startSN=l[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,i){let{dateRanges:r,recentlyRemovedDateranges:s}=e,a=k({},t);s&&s.forEach(t=>{delete a[t]});let n=Object.keys(a).length;return n?(Object.keys(r).forEach(t=>{let e=a[t],s=new eC(r[t].attr,e);s.isValid?(a[t]=s,e||(s.tagOrder+=n)):i.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(tY(r[t].attr),'"'))}),a):r}(t.dateRanges,e,i));let r=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&e7(o[t],o[t-1],r);e4(r,e)}e.endCC=l[l.length-1].cc}if(!e.startCC){var h;let i=ic(t,e.startSN-1);e.startCC=null!=(h=null==i?void 0:i.cc)?h:l[0].cc}(function(t,e,i){if(t&&e){let r=0;for(let s=0,a=t.length;s<=a;s++){let a=t[s],n=e[s+r];a&&n&&a.index===n.index&&a.fragment.sn===n.fragment.sn?i(a,n):r--}}})(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),r?ia(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,i):io(t,e),l.length&&(e.totalduration=e.edge-l[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let t=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=t),e.driftEndTime=d,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}(i,r,this);let t=r.playlistParsingError;if(t){this.warn(t);let i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var u;let{networkDetails:s}=e;i.trigger(h.ERROR,{type:l.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(u=r.fragments[0])?void 0:u.type,networkDetails:s,stats:a});return}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=a.loading.start);let p=this.hls.mainForwardBufferInfo,E=p?p.end-p.len:0,y=(r.edge-E)*1e3,v=id(r,y);if(r.requestScheduled+v<n?r.requestScheduled=n:r.requestScheduled+=v,this.log("live playlist ".concat(t," ").concat(r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED")),!this.canLoad||!r.live)return;if(r.canBlockReload&&r.endSN&&r.advanced){let t=this.hls.config.lowLatencyMode,s=r.lastPartSn,a=r.endSN,l=r.lastPartIndex,o=s===a;-1!==l?o?(f=a+1,g=t?0:l):(f=s,g=t?l+1:r.maxPartIndex):f=a+1;let h=r.age,d=h+r.ageHeader,u=Math.min(d-r.partTarget,1.5*r.targetduration);if(u>0){if(d>3*r.targetduration)this.log("Playlist last advanced ".concat(h.toFixed(2),"s ago. Omitting segment and part directives.")),f=void 0,g=void 0;else if(null!=i&&i.tuneInGoal&&d-r.partTarget>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(i.tuneInGoal," to: ").concat(u," with playlist age: ").concat(r.age)),u=0;else{let t=Math.floor(u/r.targetduration);f+=t,void 0!==g&&(g+=Math.round(u%r.targetduration/r.partTarget)),this.log("CDN Tune-in age: ".concat(r.ageHeader,"s last advanced ").concat(h.toFixed(2),"s goal: ").concat(u," skip sn ").concat(t," to part ").concat(g))}r.tuneInGoal=u}if(c=this.getDeliveryDirectives(r,e.deliveryDirectives,f,g),t||!o){r.requestScheduled=n,this.loadingPlaylist(m,c);return}}else(r.canBlockReload||r.canSkipUntil)&&(c=this.getDeliveryDirectives(r,e.deliveryDirectives,f,g));c&&void 0!==f&&r.canBlockReload&&(r.requestScheduled=a.loading.first+Math.max(v-2*d,v/2)),this.scheduleLoading(m,c,r)}else this.clearTimer()}scheduleLoading(t,e,i){let r=i||t.details;if(!r){this.loadingPlaylist(t,e);return}let s=self.performance.now(),a=r.requestScheduled;if(s>=a){this.loadingPlaylist(t,e);return}let n=a-s;this.log("reload live playlist ".concat(t.name||t.bitrate+"bps"," in ").concat(Math.round(n)," ms")),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),n)}getDeliveryDirectives(t,e,i,r){let s=tB(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,r=e.part,s=tU.No),new tG(i,r,s)}checkRetry(t){let e=t.details,i=t4(t),r=t.errorAction,{action:s,retryCount:a=0,retryConfig:n}=r||{},l=!!r&&!!n&&(s===ei.RetryRequest||!r.resolved&&s===ei.SendAlternateToPenaltyBox);if(l){var o;if(a>=n.maxNumRetry)return!1;if(i&&null!=(o=t.context)&&o.deliveryDirectives)this.warn("Retrying playlist loading ".concat(a+1,"/").concat(n.maxNumRetry,' after "').concat(e,'" without delivery-directives')),this.loadPlaylist();else{let t=t9(n,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn("Retrying playlist loading ".concat(a+1,"/").concat(n.maxNumRetry,' after "').concat(e,'" in ').concat(t,"ms"))}t.levelRetry=!0,r.resolved=!0}return l}constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}}function rG(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!rK(t[i].attrs,e[i].attrs))return!1;return!0}function rK(t,e,i){let r=t["STABLE-RENDITION-ID"];return r&&!i?r===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}function rV(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class rH extends rB{registerListeners(){let{hls:t}=this;t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.MANIFEST_PARSED,this.onManifestParsed,this),t.on(h.LEVEL_LOADING,this.onLevelLoading,this),t.on(h.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(h.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:t}=this;t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.MANIFEST_PARSED,this.onManifestParsed,this),t.off(h.LEVEL_LOADING,this.onLevelLoading,this),t.off(h.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(h.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(h.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){let{id:i,groupId:r,details:s}=e,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn("Audio track with id:".concat(i," and group:").concat(r," not found in active group ").concat(null==a?void 0:a.groupId));return}let n=a.details;a.details=e.details,this.log("Audio track ".concat(i,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(r," loaded [").concat(s.startSN,"-").concat(s.endSN,"]")),i===this.trackId&&this.playlistLoaded(i,e,n)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){let e=this.hls.levels[t];if(!e)return;let i=e.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>(null==r?void 0:r.indexOf(t))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let t=this.tracks.filter(t=>!i||-1!==i.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=t;let e=this.hls.config.audioPreference;if(!s&&e){let i=tX(e,t,tz);if(i>-1)s=t[i];else{let t=tX(e,this.tracks);s=this.tracks[t]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null)),this.log("Updating audio tracks, ".concat(t.length," track(s) found in group(s): ").concat(null==i?void 0:i.join(","))),this.hls.trigger(h.AUDIO_TRACKS_UPDATED,{audioTracks:t});let n=this.trackId;if(-1!==r&&-1===n)this.setAudioTrack(r);else if(t.length&&-1===n){var a;let e=Error("No audio track selected for current audio group-ID(s): ".concat(null==(a=this.groupIds)?void 0:a.join(",")," track count: ").concat(t.length));this.warn(e.message),this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==I.AUDIO_TRACK||e.context.
1id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){let e=this.hls;if(e.config.audioPreference=t,t){let i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let r=this.currentTrack;if(r&&tQ(t,r,tz))return r;let s=tX(t,this.tracksInGroup,tz);if(s>-1){let t=this.tracksInGroup[s];return this.setAudioTrack(s),t}if(r){let r=e.loadLevel;-1===r&&(r=e.firstAutoLevel);let s=function(t,e,i,r,s){let a=e[r],n=e.reduce((t,e,i)=>{let r=e.uri;return(t[r]||(t[r]=[])).push(i),t},{})[a.uri];n.length>1&&(r=Math.max.apply(Math,n));let l=a.videoRange,o=a.frameRate,h=a.codecSet.substring(0,4),d=t$(e,r,e=>{if(e.videoRange!==l||e.frameRate!==o||e.codecSet.substring(0,4)!==h)return!1;let r=e.audioGroups;return tX(t,i.filter(t=>!r||-1!==r.indexOf(t.groupId)),s)>-1});return d>-1?d:t$(e,r,e=>{let r=e.audioGroups;return tX(t,i.filter(t=>!r||-1!==r.indexOf(t.groupId)),s)>-1})}(t,e.levels,i,r,tz);if(-1===s)return null;e.nextLoadLevel=s}if(t.channels||t.audioCodec){let e=tX(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t){let e=this.tracksInGroup;if(t<0||t>=e.length){this.warn("Invalid audio track id: ".concat(t));return}this.selectDefaultTrack=!1;let i=this.currentTrack,r=e[t],s=r.details&&!r.details.live;if(t===this.trackId&&r===i&&s||(this.log("Switching to audio-track ".concat(t,' "').concat(r.name,'" lang:').concat(r.lang," group:").concat(r.groupId," channels:").concat(r.channels)),this.trackId=t,this.currentTrack=r,this.hls.trigger(h.AUDIO_TRACK_SWITCHING,P({},r)),s))return;let a=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(a)}findTrackId(t){let e=this.tracksInGroup;for(let i=0;i<e.length;i++){let r=e[i];if((!this.selectDefaultTrack||r.default)&&(!t||tQ(t,r,tz)))return i}if(t){let{name:i,lang:r,assocLang:s,characteristics:a,audioCodec:n,channels:l}=t;for(let t=0;t<e.length;t++)if(tQ({name:i,lang:r,assocLang:s,characteristics:a,audioCodec:n,channels:l},e[t],tz))return t;for(let i=0;i<e.length;i++){let r=e[i];if(rK(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){let r=e[i];if(rK(t.attrs,r.attrs,["LANGUAGE"]))return i}}return -1}loadPlaylist(t){super.loadPlaylist();let e=this.currentTrack;this.shouldLoadPlaylist(e)&&tZ(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);let i=t.id,r=t.groupId,s=this.getUrlWithDirectives(t.url,e),a=t.details,n=null==a?void 0:a.age;this.log("Loading audio-track ".concat(i,' "').concat(t.name,'" lang:').concat(t.lang," group:").concat(r).concat((null==e?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:"").concat(n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""," ").concat(s)),this.hls.trigger(h.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null,track:t})}constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}}class rY{destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;let r=this.queues[e];r.push(t),1!==r.length||i||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{this.append({label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}},t)})}prependBlocker(t){return new Promise(e=>{this.queues&&this.queues[t].unshift({label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}})})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;let i=null==(e=t[0])?void 0:e.label;("async-blocker"===i||"async-blocker-prepend"===i)&&(t[0].execute(),t.splice(0,1))})}unblockAudio(t){null!==this.queues&&this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;let e=this.queues[t];if(e.length){let r=e[0];try{r.execute()}catch(s){var i;if(r.onError(s),null===this.queues||null===this.tracks)return;let e=null==(i=this.tracks[t])?void 0:i.buffer;null!=e&&e.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){let{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":"\n".concat(this.list("video"),"\n").concat(this.list("audio"),"\n").concat(this.list("audiovideo"),"}")}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?"".concat(t,": (").concat(this.listSbInfo(t),") ").concat(this.listOps(t)):""}listSbInfo(t){var e;let i=null==(e=this.tracks)?void 0:e[t],r=null==i?void 0:i.buffer;return r?"SourceBuffer".concat(r.updating?" updating":"").concat(i.ended?" ended":"").concat(i.ending?" ending":""):"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}}let rW=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rj="HlsJsTrackRemovedError";
1class rq extends Error{constructor(t){super(t),this.name=rj}}class rX extends C{hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:t}=this;t.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.MANIFEST_PARSED,this.onManifestParsed,this),t.on(h.BUFFER_RESET,this.onBufferReset,this),t.on(h.BUFFER_APPENDING,this.onBufferAppending,this),t.on(h.BUFFER_CODECS,this.onBufferCodecs,this),t.on(h.BUFFER_EOS,this.onBufferEos,this),t.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(h.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(h.FRAG_PARSED,this.onFragParsed,this),t.on(h.FRAG_CHANGED,this.onFragChanged,this),t.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:t}=this;t.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.MANIFEST_PARSED,this.onManifestParsed,this),t.off(h.BUFFER_RESET,this.onBufferReset,this),t.off(h.BUFFER_APPENDING,this.onBufferAppending,this),t.off(h.BUFFER_CODECS,this.onBufferCodecs,this),t.off(h.BUFFER_EOS,this.onBufferEos,this),t.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(h.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(h.FRAG_PARSED,this.onFragParsed,this),t.off(h.FRAG_CHANGED,this.onFragChanged,this),t.off(h.ERROR,this.onError,this)}transferMedia(){let{media:t,mediaSource:e}=this;if(!t)return null;let i={};if(this.operationQueue){let t=this.isUpdating();t||this.operationQueue.removeBlockers();let e=this.isQueued();(t||e)&&this.warn("Transfering MediaSource with".concat(e?" operations in queue":"").concat(t?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}let r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===e?k(i,r.tracks):this.sourceBuffers.forEach(t=>{let[e]=t;e&&(i[e]=k({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var i;let r=2;(!e.audio||e.video)&&e.altAudio||(r=1),this.bufferCodecEventsTotal=r,this.log("".concat(r," bufferCodec event(s) expected.")),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(t,e){let i=this.media=e.media;this.transferData=this.overrides=void 0;let r=N(this.appendSource);if(r){let t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);let s=this.mediaSource=e.mediaSource||new r;if(this.assignMediaSource(s),t)this._objectUrl=i.src,this.attachTransferred();else{let t=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{i.removeAttribute("src");let e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&s instanceof e,rQ(i),function(t,e){let i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log("".concat((null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"," media source: ").concat(null==(i=t.constructor)?void 0:i.name)),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){let t=this.media,e=this.transferData;if(!e||!t)return;let i=this.tracks,r=e.tracks,s=r?Object.keys(r):null,a=s?s.length:0,n=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&s&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log("attachTransferred: (bufferCodecEventsTotal ".concat(this.bufferCodecEventsTotal,")\nrequired tracks: ").concat(tY(i,(t,e)=>"initSegment"===t?void 0:e),";\ntransfer tracks: ").concat(tY(r,(t,e)=>"initSegment"===t?void 0:e),"}")),!U(r,i)){e.mediaSource=null,e.tracks=void 0;let s=t.currentTime,a=this.details,n=Math.max(s,(null==a?void 0:a.fragments[0].start)||0);if(n-s>1){this.log("attachTransferred: waiting for playback to reach new tracks start time ".concat(s," -> ").concat(n));return}this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'.concat(Object.keys(r),'"->"').concat(Object.keys(i),'") start time: ').concat(n," currentTime: ").concat(s)),this.onMediaDetaching(h.MEDIA_DETACHING,{}
1),this.onMediaAttaching(h.MEDIA_ATTACHING,e),t.currentTime=n;return}this.transferData=void 0,s.forEach(t=>{let e=r[t];if(e){let i=e.buffer;if(i){let r=this.fragmentTracker,s=e.id;if(r.hasFragments(s)||r.hasParts(s)){let e=eI.getBuffered(i);r.detectEvictedFragments(t,e,s,null,!0)}let a=rz(t),n=[t,i];this.sourceBuffers[a]=n,i.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,e)}}}),n(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),n()}get mediaSourceOpenOrEnded(){var t;let e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){let i=!!e.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:s,_objectUrl:a}=this;if(s){if(this.log("media source ".concat(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(t=>{let[e]=t;e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let t="open"===s.readyState;try{let e=s.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),s.removeSourceBuffer(e[i]);t&&s.endOfStream()}catch(t){this.warn("onMediaDetaching: ".concat(t.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&rQ(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(h.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(t=>{let[e]=t;e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(t){var e,i;let r=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),r)try{null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(e){this.warn("onBufferReset ".concat(t),e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[rz(t)]=[null,null];let e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new rY(this.tracks)}onBufferCodecs(t,e){var i;let r=this.tracks,s=Object.keys(e);this.log('BUFFER_CODECS: "'.concat(s,'" (current SB count ').concat(this.sourceBufferCount,")"));let a="audiovideo"in e&&(r.audio||r.video)||r.audiovideo&&("audio"in e||"video"in e),n=!a&&this.sourceBufferCount&&this.media&&s.some(t=>!r[t]);if(a||n){this.warn('Unsupported transition between "'.concat(Object.keys(r),'" and "').concat(s,'" SourceBuffers'));return}s.forEach(t=>{var i,s;let{id:a,codec:n,levelCodec:l,container:o,metadata:h,supplemental:d}=e[t],c=r[t],u=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],f=null!=u&&u.buffer?u:c,g=(null==f?void 0:f.pendingCodec)||(null==f?void 0:f.codec),m=null==f?void 0:f.levelCodec;c||(c=r[t]={buffer:void 0,listeners:[],codec:n,supplemental:d,container:o,levelCodec:l,metadata:h,id:a});let p=tD(g,m),E=null==p?void 0:p.replace(rW,"$1"),y=tD(n,l),v=null==(s=y)?void 0:s.replace(rW,"$1");y&&p&&E!==v&&("audio"===t.slice(0,5)&&(y=tb(y,this.appendSource)),this.log("switching codec ".concat(g," to ").concat(y)),y!==(c.pendingCodec||c.codec)&&(c.pendingCodec=y),c.container=o,this.appendChangeType(t,o,y))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(!(this.bufferCodecEventsTotal>1)||this.tracks.video||e.video||(null==(i=e.audio)?void 0:i.id)!=="main"||(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{let i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){let r="".concat(e,";codecs=").concat(i);this.append({label:"change-type=".concat(r),execute:()=>{let s=this.tracks[t];if(s){let a=s.buffer;null!=a&&a.changeType&&(this.log("changing ".concat(t," sourceBuffer type to ").concat(r)),a.changeType(r),s.codec=i,s.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Failed to change ".concat(t," SourceBuffer type"),e)}},t,this.isPending(this.tracks[t]))}blockAudio(t){var e;let i=t.start,r=i+.05*t.duration;if((null==(e=this.fragmentTracker.getAppendedFrag(i,R.MAIN))?void 0:e.gap)===!0)return;let s={label:"block-audio",execute:()=>{var t;let e=this.tracks.video;(this.lastVideoAppendEnd>r||null!=e&&e.buffer&&eI.isBuffered(e.buffer,r)||(null==(t=this.fragmentTracker.getAppendedFrag(r,R.MAIN))?void 0:t.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:s,frag:t},this.append(s,"audio",!0)}unblockAudio(){let{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){let{tracks:i}=this,{data:r,type:a,parent:n,frag:d,part:c,chunkMeta:u,offset:f}=e,g=u.buffering[a],{sn:m,cc:p}=d,E=self.performance.now();g.start=E;let y=d.stats.buffering,v=c?c.stats.buffering:null;0===y.start&&(y.start=E),v&&0===v.start&&(v.start=E);let T=i.audio,S=!1;"audio"===a&&(null==T?void 0:T.container)==="audio/mpeg"&&(S=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);let A=i.video,L=null==A?void 0:A.buffer;if(L&&"initSegment"!==m){let t=c||d,e=this.blockedAudioAppend;if("audio"!==a||"main"===n||this.blockedAudioAppend||A.ending||A.ended){if("video"===a){let i=t.end;if(e){let t=e.frag.start;(i>t||i<this.lastVideoAppendEnd||eI.isBuffered(L,t))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{let e=t.start+.05*t.duration,i=L.buffered,r=this.currentOp("video");(i.length||r)&&(r||eI.isBuffered(L,e)||!(this.lastVideoAppendEnd<e))||this.blockAudio(t)}}let I=(c||d).start;this.log('queuing "'.concat(a,'" append sn: ').concat(m).concat(c?" p: "+c.index:""," of ").concat(d.type===R.MAIN?"level":"track"," ").concat(d.level," cc: ").concat(p)),this.append({label:"append-".concat(a),execute:()=>{var t;g.executeStart=self.performance.now();let e=null==(t=this.tracks[a])?void 0:t.buffer;e&&(S?this.updateTimestampOffset(e,I,.1,a,m,p):void 0!==f&&s(f)&&this.updateTimestampOffset(e,f,1e-6,a,m,p)),this.appendExecutor(r,a)},onStart:()=>{},onComplete:()=>{let t=self.performance.now();g.executeEnd=g.end=t,0===y.first&&(y.first=t),v&&0===v.first&&(v.first=t);let e={};
1this.sourceBuffers.forEach(t=>{let[i,r]=t;i&&(e[i]=eI.getBuffered(r))}),this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(h.BUFFER_APPENDED,{type:a,frag:d,part:c,chunkMeta:u,parent:d.type,timeRanges:e})},onError:t=>{var e;let i={type:l.MEDIA_ERROR,parent:d.type,details:o.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:d,part:c,chunkMeta:u,error:t,err:t,fatal:!1},r=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)i.details=o.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!r)i.errorAction=ea(!0);else if(t.name===rj&&0===this.sourceBufferCount)i.errorAction=ea(!0);else{let t=++this.appendErrors[a];this.warn("Failed ".concat(t,"/").concat(this.hls.config.appendErrorMaxRetry,' times to append segment in "').concat(a,'" sourceBuffer (').concat(r||"no media error",")")),(t>=this.hls.config.appendErrorMaxRetry||r)&&(i.fatal=!0)}this.hls.trigger(h.ERROR,i)}},a,this.isPending(this.tracks[a]))}getFlushOp(t,e,i){return this.log('queuing "'.concat(t,'" remove ').concat(e,"-").concat(i)),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(h.BUFFER_FLUSHED,{type:t})},onError:r=>{this.warn("Failed to remove ".concat(e,"-").concat(i,' from "').concat(t,'" SourceBuffer'),r)}}}onBufferFlushing(t,e){let{type:i,startOffset:r,endOffset:s}=e;i?this.append(this.getFlushOp(i,r,s),i):this.sourceBuffers.forEach(t=>{let[e]=t;e&&this.append(this.getFlushOp(e,r,s),e)})}onFragParsed(t,e){let{frag:i,part:r}=e,s=[],a=r?r.elementaryStreams:i.elementaryStreams;a[W.AUDIOVIDEO]?s.push("audiovideo"):(a[W.AUDIO]&&s.push("audio"),a[W.VIDEO]&&s.push("video")),0===s.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: ".concat(i.type," level: ").concat(i.level," sn: ").concat(i.sn)),this.blockBuffers(()=>{let t=self.performance.now();i.stats.buffering.end=t,r&&(r.stats.buffering.end=t);let e=r?r.stats:i.stats;this.hls.trigger(h.FRAG_BUFFERED,{frag:i,part:r,stats:e,id:i.type})},s).catch(t=>{this.warn("Fragment buffered callback ".concat(t)),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(t=>{let[e]=t;if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(t=>{let[i]=t;if(i){let t=this.tracks[i];e.type&&e.type!==i||(t.ending=!0,t.ended||(t.ended=!0,this.log("".concat(i," buffer reached EOS"))))}});let r=(null==(i=this.overrides)?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(t=>{var e;let[i]=t;return i&&!(null!=(e=this.tracks[i])&&e.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:t}=this;if(!t||"open"!==t.readyState){t&&this.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(t.readyState));return}this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(h.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(h.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(t=>{let[e]=t;if(null!==e){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(t,e){let{details:i}=e;i.fragments.length&&(this.details=i,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===o.BUFFER_APPEND_ERROR&&e.frag){var i;let t=null==(i=e.errorAction)?void 0:i.nextAutoLevel;s(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:t,details:e,media:i}=this;if(!i||null===e||!this.sourceBufferCount)return;let r=t.config,a=i.currentTime,n=e.levelTargetDuration,l=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(s(l)&&l>=0){let t=Math.max(l,n);this.flushBackBuffer(a,n,Math.floor(a/n)*n-t)}let o=r.frontBufferFlushThreshold;if(s(o)&&o>0){let t=Math.max(Math.max(r.maxBufferLength,o),n);this.flushFrontBuffer(a,n,Math.floor(a/n)*n+t)}}
1flushBackBuffer(t,e,i){this.sourceBuffers.forEach(t=>{let[e,r]=t;if(r){let t=eI.getBuffered(r);if(t.length>0&&i>t.start(0)){var s;this.hls.trigger(h.BACK_BUFFER_REACHED,{bufferEnd:i});let t=this.tracks[e];if(null!=(s=this.details)&&s.live)this.hls.trigger(h.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended){this.log("Cannot flush ".concat(e," back buffer while SourceBuffer is in ended state"));return}this.hls.trigger(h.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(e=>{let[r,s]=e;if(s){let e=eI.getBuffered(s),a=e.length;if(a<2)return;let n=e.start(a-1),l=e.end(a-1);if(i>n||t>=n&&t<=l)return;this.hls.trigger(h.BUFFER_FLUSHING,{startOffset:n,endOffset:1/0,type:r})}})}getDurationAndRange(){var t;let{details:e,mediaSource:i}=this;if(!e||!this.media||(null==i?void 0:i.readyState)!=="open")return null;let r=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&i.setLiveSeekableRange){let t=Math.max(0,e.fragmentStart),i=Math.max(t,r);return{duration:1/0,start:t,end:i}}return{duration:1/0}}let a=null==(t=this.overrides)?void 0:t.duration;if(a)return s(a)?{duration:a}:null;let n=this.media.duration;return r>(s(i.duration)?i.duration:0)&&r>n||!s(n)?{duration:r}:null}updateMediaSource(t){let{duration:e,start:i,end:r}=t,a=this.mediaSource;this.media&&a&&"open"===a.readyState&&(a.duration!==e&&(s(e)&&this.log("Updating MediaSource duration to ".concat(e.toFixed(3))),a.duration=e),void 0!==i&&void 0!==r&&(this.log("MediaSource duration is set to ".concat(a.duration,". Setting seekable range to ").concat(i,"-").concat(r,".")),a.setLiveSeekableRange(i,r)))}get tracksReady(){let t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log("checkPendingTracks (pending: ".concat(e," codec events expected: ").concat(t,") ").concat(tY(i))),this.tracksReady){var r;let t=null==(r=this.transferData)?void 0:r.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let t={};this.sourceBuffers.forEach(e=>{let[i,r]=e;if(i){let e=this.tracks[i];t[i]={buffer:r,container:e.container,codec:e.codec,supplemental:e.supplemental,levelCodec:e.levelCodec,id:e.id,metadata:e.metadata}}}),this.hls.trigger(h.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(t=>{let[e]=t;this.executeNext(e)})}else{let t=Error("could not create source buffer for media codec(s)");this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){let{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let s in t){let a=t[s];if(this.isPending(a)){let t=this.getTrackCodec(a,s),n="".concat(a.container,";codecs=").concat(t);a.codec=t,this.log("creating sourceBuffer(".concat(n,")").concat(this.currentOp(s)?" Queued":""," ").concat(tY(a)));try{let t=i.addSourceBuffer(n),r=rz(s),l=[s,t];e[r]=l,a.buffer=t}catch(t){var r;this.error("error while trying to add sourceBuffer: ".concat(t.message)),this.shiftAndExecuteNext(s),null==(r=this.operationQueue)||r.removeBlockers(),delete this.tracks[s],this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:s,mimeType:n,parent:a.id});return}this.trackSourceBuffer(s,a)}}this.bufferCreated()}getTrackCodec(t,e){let i=t.supplemental,r=t.codec;i&&("video"===e||"audiovideo"===e)&&tv(i,"video")&&(r=function(t,e){let i=[];if(t){let e=t.split(",");for(let t=0;t<e.length;t++)ty(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(r,i));let s=tD(r,t.levelCodec);return s?"audio"===e.slice(0,5)?tb(s,this.appendSource):s:""}trackSourceBuffer(t,e){let i=e.buffer;if(!i)return;let r=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:r,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{let i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(h.BUFFER_FLUSHED,{type:t})})}get mediaSrc(){var t,e;let i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(t){let e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if((null==(e=this.mediaSource)?void 0:e.readyState)==="closed"){this.resetBuffer(t);return}let i=this.currentOp(t);
1i&&(i.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var i;let r=Error("".concat(t," SourceBuffer error. MediaSource readyState: ").concat(null==(i=this.mediaSource)?void 0:i.readyState));this.error("".concat(r),e),this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});let s=this.currentOp(t);s&&s.onError(r)}updateTimestampOffset(t,e,i,r,s,a){Math.abs(e-t.timestampOffset)>=i&&(this.log("Updating ".concat(r," SourceBuffer timestampOffset to ").concat(e," (sn: ").concat(s," cc: ").concat(a,")")),t.timestampOffset=e)}removeExecutor(t,e,i){let{media:r,mediaSource:a}=this,n=this.tracks[t],l=null==n?void 0:n.buffer;if(!r||!a||!l){this.warn("Attempting to remove from the ".concat(t," SourceBuffer, but it does not exist")),this.shiftAndExecuteNext(t);return}let o=s(r.duration)?r.duration:1/0,h=s(a.duration)?a.duration:1/0,d=Math.max(0,e),c=Math.min(i,o,h);c>d&&(!n.ending||n.ended)?(n.ended=!1,this.log("Removing [".concat(d,",").concat(c,"] from the ").concat(t," SourceBuffer")),l.remove(d,c)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){let i=this.tracks[e],r=null==i?void 0:i.buffer;if(!r)throw new rq("Attempting to append to the ".concat(e," SourceBuffer, but it does not exist"));i.ending=!1,i.ended=!1,r.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn("SourceBuffer blocked callback ".concat(t)),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn("Callback run without blocking ".concat(this.operationQueue," ").concat(t))}}isUpdating(){return this.sourceBuffers.some(t=>{let[e,i]=t;return e&&i.updating})}isQueued(){return this.sourceBuffers.some(t=>{let[e]=t;return e&&!!this.currentOp(e)})}isPending(t){return!!t&&!t.buffer}blockBuffers(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);let{operationQueue:i}=this,r=e.map(t=>this.appendBlocker(t));return e.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;let i=null==(e=this.tracks[t])?void 0:e.buffer;i&&!i.updating&&this.shiftAndExecuteNext(t)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,e)=>{let[i]=e;return t+(i?1:0)},0)}get sourceBufferTypes(){return this.sourceBuffers.map(t=>{let[e]=t;return e}).filter(t=>!!t)}addBufferListener(t,e,i){let r=this.tracks[t];if(!r)return;let s=r.buffer;if(!s)return;let a=i.bind(this,t);r.listeners.push({event:e,listener:a}),s.addEventListener(e,a)}removeBufferListeners(t){let e=this.tracks[t];if(!e)return;let i=e.buffer;i&&(e.listeners.forEach(t=>{i.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}constructor(t,e){var i;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&(null==(e=this.mediaSource)?void 0:e.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{let{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(h.MEDIA_ATTA
1CHED,{media:e,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error("Media element src was set while attaching MediaSource (".concat(e," > ").concat(t,")"))},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=N(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}}function rQ(t){let e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function rz(t){return"audio"===t?1:0}class r${setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:t}=this;t.on(h.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(h.MANIFEST_PARSED,this.onManifestParsed,this),t.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(h.BUFFER_CODECS,this.onBufferCodecs,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:t}=this;t.off(h.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(h.MANIFEST_PARSED,this.onManifestParsed,this),t.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(h.BUFFER_CODECS,this.onBufferCodecs,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){let i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){let i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&s(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let t=this.hls.levels;if(t.length){let e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log("Setting autoLevelCapping to ".concat(i,": ").concat(t[i].height,"p@").concat(t[i].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){let e=this.hls.levels;if(!e.length)return -1;let i=e.filter((e,i)=>this.isLevelAllowed(e)&&i<=t);return this.clientRect=null,r$.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let t=this.media,e={width:0,height:0};if(t){let i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,i){if(!(null!=t&&t.length))return -1;let r=(t,e)=>!e||t.width!==e.width||t.height!==e.height,s=t.length-1,a=Math.max(e,i);for(let e=0;e<t.length;e+=1){let i=t[e];if((i.width>=a||i.height>=a)&&r(i,t[e+1])){s=e;break}}return s}constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}}let rZ={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",TIMED_TEXT:"tt"};class rJ{constructor(t,e){Array.isArray(t)&&(t=t.map(t=>t instanceof rJ?t:new rJ(t))),this.value=t,this.params=e}}
1function r0(t,e,i){return Error("failed to ".concat("serialize",' "').concat(Array.isArray(t)?JSON.stringify(t):t instanceof Map?"Map{}":t instanceof Set?"Set{}":"object"==typeof t?JSON.stringify(t):String(t),'" as ').concat(e),{cause:i})}class r1{constructor(t){this.description=t}}let r2="Bare Item";function r3(t){if(t<-999999999999999||999999999999999<t)throw r0(t,"Integer");return t.toString()}let r4=/[\x00-\x1f\x7f]+/;function r5(t){let e=t.description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw r0(e,"Token");return e}function r8(t){switch(typeof t){case"number":if(!s(t))throw r0(t,r2);if(Number.isInteger(t))return r3(t);return function(t){let e=function t(e,i){if(e<0)return-t(-e,i);let r=Math.pow(10,i);if(!(Math.abs(e*r%1-.5)<Number.EPSILON))return Math.round(e*r)/r;{let t=Math.floor(e*r);return(t%2==0?t:t+1)/r}}(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw r0(t,"Decimal");let i=e.toString();return i.includes(".")?i:"".concat(i,".0")}(t);case"string":return function(t){if(r4.test(t))throw r0(t,"String");return'"'.concat(t.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(t);case"symbol":return r5(t);case"boolean":return function(t){if("boolean"!=typeof t)throw r0(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return"@".concat(r3(t.getTime()/1e3));if(t instanceof Uint8Array)return function(t){if(!1===ArrayBuffer.isView(t))throw r0(t,"Byte Sequence");return":".concat(btoa(String.fromCharCode(...t)),":")}(t);if(t instanceof r1)return r5(t);default:throw r0(t,r2)}}function r6(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw r0(t,"Key");return t}function r9(t){return null==t?"":Object.entries(t).map(t=>{let[e,i]=t;return!0===i?";".concat(r6(e)):";".concat(r6(e),"=").concat(r8(i))}).join("")}function r7(t){return t instanceof rJ?"".concat(r8(t.value)).concat(r9(t.params)):r8(t)}function st(t,e){return function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!=typeof t||null==t)throw r0(t,"Dict");let i=t instanceof Map?t.entries():Object.entries(t),r=(null==e?void 0:e.whitespace)?" ":"";return Array.from(i).map(t=>{let[e,i]=t;i instanceof rJ==!1&&(i=new rJ(i));let r=r6(e);if(!0===i.value)r+=r9(i.params);else if(r+="=",Array.isArray(i.value)){var s;r+=(s=i,"(".concat(s.value.map(r7).join(" "),")").concat(r9(s.params)))}else r+=r7(i);return r}).join(",".concat(r))}(t,e)}let se="CMCD-Object",si="CMCD-Request",sr="CMCD-Session",ss="CMCD-Status",sa={br:se,ab:se,d:se,ot:se,tb:se,tpb:se,lb:se,tab:se,lab:se,url:se,pb:si,bl:si,tbl:si,dl:si,ltc:si,mtp:si,nor:si,nrr:si,rc:si,sn:si,sta:si,su:si,ttfb:si,ttfbb:si,ttlb:si,cmsdd:si,cmsds:si,smrt:si,df:si,cs:si,ts:si,cid:sr,pr:sr,sf:sr,sid:sr,st:sr,v:sr,msd:sr,bs:ss,bsd:ss,cdn:ss,rtp:ss,bg:ss,pt:ss,ec:ss,e:ss},sn={REQUEST:si},sl="event",so=t=>Math.round(t),sh=(t,e)=>Array.isArray(t)?t.map(t=>sh(t,e)):t instanceof rJ&&"string"==typeof t.value?new rJ(sh(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){let i=new URL(t),r=new URL(e);if(i.origin!==r.origin)return t;let s=i.pathname.split("/").slice(1),a=r.pathname.split("/").slice(1,-1);for(;s[0]===a[0];)s.shift(),a.shift();for(;a.length;)a.shift(),s.unshift("..");return s.join("/")+i.search+i.hash}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),sd=t=>100*so(t/100),sc={br:so,d:so,bl:sd,dl:sd,mtp:sd,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof rJ&&"string"==typeof t.value?i=new rJ([t]):"string"==typeof t&&(i=[t])),sh(i,e)},rtp:sd,tb:so},su="request",sf="response",sg=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],sm=["e"],sp=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function sE(t){return sp.test(t)}let sy=["d","dl","nor","ot","rtp","su"],sv=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],sT=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function sS(t){return sT.includes(t)||sE(t)}let sA={[sf]:function(t){return sg.includes(t)||sy.includes(t)||sv.includes(t)||sE(t)},[sl]:function(t){return sg.includes(t)||sm.includes(t)||sE(t)},[su]:function(t){return sg.includes(t)||sy.includes(t)||sE(t)}};function sL(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};if(null==t||"object"!=typeof t)return i;let r=e.version||t.v||1,a=e.reportingMode||su,n=1===r?sS:sA[a],l=Object.keys(t).filter(n),o=e.filter;"function"==typeof o&&(l=l.filter(o));let h=a===sf||a===sl;h&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");let d=k({},sc,e.formatters),c={version:r,reportingMode:a,baseUrl:e.baseUrl};
1return l.sort().forEach(e=>{var a;let n=t[e],l=d[e];if("function"==typeof l&&(n=l(n,c)),"v"===e){if(1===r)return;n=r}("pr"!=e||1!==n)&&(h&&"ts"===e&&!s(n)&&(n=Date.now()),("number"==typeof(a=n)?s(a):null!=a&&""!==a&&!1!==a)&&(["ot","sf","st","e","sta"].includes(e)&&"string"==typeof n&&(n=new r1(n)),i[e]=n))}),i}let sI=/CMCD=[^&#]+/;class sR{registerListeners(){let t=this.hls;t.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(h.MEDIA_DETACHED,this.onMediaDetached,this),t.on(h.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let t=this.hls;t.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(h.MEDIA_DETACHED,this.onMediaDetached,this),t.off(h.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var i,r;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer}createData(){var t;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};k(e,this.createData());let i=e.ot===rZ.INIT||e.ot===rZ.VIDEO||e.ot===rZ.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);let{includeKeys:r}=this;r&&(e=Object.keys(e).reduce((t,i)=>(r.includes(i)&&(t[i]=e[i]),t),{}));let s={baseUrl:t.url};if(this.useHeaders){var a;t.headers||(t.headers={}),a=t.headers,k(a,function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};return t?Object.entries(function(t,e){let i={};if(!t)return i;let r=Object.keys(t),s=e?Object.keys(e).reduce((t,i)=>{var r;return null===(r=e[i])||void 0===r||r.forEach(e=>t[e]=i),t},{}):{};return r.reduce((e,i)=>{var r;let a=sa[i]||s[i]||sn.REQUEST;return(null!==(r=e[a])&&void 0!==r?r:e[a]={})[i]=t[i],e},i)}(sL(t,e),null==e?void 0:e.customHeaderMap)).reduce((t,e)=>{let[i,r]=e,s=st(r,{whitespace:!1});return s&&(t[i]=s),t},i):i}(e,s))}else t.url=function(t,e,i){let r=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!t)return"";let i=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t?encodeURIComponent(function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t?st(sL(t,e),{whitespace:!1}):""}(t,e)):""}(t,e);return"".concat("CMCD","=").concat(i)}(e,i);if(!r)return t;if(sI.test(t))return t.replace(sI,r);let s=t.includes("?")?"&":"?";return"".concat(t).concat(s).concat(r)}(t.url,e,s)}getNextFrag(t){var e;let i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){let e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;let{index:i,fragment:r}=t,s=null==(e=this.hls.levels[r.level])||null==(e=e.details)?void 0:e.partList;if(s){let{sn:t}=r;for(let e=s.length-1;e>=0;e--){let r=s[e];if(r.index===i&&r.fragment.sn===t)return s[e+1]}}}getObjectType(t){let{type:e}=t;return"subtitle"===e?rZ.TIMED_TEXT:"initSegment"===t.sn?rZ.INIT:"audio"===e?rZ.AUDIO:"main"===e?this.hls.audioTracks.length?rZ.VIDEO:rZ.MUXED:void 0}getTopBandwidth(t){let e,i=0,r=this.hls;if(t===rZ.AUDIO)e=r.audioTracks;else{let t=r.maxAutoLevel,i=t>-1?t+1:r.levels.length;e=r.levels.slice(0,i)}return e.forEach(t=>{t.bitrate>i&&(i=t.bitrate)}),i>0?i:NaN}getBufferLength(t){let e=this.media,i=t===rZ.AUDIO?this.audioBuffer:this.videoBuffer;return i&&e?1e3*eI.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){let{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}constructor(t){this.loader=void 0,this.loader=new i(t)}}}createFragmentLoader(){let{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}constructor(t){this.loader=void 0,this.loader=new i(t)}}}constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:rZ.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{let{frag:e,part:i}=t,r=this.hls.levels[e.level],s=this.getObjectType(e),a={d:1e3*(i||e).duration,ot:s};(s===rZ.VIDEO||s===rZ.AUDIO||s==rZ.MUXED)&&(a.br=r.bitrate/1e3,a.tb=this.getTopBandwidth(s)/1e3,a.bl=this.getBufferLength(s));let n=i?this.getNextPart(i):this.getNextFrag(e);null!=n&&n.url&&n.url!==e.url&&(a.nor=n.url),this.apply(t,a)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=t;let e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||t.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}}class sb extends C{registerListeners(){let t=this.hls;t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(h.MANIFEST_PARSED,this.onManifestParsed,this),t.on(h.ERROR,this.onError,this)}unregisterListeners(){let t=this.hls;t&&(t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(h.MANIFEST_PARSED,this.onManifestParsed,this),t.off(h.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>
1(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){let e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){let{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){let{errorAction:i}=e;if((null==i?void 0:i.action)===ei.SendAlternateToPenaltyBox&&i.flags===er.MoveAllAlternatesMatchingHost){let t=this.levels,r=this._pathwayPriority,s=this.pathwayId;if(e.context){let{groupId:i,pathwayId:r,type:a}=e.context;i&&t?s=this.getPathwayForGroupId(i,a,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&t&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),e.details!==o.BUFFER_APPEND_ERROR||e.fatal?i.resolved||this.warn("Could not resolve ".concat(e.details,' ("').concat(e.error.message,'") with content-steering for Pathway: ').concat(s," levels: ").concat(t?t.length:t," priorities: ").concat(tY(r)," penalized: ").concat(tY(this.penalizedPathways))):i.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){let i=t[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(i,'"')),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log("Found ".concat(e.length,"/").concat(t.length,' levels in Pathway "').concat(this.pathwayId,'"')),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;let i=this.penalizedPathways,r=performance.now();
1Object.keys(i).forEach(t=>{r-i[t]>3e5&&delete i[t]});for(let r=0;r<t.length;r++){let s=t[r];if(s in i)continue;if(s===this.pathwayId)return;let a=this.hls.nextLoadLevel,n=this.hls.levels[a];if((e=this.getLevelsForPathway(s)).length>0){this.log('Setting Pathway to "'.concat(s,'"')),this.pathwayId=s,im(e),this.hls.trigger(h.LEVELS_UPDATED,{levels:e});let t=this.hls.levels[a];n&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==n.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==n.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(n.bitrate," to ").concat(t.bitrate)),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(t,e,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(e===I.AUDIO_TRACK&&r[i].hasAudioGroup(t)||e===I.SUBTITLE_TRACK&&r[i].hasSubtitleGroup(t))return r[i].pathwayId;return i}clonePathways(t){let e=this.levels;if(!e)return;let i={},r={};t.forEach(t=>{let{ID:s,"BASE-ID":a,"URI-REPLACEMENT":n}=t;if(e.some(t=>t.pathwayId===s))return;let l=this.getLevelsForPathway(a).map(t=>{let e=new eP(t.attrs);e["PATHWAY-ID"]=s;let a=e.AUDIO&&"".concat(e.AUDIO,"_clone_").concat(s),l=e.SUBTITLES&&"".concat(e.SUBTITLES,"_clone_").concat(s);a&&(i[e.AUDIO]=a,e.AUDIO=a),l&&(r[e.SUBTITLES]=l,e.SUBTITLES=l);let o=sk(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",n),h=new tK({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:o,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)h.addGroupId("audio","".concat(t.audioGroups[e],"_clone_").concat(s));if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text","".concat(t.subtitleGroups[e],"_clone_").concat(s));return h});e.push(...l),sD(this.audioTracks,i,n,s),sD(this.subtitleTracks,r,n,s)})}loadSteeringManifest(t){let e;let i=this.hls.config,r=i.loader;this.loader&&this.loader.destroy(),this.loader=new r(i);try{e=new self.URL(t)}catch(e){this.enabled=!1,this.log("Failed to parse Steering Manifest URI: ".concat(t));return}if("data:"!==e.protocol){let t=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);e.searchParams.set("_HLS_pathway",this.pathwayId),e.searchParams.set("_HLS_throughput",""+t)}let s={responseType:"json",url:e.href},a=i.steeringManifestLoadPolicy.default,n=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};this.log("Requesting steering manifest: ".concat(e)),this.loader.load(s,l,{onSuccess:(t,i,r,s)=>{this.log('Loaded steering manifest: "'.concat(e,'"'));let a=t.data;if((null==a?void 0:a.VERSION)!==1){this.log("Steering VERSION ".concat(a.VERSION," not supported!"));return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":n,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":o}=a;if(n)try{this.uri=new self.URL(n,e).href}catch(t){this.enabled=!1,this.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(n));return}this.scheduleRefresh(this.uri||r.url),l&&this.clonePathways(l);let d={steeringManifest:a,url:e.toString()};this.hls.trigger(h.STEERING_MANIFEST_LOADED,d),o&&this.updatePathwayPriority(o)},onError:(t,e,i,r)=>{if(this.log("Error loading steering manifest: ".concat(t.code," ").concat(t.text," (").concat(e.url,")")),this.stopLoad(),410===t.code){this.enabled=!1,this.log("Steering manifest ".concat(e.url," no longer available"));return}let s=1e3*this.timeToLoad;if(429===t.code){let t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){let e=t.getResponseHeader("Retry-After");e&&(s=1e3*parseFloat(e))}this.log("Steering manifest ".concat(e.url," rate limited"));return}this.scheduleRefresh(this.uri||e.url,s)},onTimeout:(t,e,i)=>{this.log("Timeout loading steering manifest (".concat(e.url,")")),this.scheduleRefresh(this.uri||e.url)}})}scheduleRefresh(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;let i=null==(e=this.hls)?void 0:e.media;if(i&&!i.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,1e3*this.timeToLoad)},e)}constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}}function sD(t,e,i,r){t&&Object.keys(e).forEach(s=>{let a=t.filter(t=>t.groupId===s).map(t=>{let a=k({},t);return a.details=void 0,a.attrs=new eP(a.attrs),a.url=a.attrs.URI=sk(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=e[s],a.attrs["PATHWAY-ID"]=r,a});t.push(...a)})}function sk(t,e,i,r){let s;let{HOST:a,PARAMS:n,[i]:l}=r;e&&(s=null==l?void 0:l[e])&&(t=s);let o=new self.URL(t);
1return a&&!s&&(o.host=a),n&&Object.keys(n).sort().forEach(t=>{t&&o.searchParams.set(t,n[t])}),o.href}class s_ extends C{destroy(){this.onDestroying(),this.onMediaDetached();let t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(h.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(h.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(h.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(h.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(h.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(h.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){let{drmSystems:e,widevineLicenseUrl:i}=this.config,r=null==e?void 0:e[t];return r?r.licenseUrl:t===eV.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(t){let e=this.getLicenseServerUrl(t);if(void 0===e)throw Error('no license server URL configured for key-system "'.concat(t,'"'));return e}getServerCertificateUrl(t){let{drmSystems:e}=this.config,i=null==e?void 0:e[t];if(i)return i.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'.concat(t,'"]'))}attemptKeySystemAccess(t){let e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,r=e.map(t=>t.audioCodec).filter(i),s=e.map(t=>t.videoCodec).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise((e,i)=>{let a=t=>{let n=t.shift();this.getMediaKeysPromise(n,r,s).then(t=>e({keySystem:n,mediaKeys:t})).catch(e=>{t.length?a(t):e instanceof sC?i(e):i(new sC({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};a(t)})}requestMediaKeySystemAccess(t,e){let{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t="Configured requestMediaKeySystemAccess is not a function ".concat(i);return null===eq&&"http:"===self.location.protocol&&(t="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){var r;let s=function(t,e,i,r){let s;switch(t){case eV.FAIRPLAY:s=["cenc","sinf"];break;case eV.WIDEVINE:case eV.PLAYREADY:s=["cenc"];break;case eV.CLEARKEY:s=["cenc","keyids"];break;default:throw Error("Unknown key-system: ".concat(t))}return[{initDataTypes:s,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:"audio/mp4; codecs=".concat(t),robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:i.map(t=>({contentType:"video/mp4; codecs=".concat(t),robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}(t,e,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[t],n=null==(r=a)?void 0:r.keySystemAccess;if(!n){this.log('Requesting encrypted media "'.concat(t,'" key-system access with config: ').concat(tY(s))),n=this.requestMediaKeySystemAccess(t,s);let e=a=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch(e=>{this.log('Failed to obtain access to key-system "'.concat(t,'": ').concat(e))}),n.then(i=>{this.log('Access for key-system "'.concat(i.keySystem,'" obtained'));let r=this.fetchServerCertificate(t);this.log('Create media-keys for "'.concat(t,'"'));let s=e.mediaKeys=i.createMediaKeys().then(i=>(this.log('Media-keys created for "'.concat(t,'"')),e.hasMediaKeys=!0,r.then(e=>e?this.setMediaKeysServerCertificate(i,t,e):i)));return s.catch(e=>{this.error('Failed to create media-keys for "'.concat(t,'"}: ').concat(e))}),s})}return n.then(()=>a.mediaKeys)}createMediaKeySessionContext(t){let{decryptdata:e,keySystem:i,mediaKeys:r}=t;this.log('Creating key-system session "'.concat(i,'" keyId: ').concat(G(e.keyId||[])," keyUri: ").concat(e.uri));let s=r.createSession(),a={decryptdata:e,keySystem:i,mediaKeys:r,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}renewKeySession(t){let e=t.decryptdata;if(e.pssh){let i=this.createMediaKeySessionContext(t),r=sP(e);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,e){let i=t.mediaKeysSession;return this.log('Updating key-session "'.concat(i.sessionId,'" for keyId ').concat(G(t.decryptdata.keyId||[]),"\n      } (data length: ").concat(e.byteLength,")")),i.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(t=>{let{hasMediaKeys:e}=t;return!!e}).map(t=>{let{keySystem:e}=t;return eW(e)}).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(t=>{let{keySystem:e,mediaKeys:i}=t;return this.attemptSetMediaKeys(e,i)})}selectKeySystem(t){return new Promise((e,i)=>{this.getKeySystemSelectionPromise(t).then(t=>{let{keySystem:r}=t,s=eW(r);s?e(s):i(Error('Unable to find format for key-system "'.concat(r,'"')))}).catch(i)})}selectKeySystemFormat(t){let e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: ".concat(t.sn," ").concat(t.type,": ").concat(t.level,") key formats ").concat(e.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){let e=ej(this.config),i=t.map(eY).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(i)}getKeyStatus(t){let{mediaKeySessions:e}=this;for(let r=0;r<e.length;r++){var i;let s=(i=e[r],t.keyId&&i.mediaKeysSession.keyStatuses.has(t.keyId)?i.mediaKeysSession.keyStatuses.get(t.keyId):t.matches(i.decryptdata)?i.keyStatus:void 0);if(s)return s}}loadKey(t){let e=t.keyInfo.decryptdata,i=sP(e),r=this.bannedKeyIds[i];if(r||"internal-error"===this.getKeyStatus(e)){let i=sO(r||"internal-error",e);return this.handleError(i,t.frag),Promise.reject(i)}let s="(keyId: ".concat(i,' format: "').concat(e.keyFormat,'" method: ').concat(e.method," uri: ").concat(e.uri,")");this.log("Starting session for key ".concat(s));let a=this.keyIdToKeySessionPromise[i];if(!a){let r=this.getKeySystemForKeyPromise(e).then(i=>{let{keySystem:r,mediaKeys:a}=i;return this.throwIfDestroyed(),this.log("Handle encrypted media sn: ".concat(t.frag.sn," ").concat(t.frag.type,": ").concat(t.frag.level," using key ").concat(s)),this.attemptSetMediaKeys(r,a).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:r,mediaKeys:a,decryptdata:e})))}).then(t=>{let i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",i,"playlist-key")});return r.catch(e=>this.handleError(e,t.frag)),this.keyIdToKeySessionPromise[i]=r,r}return a.catch(i=>{if(i instanceof sC){let r=P({},i.data);"internal-error"===this.getKeyStatus(e)&&(r.decryptdata=e);let s=new sC(r,i.message);this.handleError(s,t.frag)}}),a}throwIfDestroyed(){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0],!this.hls)throw Error("invalid state")}handleError(t,e){if(this.hls){if(t instanceof sC){e&&(t.data.frag=e);let i=t.data.decryptdata;this.error("".concat(t.message).concat(i?" (".concat(G(i.keyId||[]),")"):"")),this.hls.trigger(h.ERROR,t.data)}else this.error(t.message),this.hls.trigger(h.ERROR,{type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}}getKeySystemForKeyPromise(t){let e=sP(t),i=this.keyIdToKeySessionPromise[e];
1if(!i){let e=eY(t.keyFormat),i=e?[e]:ej(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=ej(this.config)),0===t.length)throw new sC({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(tY({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaKeys===e)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(t,'"'));let r=Promise.all(i).then(()=>{if(!this.media)throw this.mediaKeys=null,Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.mediaKeys=e,this.setMediaKeysQueue.push(r),r.then(()=>{this.log('Media-keys set for "'.concat(t,'"')),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===i.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,i,r){var s;let a=null==(s=this.config.drmSystems)||null==(s=s[t.keySystem])?void 0:s.generateRequest;if(a)try{let r=a.call(this.hls,e,i,t);if(!r)throw Error("Invalid response from configured generateRequest filter");e=r.initDataType,i=r.initData?r.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(t){if(this.warn(t.message),this.hls&&this.hls.config.debug)throw t}if(null===i)return this.log('Skipping key-session request for "'.concat(r,'" (no initData)')),Promise.resolve(t);let n=sP(t.decryptdata),h=t.decryptdata.uri;this.log('Generating key-session request for "'.concat(r,'" keyId: ').concat(n," URI: ").concat(h," (init data type: ").concat(e," length: ").concat(i.byteLength,")"));let d=new iP,c=t._onmessage=e=>{let i=t.mediaKeysSession;if(!i){d.emit("error",Error("invalid state"));return}let{messageType:r,message:s}=e;this.log('"'.concat(r,'" message event for session "').concat(i.sessionId,'" message size: ').concat(s.byteLength)),"license-request"===r||"license-renewal"===r?this.renewLicense(t,s).catch(t=>{d.eventNames().length?d.emit("error",t):this.handleError(t)}):"license-release"===r?t.keySystem===eV.FAIRPLAY&&this.updateKeySession(t,eU("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn('unhandled media key message type "'.concat(r,'"'))},u=(t,e)=>{let i;e.keyStatus=t,t.startsWith("usable")?d.emit("resolved"):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=sO(t,e.decryptdata):"expired"===t?i=Error("key expired (keyId: ".concat(n,")")):"released"===t?i=Error("key released"):"status-pending"===t||this.warn('unhandled key status change "'.concat(t,'" (keyId: ').concat(n,")")),i&&(d.eventNames().length?d.emit("error",i):this.handleError(i))},f=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession){d.emit("error",Error("invalid state"));return}let i=this.getKeyStatuses(t);if(!Object.keys(i).some(t=>"status-pending"!==i[t]))return;if("expired"===i[n]){this.log("Expired key ".concat(tY(i),' in key-session "').concat(t.mediaKeysSession.sessionId,'"')),this.renewKeySession(t);return}let r=i[n];if(r)u(r,t);else{var s;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(s=t.keyStatusTimeouts)[n]||(s[n]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;let e=this.getKeyStatus(t.decryptdata);if(e&&"status-pending"!==e)return this.log("No status for keyId ".concat(n,' in key-session "').concat(t.mediaKeysSession.sessionId,'". Using session key-status ').concat(e," from other session.")),u(e,t);this.log("key status for ".concat(n,' in key-session "').concat(t.mediaKeysSession.sessionId,'" timed out after ').concat(1e3,"ms")),u(r="internal-error",t)},1e3)),this.log("No status for keyId ".concat(n," (").concat(tY(i),")."))}};iA(t.mediaKeysSession,"message",c),iA(t.mediaKeysSession,"keystatuseschange",f);let g=new Promise((t,e)=>{d.on("error",e),d.on("resolved",t)});return t.mediaKeysSession.generateRequest(e,i).then(()=>{this.log('Request generated for key-session "'.concat(t.mediaKeysSession.sessionId,'" keyId: ').concat(n," URI: ").concat(h))}).catch(e=>{throw new sC({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t.decryptdata,fatal:!1},"Error generating key-session request: ".concat(e))}).then(()=>g).catch(e=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw e}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){let e={};
1return t.mediaKeysSession.keyStatuses.forEach((i,r)=>{if("string"==typeof r&&"object"==typeof i){let t=r;r=i,i=t}let s="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);t.keySystem===eV.PLAYREADY&&16===s.length&&eB(s);let a=G(s);"internal-error"===i&&(this.bannedKeyIds[a]=i),this.log('key status change "'.concat(i,'" for keyStatuses keyId: ').concat(a,' key-session "').concat(t.mediaKeysSession.sessionId,'"')),e[a]=i}),e}fetchServerCertificate(t){let e=this.config,i=new e.loader(e),r=this.getServerCertificateUrl(t);return r?(this.log('Fetching server certificate for "'.concat(t,'"')),new Promise((s,a)=>{let n={responseType:"arraybuffer",url:r},h=e.certLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(n,d,{onSuccess:(t,e,i,r)=>{s(t.data)},onError:(e,i,s,h)=>{a(new sC({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:P({url:n.url,data:void 0},e)},'"'.concat(t,'" certificate request failed (').concat(r,"). Status: ").concat(e.code," (").concat(e.text,")")))},onTimeout:(e,i,s)=>{a(new sC({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:n.url,data:void 0}},'"'.concat(t,'" certificate request timed out (').concat(r,")")))},onAbort:(t,e,i)=>{a(Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((r,s)=>{t.setServerCertificate(i).then(s=>{this.log("setServerCertificate ".concat(s?"success":"not supported by CDM"," (").concat(i.byteLength,') on "').concat(e,'"')),r(t)}).catch(t=>{s(new sC({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(e=>{throw new sC({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(t,e){let i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;let r=new DOMParser().parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let e;for(let i=0,r=s.length;i<r;i++){var a,n;let r=null==(a=(e=s[i]).querySelector("name"))?void 0:a.textContent,l=null==(n=e.querySelector("value"))?void 0:n.textContent;r&&l&&t.setRequestHeader(r,l)}}let l=r.querySelector("Challenge"),o=null==l?void 0:l.textContent;if(!o)throw Error("Cannot find <Challenge> in key message");return eU(atob(o))}setupLicenseXHR(t,e,i,r){let s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!i.decryptdata)throw Error("Key removed");return s.call(this.hls,t,e,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return t.open("POST",e,!0),s.call(this.hls,t,e,i,r)}).then(i=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:i||r})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e){let i=this.config.keyLoadPolicy.default;return new Promise((r,s)=>{let a=this.getLicenseServerUrlOrThrow(t.keySystem);this.log("Sending license request to URL: ".concat(a));let n=new XMLHttpRequest;n.responseType="arraybuffer",n.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return s(Error("invalid state"));if(4===n.readyState){if(200===n.status){this._requestLicenseFailureCount=0;let e=n.response;this.log("License received ".concat(e instanceof ArrayBuffer?e.byteLength:e));let i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,n,a,t)}catch(t){this.error(t)}r(e)}else{let h=i.errorRetry,d=h?h.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||n.status>=400&&n.status<500)s(new sC({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:n,response:{url:a,data:void 0,code:n.status,text:n.statusText}},"License Request XHR failed (".concat(a,"). Status: ").concat(n.status," (").concat(n.statusText,")")));else{let i=d-this._requestLicenseFailureCount+1;this.warn("Retrying license request, ".concat(i," attempts left")),this.requestLicense(t,e).then(r,s)}}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=n,this.setupLicenseXHR(n,a,t,e).then(e=>{let{xhr:i,licenseChallenge:r}=e;t.keySystem==eV.PLAYREADY&&(r=this.unpackPlayReadyKeyMessage(i,r)),i.send(r)}).catch(s)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;let i=e.media;this.media=i,iA(i,"encrypted",this.onMediaEncrypted),iA(i,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){let t=this.media;t&&(iL(t,"encrypted",this.onMediaEncrypted),iL(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;let e=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ez.clearKeyUriToKeyIdMap();let r=i.length;s_.CDMCleanupPromise=Promise.all(i.map(t=>this.removeSession(t)).concat((null==e||null==(t=e.setMediaKeys(null))?void 0:t.catch(t=>
1{this.log("Could not clear media keys: ".concat(t)),this.hls&&this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error("Could not clear media keys: ".concat(t))})}))||Promise.resolve())).catch(t=>{this.log("Could not close sessions and clear media keys: ".concat(t)),this.hls&&this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error("Could not close sessions and clear media keys: ".concat(t))})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={}}onManifestLoaded(t,e){let{sessionKeys:i}=e;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){let t=i.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log("Selecting key-system from session-keys ".concat(t.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){let{mediaKeysSession:e,licenseXhr:i,decryptdata:r}=t;if(e){var s;this.log('Remove licenses and keys and close session "'.concat(e.sessionId,'" keyId: ').concat(G((null==r?void 0:r.keyId)||[]))),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;let a=this.mediaKeySessions.indexOf(t);a>-1&&this.mediaKeySessions.splice(a,1);let{keyStatusTimeouts:n}=t;n&&Object.keys(n).forEach(t=>self.clearTimeout(n[t]));let{drmSystemOptions:d}=this.config;return(d&&("persistent-license"===d.sessionType||null!=(s=d.sessionTypes)&&s.some(t=>"persistent-license"===t))?new Promise((t,i)=>{self.setTimeout(()=>i(Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(i)}):Promise.resolve()).catch(t=>{this.log("Could not remove session: ".concat(t)),this.hls&&this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error("Could not remove session: ".concat(t))})}).then(()=>e.close()).catch(t=>{this.log("Could not close session: ".concat(t)),this.hls&&this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error("Could not close session: ".concat(t))})})}return Promise.resolve()}constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=s_.CDMCleanupPromise?[s_.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:e,initData:i}=t,r='"'.concat(t.type,'" event: init data type: "').concat(e,'"');if(this.debug(r),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=ej(this.config));let e=t.map(eW).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(s=>{let a;let n=eY(s);if("sinf"!==e||n!==eV.FAIRPLAY){this.log('Ignoring "'.concat(t.type,'" event with init data type: "').concat(e,'" for selected key-system ').concat(n));return}try{let t=Z(new Uint8Array(i)),e=eN(JSON.parse(t).sinf),r=td(e);if(!r)throw Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(r.subarray(8,24))}catch(t){this.warn("".concat(r," Failed to parse sinf: ").concat(t));return}let l=G(a),{keyIdToKeySessionPromise:o,mediaKeySessions:h}=this,d=o[l];for(let t=0;t<h.length;t++){let r=h[t],s=r.decryptdata;if(!s.keyId)continue;let n=G(s.keyId);if(ew(a,s.keyId)||-1!==s.uri.replace(/-/g,"").indexOf(l)){if(!(d=o[n]))continue;if(s.pssh)break;delete o[n],s.pssh=new Uint8Array(i),s.keyId=a,(d=o[l]=d.then(()=>this.generateRequestWithPreferredKeySession(r,e,i,"encrypted-event-key-match"))).catch(t=>this.handleError(t));break}}d||this.handleError(Error("Key ID ".concat(l," not encountered in playlist. Key-system sessions ").concat(h.length,".")))}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log('"'.concat(t.type,'" event'))},this.hls=t,this.config=t.config,this.registerListeners()}}function sP(t){if(!t)throw Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw Error("keyId is null");return G(t.keyId)}s_.CDMCleanupPromise=void 0;
1class sC extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=Error(e)),this.data=t,t.err=t.error}}function sO(t,e){let i="output-restricted"===t,r=i?o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:o.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new sC({type:l.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:e},i?"HDCP level output restricted":'key status changed to "'.concat(t,'"'))}class sw{setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(h.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(h.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){let i=this.hls.config;if(i.capLevelOnFPSDrop){let t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){let r=performance.now();if(e){if(this.lastTime){let t=r-this.lastTime,s=i-this.lastDroppedFrames,a=e-this.lastDecodedFrames,n=1e3*s/t,l=this.hls;if(l.trigger(h.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:i}),n>0&&s>l.config.fpsDroppedMonitoringThreshold*a){let t=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=t)&&(t-=1,l.trigger(h.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:l.currentLevel}),l.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){let t=this.media;if(t){if(this.isVideoPlaybackQualityAvailable){let e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}constructor(t){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=t,this.registerListeners()}}function sM(t,e){let i;try{i=new Event("addtrack")}catch(t){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function sx(t,e){let i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw Error("addCue is failed for: ".concat(e))}catch(i){F.debug("[texttrack-utils]: ".concat(i));try{let i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){F.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(t))}}"disabled"===i&&(t.mode=i)}function sF(t,e){let i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===i&&(t.mode=i)}function sN(t,e,i,r){let s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0){let s=function(t,e,i){let r=[],s=function(t,e){let i;if(e<=t[0].startTime)return 0;let r=t.length-1;if(e>t[r].endTime)return -1;let s=0,a=r;for(;s<=a;)if(e<t[i=Math.floor((a+s)/2)].startTime)a=i-1;else{if(!(e>t[i].startTime)||!(s<r))return i;s=i+1}return t[s].startTime-e<e-t[a].startTime?s:a}(t,e);if(s>-1)for(let a=s,n=t.length;a<n;a++){let s=t[a];if(s.startTime>=e&&s.endTime<=i)r.push(s);else if(s.startTime>i)break}return r}(t.cues,e,i);for(let e=0;e<s.length;e++)(!r||r(s[e]))&&t.removeCue(s[e])}"disabled"===s&&(t.mode=s)}function sU(t){let e=[];for(let i=0;i<t.length;i++){let r=t[i];("subtitles"===r.kind||"captions"===r.kind)&&r.label&&e.push(t[i])}return e}class sB extends rB{destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:t}=this;
vendor: 1,686 bytes, line 1
1t.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.MANIFEST_PARSED,this.onManifestParsed,this),t.on(h.LEVEL_LOADING,this.onLevelLoading,this),t.on(h.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(h.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:t}=this;t.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.MANIFEST_PARSED,this.onManifestParsed,this),t.off(h.LEVEL_LOADING,this.onLevelLoading,this),t.off(h.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(h.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(h.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){let i=this.media;if(!i)return;let r=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r||sU(i.textTracks).forEac
1h(t=>{sF(t)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){let{id:i,groupId:r,details:s}=e,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn("Subtitle track with id:".concat(i," and group:").concat(r," not found in active group ").concat(null==a?void 0:a.groupId));return}let n=a.details;a.details=e.details,this.log("Subtitle track ".concat(i,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(r," loaded [").concat(s.startSN,"-").concat(s.endSN,"]")),i===this.trackId&&this.playlistLoaded(i,e,n)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){let e=this.hls.levels[t];if(!e)return;let i=e.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>(null==r?void 0:r.indexOf(t))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let t=this.tracks.filter(t=>!i||-1!==i.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=t;let e=this.hls.config.subtitlePreference;if(!s&&e){this.selectDefaultTrack=!1;let i=tX(e,t);if(i>-1)s=t[i];else{let t=tX(e,this.tracks);s=this.tracks[t]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null)),this.log("Updating subtitle tracks, ".concat(t.length,' track(s) found in "').concat(null==i?void 0:i.join(","),'" group-id')),this.hls.trigger(h.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:t}),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}}findTrackId(t){let e=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<e.length;r++){let s=e[r];if((!i||s.default)&&(i||t)&&(!t||tQ(s,t)))return r}if(t){for(let i=0;i<e.length;i++){let r=e[i];if(rK(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){let r=e[i];if(rK(t.attrs,r.attrs,["LANGUAGE"]))return i}}return -1}findTrackForTextTrack(t){if(t){let e=this.tracksInGroup;for(let i=0;i<e.length;i++)if(rV(e[i],t))return i}return -1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==I.SUBTITLE_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1),null;let e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){let i=this.currentTrack;if(i&&tQ(t,i))return i;let r=tX(t,this.tracksInGroup);if(r>-1){let t=this.tracksInGroup[r];return this.setSubtitleTrack(r),t}if(i);else{let i=tX(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);let i=t.id,r=t.groupId,s=this.getUrlWithDirectives(t.url,e),a=t.details,n=null==a?void 0:a.age;this.log("Loading subtitle ".concat(i,' "').concat(t.name,'" lang:').concat(t.lang," group:").concat(r).concat((null==e?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:"").concat(n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""," ").concat(s)),this.hls.trigger(h.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null,track:t})}toggleTrackModes(){let t;let{media:e}=this;if(!e)return;let i=sU(e.textTracks),r=this.currentTrack;if(!r||(t=i.filter(t=>rV(r,t))[0])||this.warn('Unable to find subtitle TextTrack with name "'.concat(r.name,'" and language "').concat(r.lang,'"')),[].slice.call(i).forEach(e=>{"disabled"!==e.mode&&e!==t&&(e.mode="disabled")}),t){let e=this.subtitleDisplay?"showing":"hidden";t.mode!==e&&(t.mode=e)}}setSubtitleTrack(t){let e=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=e.length||!s(t)){this.warn("Invalid subtitle track id: ".concat(t));return}this.selectDefaultTrack=!1;let i=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(h.SUBTITLE_TRACK_SWITCH,{id:t});return}let a=!!r.details&&!r.details.live;if(t===this.trackId&&r===i&&a)return;this.log("Switching to subtitle-track ".concat(t)+(r?' "'.concat(r.name,'" lang:').concat(r.lang," group:").concat(r.groupId):""));let{id:n,groupId:l="",name:o,type:d,url:c}=r;this.hls.trigger(h.SUBTITLE_TRACK_SWITCH,{id:n,groupId:l,name:o,type:d,url:c});let u=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(u)}constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>
1{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null,e=sU(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}let i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}}function sG(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}let sK=((y={})[y.Point=0]="Point",y[y.Range=1]="Range",y);class sV{setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;let i=this.playoutLimit;return!(t<=0||isNaN(i))&&(0===i||((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i)}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let t=this.dateRange.startTime;if(this.snapOptions.out){let e=this.dateRange.tagAnchor;if(e)return sH(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;let t=this.dateRange.tagAnchor;if(t){let e=this.dateRange.startTime,i=sH(e,t);return e-i<.1}return!1}get resumptionOffset(){let t=this.resumeOffset,e=s(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){let t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let e=this.resumeAnchor;if(e)return sH(t,e)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&.025>Math.abs(this.resumeOffset-this.duration)))}set appendInPlace(t){if(this.appendInPlaceStarted){this.resetOnResume=!t;return}this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){let t;let e=this.playoutLimit;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?sK.Range:sK.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return'["'.concat(this.identifier,'" ').concat(this.cue.pre?"<pre>":this.cue.post?"<post>":"").concat(this.timelineStart.toFixed(2),"-").concat(this.resumeTime.toFixed(2),"]")}constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}}function sH(t,e){return t-e.start<e.duration/2&&!(.025>Math.abs(t-(e.start+e.duration)))?e.start:e.start+e.duration}function sY(t,e,i){let r=new self.URL(t,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",e),r}function sW(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function sj(t){let e=t.timelineStart,i=t.duration||0;return'["'.concat(t.identifier,'" ').concat(e.toFixed(2),"-").concat((e+i).toFixed(2),"]")}class sq{get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let t=this.hls;if(t){if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=sY(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;
1if(!t)return!1;let i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,s=eI.bufferInfo(t,r,0);return this.getAssetTime(s.end)>=i-.02}reachedPlayout(t){let e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){let t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let e=eI.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){let t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){let t=this.assetItem.duration;if(!t)return 0;let e=this.interstitial.playoutLimit;if(e){let i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){let t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){let e=this.timelineOffset;if(t!==e&&Math.abs(t-e)>1/9e4&&this.hls){if(this.hasDetails)throw Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}getAssetTime(t){return Math.min(Math.max(0,t-this.timelineOffset),this.duration)}removeMediaListeners(){let t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var t;null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){let t=this.hls;if(t&&this.hasDetails){t.stopLoad();let e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var r;null==(r=this.hls)||r.on(t,e)}once(t,e,i){var r;null==(r=this.hls)||r.once(t,e)}off(t,e,i){var r;null==(r=this.hls)||r.off(t,e)}toString(){var t;return"HlsAssetPlayer: ".concat(sj(this.assetItem)," ").concat(null==(t=this.hls)?void 0:t.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}constructor(t,e,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(h.PLAYOUT_LIMIT_REACHED,{})};let s=this.hls=new t(e);this.interstitial=i,this.assetItem=r;let a=()=>{this.hasDetails=!0};s.once(h.LEVEL_LOADED,a),s.once(h.AUDIO_TRACK_LOADED,a),s.once(h.SUBTITLE_TRACK_LOADED,a),s.on(h.MEDIA_ATTACHING,(t,e)=>{let{media:i}=e;this.removeMediaListeners(),this.mediaAttached=i,this.interstitial.playoutLimit&&(i.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(h.BUFFER_APPENDED,()=>{let t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,s.trigger(h.BUFFERED_TO_END,void 0))}))})}}class sX extends C{destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,r)=>t<=r.startOffset&&e>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.i
1dentifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i}findItemIndexAtTime(t,e){let i=this.items;if(i)for(let r=0;r<i.length;r++){let s=i[r];if(e&&"primary"!==e&&(s=s[e]),t===s.start||t>s.start&&t<s.end)return r}return -1}findJumpRestrictedIndex(t,e){let i=this.items;if(i)for(let r=t;r<=e&&i[r];r++){let t=i[r].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return r}return -1}findEventIndex(t){let e=this.items;if(e)for(let r=e.length;r--;){var i;if((null==(i=e[r].event)?void 0:i.identifier)===t)return r}return -1}findAssetIndex(t,e){let i=t.assetList,r=i.length;if(r>1)for(let t=0;t<r;t++){let s=i[t];if(!s.error){let i=s.timelineStart;if(e===i||e>i&&(e<i+(s.duration||0)||t===r-1))return t}}return 0}get assetIdAtEnd(){var t;let e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){let t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e){let i=t.main.details,{dateRanges:r}=i,s=this.events,a=this.parseDateRanges(r,{url:i.url},e),n=Object.keys(r),l=s?s.filter(t=>!n.includes(t.identifier)):[];a.length&&a.sort((t,e)=>{let i=t.cue.pre,r=t.cue.post,s=e.cue.pre,a=e.cue.post;if(i&&!s)return -1;if(s&&!i||r&&!a)return 1;if(a&&!r)return -1;if(!i&&!s&&!r&&!a){let i=t.startTime,r=e.startTime;if(i!==r)return i-r}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=a,l.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,l)}updateSchedule(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this.events||[];
1if(r.length||e.length||this.length<2){let s=this.items,a=this.parseSchedule(r,t);(i||e.length||(null==s?void 0:s.length)!==a.length||a.some((t,e)=>Math.abs(t.playout.start-s[e].playout.start)>.005||Math.abs(t.playout.end-s[e].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(e,s))}}parseDateRanges(t,e,i){let r=[],s=Object.keys(t);for(let a=0;a<s.length;a++){let n=s[a],l=t[n];if(l.isInterstitial){let t=this.eventMap[n];t?t.setDateRange(l):(t=new sV(l,e),this.eventMap[n]=t,!1===i&&(t.appendInPlace=i)),r.push(t)}}return r}parseSchedule(t,e){let i=[],r=e.main.details,s=r.live?1/0:r.edge,a=0;if((t=t.filter(t=>!t.error&&!(t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let r=0,l=0;if(t.forEach((e,n)=>{let o=e.cue.pre,h=e.cue.post,d=t[n-1]||null,c=e.appendInPlace,u=h?s:e.startOffset,f=e.duration,g=e.timelineOccupancy===sK.Range?f:0,m=e.resumptionOffset,p=(null==d?void 0:d.startTime)===u,E=u+e.cumulativeDuration,y=c?E+f:u+m;if(o||!h&&u<=0){let t=l;l+=g,e.timelineStart=E;let r=a;a+=f,i.push({event:e,start:E,end:y,playout:{start:r,end:a},integrated:{start:t,end:l}})}else{if(!(u<=s))return;if(!p){let s=u-r;if(s>.033){let o=r,h=l;l+=s;let d=a;a+=s;let c={previousEvent:t[n-1]||null,nextEvent:e,start:o,end:o+s,playout:{start:d,end:a},integrated:{start:h,end:l}};i.push(c)}else s>0&&d&&(d.cumulativeDuration+=s,i[i.length-1].end=u)}h&&(y=E),e.timelineStart=E;let o=l;l+=g;let c=a;a+=f,i.push({event:e,start:E,end:y,playout:{start:c,end:a},integrated:{start:o,end:l}})}let v=e.resumeTime;r=h||v>s?s:v}),r<s){var n;let t=r,e=l,o=s-r;l+=o;let h=a;a+=o,i.push({previousEvent:(null==(n=i[i.length-1])?void 0:n.event)||null,nextEvent:null,start:r,end:t+o,playout:{start:h,end:a},integrated:{start:e,end:l}})}this.setDurations(s,a,l)}else i.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return i}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,e){let i=e.main.details,r=i.live?1/0:i.edge,a=0,n=-1;t.forEach((l,o)=>{let h=l.cue.pre,d=l.cue.post,c=h?0:d?r:l.startTime;this.updateAssetDurations(l),n===c?l.cumulativeDuration=a:(a=0,n=c),!d&&l.snapOptions.in&&(l.resumeAnchor=t1(null,i.fragments,l.startOffset+l.resumptionOffset,0,0)||void 0),!l.appendInPlace||l.appendInPlaceStarted||this.primaryCanResumeInPlaceAt(l,e)||(l.appendInPlace=!1),!l.appendInPlace&&o+1<t.length&&t[o+1].startTime-t[o].resumeTime<.033&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn("Could not change append strategy for abutting event ".concat(l)));let u=s(l.resumeOffset)?l.resumeOffset:l.duration;a+=u})}primaryCanResumeInPlaceAt(t,e){let i=t.resumeTime,r=t.startTime+t.resumptionOffset;return Math.abs(i-r)>.025?(this.log('"'.concat(t.identifier,'" resumption ').concat(i," not aligned with estimated timeline end ").concat(r)),!1):!Object.keys(e).some(r=>{let s=e[r].details,a=s.edge;if(i>=a)return this.log('"'.concat(t.identifier,'" resumption ').concat(i," past ").concat(r," playlist end ").concat(a)),!1;let n=t1(null,s.fragments,i);if(!n)return this.log('"'.concat(t.identifier,'" resumption ').concat(i," does not align with any fragments in ").concat(r," playlist (").concat(s.fragStart,"-").concat(s.fragmentEnd,")")),!0;let l="audio"===r?.175:0;return!(Math.abs(n.start-i)<.025+l||Math.abs(n.end-i)<.025+l)&&(this.log('"'.concat(t.identifier,'" resumption ').concat(i," not aligned with ").concat(r," fragment bounds (").concat(n.start,"-").concat(n.end," sn: ").concat(n.sn," cc: ").concat(n.cc,")")),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;let e=t.timelineStart,i=0,r=!1,s=!1;for(let a=0;a<t.assetList.length;a++){let n=t.assetList[a],l=e+i;n.startOffset=i,n.timelineStart=l,r||(r=null===n.duration),s||(s=!!n.error),i+=n.error?0:n.duration||0}r&&!s?t.duration=Math.max(i,t.duration):t.duration=i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}}
1function sQ(t){return"[".concat(t.event?'"'+t.event.identifier+'"':"primary",": ").concat(t.start.toFixed(2),"-").concat(t.end.toFixed(2),"]")}class sz{destroy(){this.hls=null}loadAssetList(t,e){let i;let r=t.assetListUrl;try{i=sY(r,this.hls.sessionId,t.baseUrl)}catch(i){let e=this.assignAssetListError(t,o.ASSET_LIST_LOAD_ERROR,i,r);this.hls.trigger(h.ERROR,e);return}e&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+e);let s=this.hls.config,a=new s.loader(s),n={responseType:"json",url:i.href},l=s.interstitialAssetListLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return a.load(n,d,{onSuccess:(e,i,r,s)=>{let a=e.data;if(!Array.isArray(null==a?void 0:a.ASSETS)){let e=this.assignAssetListError(t,o.ASSET_LIST_PARSING_ERROR,Error("Invalid interstitial asset list"),r.url,i,s);this.hls.trigger(h.ERROR,e);return}t.assetListResponse=a,this.hls.trigger(h.ASSET_LIST_LOADED,{event:t,assetListResponse:a,networkDetails:s})},onError:(e,i,r,s)=>{let a=this.assignAssetListError(t,o.ASSET_LIST_LOAD_ERROR,Error("Error loading X-ASSET-LIST: HTTP status ".concat(e.code," ").concat(e.text," (").concat(i.url,")")),i.url,s,r);this.hls.trigger(h.ERROR,a)},onTimeout:(e,i,r)=>{let s=this.assignAssetListError(t,o.ASSET_LIST_LOAD_TIMEOUT,Error("Timeout loading X-ASSET-LIST (".concat(i.url,")")),i.url,e,r);this.hls.trigger(h.ERROR,s)}}),this.hls.trigger(h.ASSET_LIST_LOADING,{event:t}),a}assignAssetListError(t,e,i,r,s,a){return t.error=i,{type:l.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:r,error:i,networkDetails:a,stats:s}}constructor(t){this.hls=void 0,this.hls=t}}function s$(t){null==t||t.play().catch(()=>{})}function sZ(t,e){return"[".concat(t,"] Advancing timeline position to ").concat(e)}class sJ extends C{registerListeners(){let t=this.hls;t&&(t.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(h.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(h.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(h.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(h.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(h.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(h.BUFFER_APPENDED,this.onBufferAppended,this),t.on(h.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(h.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(h.MEDIA_ENDED,this.onMediaEnded,this),t.on(h.ERROR,this.onError,this),t.on(h.DESTROYING,this.onDestroying,this))}unregisterListeners(){let t=this.hls;t&&(t.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(h.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(h.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(h.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(h.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(h.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(h.BUFFER_CODECS,this.onBufferCodecs,this),t.off(h.BUFFER_APPENDED,this.onBufferAppended,this),t.off(h.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(h.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(h.MEDIA_ENDED,this.onMediaEnded,this),t.off(h.ERROR,this.onError,this),t.off(h.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){iL(t,"play",this.onPlay),iL(t,"pause",this.onPause),iL(t,"seeking",this.onSeeking),iL(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){let i=this.media=e.media;iA(i,"seeking",this.onSeeking),iA(i,"timeupdate",this.onTimeupdate),iA(i,"play",this.onPlay),iA(i,"pause",this.onPause)}onMediaAttached(t,e){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();let t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){let i=!!e.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let t=this.getBuffer
1ingPlayer();t&&(this.log("Removing schedule state for detachedData and ".concat(t)),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,r=(e,r,s,n,l)=>{if(e){let o=e[r].start,h=e.event;if(h){if("playout"===r||h.timelineOccupancy!==sK.Point){let t=i(s);(null==t?void 0:t.interstitial)===h&&(o+=t.assetItem.startOffset+t[l])}}else o+=("bufferedPos"===n?a():t[n])-e.start;return o}return 0},s=(e,i)=>{var r,s;if(0!==e&&"primary"!==i&&null!=(r=t.schedule)&&r.length){let r=t.schedule.findItemIndexAtTime(e),a=null==(s=t.schedule.items)?void 0:s[r];if(a)return e+(a[i].start-a.start)}return e},a=()=>{let e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var i,r;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(r=t.schedule)?void 0:r.durations[e])||0},l=(e,s)=>{var a,n;let l=t.effectivePlayingItem;if(null!=l&&null!=(a=l.event)&&a.restrictions.skip||!t.schedule)return;t.log("seek to ".concat(e,' "').concat(s,'"'));let o=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,s),d=null==(n=t.schedule.items)?void 0:n[h],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=o&&t.itemsMatch(o,d);if(o&&(f||g)){let a=i(t.playingAsset),n=(null==a?void 0:a.media)||t.primaryMedia;if(n){let i="primary"===s?n.currentTime:r(o,s,t.playingAsset,"timelinePos","currentTime"),l=e-i,h=(f?i:n.currentTime)+l;if(h>=0&&(!a||f||h<=a.duration)){n.currentTime=h;return}}}if(d){let i=e;if("primary"!==s){let t=e-d[s].start;i=d.start+t}let r=!t.isInterstitial(d);if((!t.isInterstitial(o)||o.event.appendInPlace)&&(r||d.event.appendInPlace)){let e=t.media||(f?null==c?void 0:c.media:null);e&&(e.currentTime=i)}else if(o){let a=t.findItemIndex(o);if(h>a){let e=t.schedule.findJumpRestrictedIndex(a+1,h);if(e>a){t.setSchedulePosition(e);return}}let n=0;if(r)t.timelinePos=i,t.checkBuffer();else{let t=d.event.assetList,i=e-(d[s]||d).start;for(let e=t.length;e--;){let r=t[e];if(r.duration&&i>=r.startOffset&&i<r.startOffset+r.duration){n=e;break}}}t.setSchedulePosition(h,n)}}},o=()=>{let i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;let r=e();return t.isInterstitial(r)?r:null},h={get bufferedEnd(){let i=e(),s=t.bufferingItem;if(s&&s===i){var d;return r(s,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-s.playout.start||(null==(d=t.bufferingAsset)?void 0:d.startOffset)||0}return 0},get currentTime(){let e=o(),i=t.effectivePlayingItem;if(i&&i===e)return r(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start;return 0},set currentTime(time){let e=o(),i=t.effectivePlayingItem;i&&i===e&&l(time+i.playout.start,"playout")},get duration(){let t=o();if(t)return t.playout.end-t.playout.start;return 0},get assetPlayers(){var c;let e=null==(c=o())?void 0:c.event.assetList;if(e)return e.map(e=>t.getAssetPlayer(e.identifier));return[]},get playingIndex(){var u;let e=null==(u=o())?void 0:u.event;if(e&&t.effectivePlayingAsset)return e.findAssetIndex(t.effectivePlayingAsset);return -1},get scheduleItem(){return o()}};return this.manager={get events(){var f;return(null==(f=t.schedule)||null==(f=f.events)?void 0:f.slice(0))||[]},get schedule(){var g;return(null==(g=t.schedule)||null==(g=g.items)?void 0:g.slice(0))||[]},get interstitialPlayer(){if(o())return h;return null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){let i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){let e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return a()},get currentTime(){let e=t.timelinePos;return e>0?e:0},set currentTime(time){l(time,"primary")},get duration(){return n("primary")},get seekableStart(){var m;return(null==(m=t.primaryDetails)?void 0:m.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(time){l(time,"integrated")},get duration(){return n("integrated")},get seekableStart(){var p;return s((null==(p=t.primaryDetails)?void 0:p.fragmentStart)||0,"integrated")}},skip:()=>{let e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){let r=t.findItemIndex(e);i.appendInPlace?l(e.playout.start+e.event.duration+.001,"playout"):t.advanceAfterAssetEnded(i,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;let e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!this.playbackStarted&&!!e&&!!i&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(r=this.primaryMedia);let a=null==(e=r)?void 0:e.currentTime;if(void 0!==a&&s(a))return a}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!!(null!=t&&t.event)}retreiveMediaSource(t,e){let i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){let i=t.interstitial.appendInPlace,r=t.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&r){this.detachedData={media:r};return}let i=t.transferMedia();this.log("transfer MediaSource from ".concat(t," ").concat(tY(i))),this.detachedData=i}else e&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(t,e){var i,r;let s;if(t.media===e)return;let a=null,n=this.hls,l=t!==n,o=l&&t.interstitial.appendInPlace,h=null==(i=this.detachedData)?void 0:i.mediaSource;if(n.media)o&&(a=n.transferMedia(),this.detachedData=a),s="Primary";
1else if(h){let t=this.getBufferingPlayer();t?(a=t.transferMedia(),s="".concat(t)):s="detached MediaSource"}else s="detached media";if(!a){if(h)a=this.detachedData,this.log("using detachedData: MediaSource ".concat(tY(a)));else if(!this.detachedData||n.media===e){let t=this.playerQueue;t.length>1&&t.forEach(t=>{if(l&&t.interstitial.appendInPlace!==o){let e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn("Could not change append strategy for queued assets ".concat(e))}}),this.hls.detachMedia(),this.detachedData={media:e}}}let d=a&&"mediaSource"in a&&(null==(r=a.mediaSource)?void 0:r.readyState)!=="closed",c=d&&a?a:e;this.log("".concat(d?"transfering MediaSource":"attaching media"," to ").concat(l?t:"Primary"," from ").concat(s," (media.currentTime: ").concat(e.currentTime,")"));let u=this.schedule;if(c===a&&u){let e=l&&t.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!l||e,cueRemoval:!l}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let t=this.schedule,e=null==t?void 0:t.events;if(!e||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);let i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){let i=this.hls.startPosition;if(this.log(sZ("checkStart",i)),this.timelinePos=i,e.length&&e[0].cue.pre){let i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){let e=this.timelinePos=i>0?i:0,r=t.findItemIndexAtTime(e);this.setSchedulePosition(r)}}else if(r&&!this.playingItem){let e=t.findItemIndex(r);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){let i=t.event,r=i.findAssetIndex(e),s=sW(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var a;let e=null==(a=this.schedule.items)?void 0:a[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,s)}advanceAfterAssetEnded(t,e,i){let r=sW(t,i);if(t.isAssetPastPlayoutLimit(r)){if(this.schedule){let i=this.schedule.items;if(i){let r=e+1;if(r>=i.length){this.setSchedulePosition(-1);return}let s=t.resumeTime;this.timelinePos<s&&(this.log(sZ("advanceAfterAssetEnded",s)),this.timelinePos=s,t.appendInPlace&&this.advanceInPlace(s),this.checkBuffer(this.bufferedPos<s)),this.setSchedulePosition(r)}}}else{if(t.appendInPlace){let e=t.assetList[r];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,r)}}setScheduleToAssetAtTime(t,e){let i=this.schedule;if(!i)return;let r=e.parentIdentifier,s=i.getEvent(r);if(s){let e=i.findEventIndex(r),a=i.findAssetIndex(s,t);this.advanceAfterAssetEnded(s,e,a-1)}}setSchedulePosition(t,e){var i,r,s;let a=null==(i=this.schedule)?void 0:i.items;if(!a||this.playbackDisabled)return;let n=t>=0?a[t]:null;this.log("setSchedulePosition ".concat(t,", ").concat(e," (").concat(n?sQ(n):n,") pos: ").concat(this.timelinePos));let l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){let i=l.event,d=this.playingAsset,c=null==d?void 0:d.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(l,n)||void 0!==e&&c!==i.assetList[e].identifier)){let e=i.findAssetIndex(d);if(this.log("INTERSTITIAL_ASSET_ENDED ".concat(e+1,"/").concat(i.assetList.length," ").concat(sj(d))),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(h.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:e,event:i,schedule:a.slice(0),scheduleIndex:t,player:u}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e);return}this.retreiveMediaSource(c,n),u.media&&!(null!=(r=this.detachedData)&&r.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(l,n)&&(this.endedItem=l,this.playingItem=null,this.log("INTERSTITIAL_ENDED ".concat(i," ").concat(sQ(l))),i.hasPlayed=!0,this.hls.trigger(h.INTERSTITIAL_ENDED,{event:i,schedule:a.slice(0),scheduleIndex:t}),i.cue.once)){this.updateSchedule();let t=null==(s=this.schedule)?void 0:s.items;if(n&&t){let i=this.findItemIndex(n);this.advanceSchedule(i,t,e,l,o)}return}}this.advanceSchedule(t,a,e,l,o)}advanceSchedule(t,e,i,r,s){let a=this.schedule;if(!a)return;let n=e[t]||null,l=this.primaryMedia,o=this.playerQueue;
1if(o.length&&o.forEach(e=>{let i=e.interstitial,r=a.findEventIndex(i.identifier);(r<t||r>t+1)&&this.clearInterstitial(i,n)}),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);let s=n.event;if(void 0===i){i=a.findAssetIndex(s,this.timelinePos);let e=sW(s,i-1);if(s.isAssetPastPlayoutLimit(e)||s.appendInPlace&&this.timelinePos===n.end){this.advanceAfterAssetEnded(s,t,i);return}i=e}let o=this.waitingItem;this.assetsBuffered(n,l)||this.setBufferingItem(n);let d=this.preloadAssets(s,i);if(this.eventItemsMatch(n,o||r)||(this.waitingItem=n,this.log("INTERSTITIAL_STARTED ".concat(sQ(n)," ").concat(s.appendInPlace?"append in place":"")),this.hls.trigger(h.INTERSTITIAL_STARTED,{event:s,schedule:e.slice(0),scheduleIndex:t})),!s.assetListLoaded){this.log("Waiting for ASSET-LIST to complete loading ".concat(s));return}if(s.assetListLoader&&(s.assetListLoader.destroy(),s.assetListLoader=void 0),!l){this.log("Waiting for attachMedia to start Interstitial ".concat(s));return}this.waitingItem=this.endedItem=null,this.playingItem=n;let c=s.assetList[i];if(!c){this.advanceAfterAssetEnded(s,t,i||0);return}if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){let t=s.assetList.length;this.warn("asset ".concat(i+1,"/").concat(t," player destroyed ").concat(s)),(d=this.createAssetPlayer(s,c,i)).loadSource()}if(!this.eventItemsMatch(n,this.bufferingItem)&&s.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,i,e,t,l),this.shouldPlay&&s$(d.media)}else n?(this.resumePrimary(n,t,r),this.shouldPlay&&s$(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!!(null!=(t=this.primaryDetails)&&t.live)}resumePrimary(t,e,i){var r,s;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log("resuming ".concat(sQ(t))),!(null!=(r=this.detachedData)&&r.mediaSource)){let i=this.timelinePos;(i<t.start||i>=t.end)&&(i=this.getPrimaryResumption(t,e),this.log(sZ("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,t)}if(!i)return;let a=null==(s=this.schedule)?void 0:s.items;a&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(sQ(t))),this.hls.trigger(h.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){let i=t.start;if(this.primaryLive){let t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(i<t.fragmentStart||i>t.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(t){let e=this.getAssetPlayer(t.identifier);return null!=e&&e.hls?e.hls.bufferedToEnd:eI.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(sZ("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){var i;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-t)>.5?r.startLoad(t,e):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(h.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(h.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;let i=this.hls.levels[e.level];if(!i.details)return;let r=P(P({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,e){let i=this.hls.audioTracks[e.id],r=this.mediaSelection;if(!r){this.altSelection=P(P({},this.altSelection),{},{audio:i});return}let s=P(P({},r),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(t,e){let i=this.hls.subtitleTracks[e.id],r=this.mediaSelection;if(!r){this.altSelection=P(P({},this.altSelection),{},{subtitles:i});return}let s=P(P({},r),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(t,e){let i=tq(e);this.playerQueue.forEach(t=>{let{hls:r}=t;return r&&(r.setAudioOption(e)||r.setAudioOption(i))})}onSubtitleTrackSwitch(t,e){let i=tq(e);this.playerQueue.forEach(t=>{let{hls:r}=t;return r&&(r.setSubtitleOption(e)||-1!==e.id&&r.setSubtitleOption(i))})}onBufferCodecs(t,e){let i=e.tracks;
1i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;let e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){let r=e[t];if(r.cue.post){var i;let t=this.schedule.findEventIndex(r.identifier),e=null==(i=this.schedule.items)?void 0:i[t];this.isInterstitial(e)&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){let e=this.playingItem;if(!this.playingLastItem&&e){let t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;let r=null==(i=this.schedule)?void 0:i.items;return t&&r&&r[this.findItemIndex(t,e)]||null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)});let i=t.end+.25,r=eI.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log("trim buffered interstitial ".concat(sQ(t)," (was ").concat(sQ(e),")")),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(){var t;let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))}checkBuffer(t){var e;let i=null==(e=this.schedule)?void 0:e.items;if(!i)return;let r=eI.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=r.len<1),this.updateBufferedPos(r.end,i,t)}updateBufferedPos(t,e,i){let r=this.schedule,s=this.bufferingItem;if(this.bufferedPos>t||!r)return;if(1===e.length&&this.itemsMatch(e[0],s)){this.bufferedPos=t;return}let a=this.playingItem,n=this.findItemIndex(a),l=r.findItemIndexAtTime(t);if(this.bufferedPos<t){var o;let i=this.findItemIndex(s),r=Math.min(i+1,e.length-1),a=e[r];if((-1===l&&s&&t>=s.end||null!=(o=a.event)&&o.appendInPlace&&t+.01>=a.start)&&(l=r),this.isInterstitial(s)){let t=s.event;if(r-n>1&&!1===t.appendInPlace||0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,l>i&&l>n)this.bufferedToItem(a);else{let e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&a.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else i&&a&&!this.itemsMatch(a,s)&&(l===n?this.bufferedToItem(a):l===n+1&&this.bufferedToItem(e[l]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{let i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){let e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){let{items:r,events:s}=i;if(!r||!s)return e;let a=this.isInterstitial(t),n=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));let l=n?n.remaining:e?e.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(sQ(t))+(e?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled){if(a){let e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,i)=>{let r=this.getAssetPlayer(t.identifier);r&&(i===e&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering())}this.hls.trigger(h.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;let e=this.detachedData;e&&e.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t)}}}preloadPrimary(t){let e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)}bufferedToEvent(t,e){let i=t.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){let t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){let e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){let i=t.assetUrl,r=t.assetList.length,s=0===r&&!t.assetListLoader,a=t.cue.once;if(s){let s;let a=t.timelineStart;if(t.appendInPlace){var n;let e=this.playingItem;this.isInterstitial(e)||(null==e||null==(n=e.nextEvent)?void 0:n.identifier)!==t.identifier||this.flushFrontBuffer(a+.25)}let l=0;if(!this.playingItem&&this.primaryLive&&-1===(l=this.hls.startPosition)&&(l=this.hls.liveSyncPosition||0),l&&!(t.cue.pre||t.cue.post)){let t=l-a;t>0&&(s=Math.round(1e3*t)/1e3)}if(this.log("Load interstitial asset ".concat(e+1,"/").concat(i?1:r," ").concat(t).concat(s?" live-start: ".concat(l," start-offset: ").concat(s):"")),i)return this.createAsset(t,0,0,a,t.duration,i);let o=this.assetListLoader.loadAssetList(t,s);o&&(t.assetListLoader=o)}else if(!a&&r){for(let i=e;i<r;i++){let e=t.assetList[i],r=this.getAssetPlayerQueueIndex(e.identifier);(-1===r||this.playerQueue[r].destroyed)&&!e.error&&this.createAssetPlayer(t,e,i)}let i=t.assetList[e];if(i){let t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){let e=this.requiredTracks;e&&(this.log("Removing front buffer starting at ".concat(t)),Object.keys(e).forEach(e
1=>{this.hls.trigger(h.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})}))}getAssetPlayerQueueIndex(t){let e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return -1}getAssetPlayer(t){let e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){let{playerQueue:t,primaryMedia:e}=this;if(e){for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i]}return null}createAsset(t,e,i,r,s,a){let n={parentIdentifier:t.identifier,identifier:"".concat(t.identifier,"-").concat(e+1,"-").concat(sG(a)),duration:s,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(t,n,e)}createAssetPlayer(t,e,i){let r=this.hls,s=r.userConfig,a=s.videoPreference,n=r.loadLevelObj||r.levels[r.currentLevel];(a||n)&&(a=k({},a),n.videoCodec&&(a.videoCodec=n.videoCodec),n.videoRange&&(a.allowedVideoRanges=[n.videoRange]));let d=r.audioTracks[r.audioTrack],c=r.subtitleTracks[r.subtitleTrack],u=0;if(this.primaryLive||t.appendInPlace){let t=this.timelinePos-e.timelineStart;if(t>1){let i=e.duration;i&&t<i&&(u=t)}}let f=e.identifier,g=P(P({},s),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:f,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:d||s.audioPreference,subtitlePreference:c||s.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(g.timelineOffset=e.timelineStart));let m=g.cmcd;null!=m&&m.sessionId&&m.contentId&&(g.cmcd=k({},m,{contentId:sG(e.uri)})),this.getAssetPlayer(f)&&this.warn("Duplicate date range identifier ".concat(t," and asset ").concat(f));let p=new sq(this.HlsPlayerClass,g,t,e);this.playerQueue.push(p),t.assetList[i]=e;let E=!0,y=r=>{if(r.live){var s;let e=Error("Interstitials MUST be VOD assets ".concat(t)),r={fatal:!0,type:l.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},a=(null==(s=this.schedule)?void 0:s.findEventIndex(t.identifier))||-1;this.handleAssetItemError(r,t,a,i,e.message);return}let a=r.edge-r.fragmentStart,n=e.duration;(E||null===n||a>n)&&(E=!1,this.log('Interstitial asset "'.concat(f,'" duration change ').concat(n," > ").concat(a)),e.duration=a,this.updateSchedule())};p.on(h.LEVEL_UPDATED,(t,e)=>{let{details:i}=e;return y(i)}),p.on(h.LEVEL_PTS_UPDATED,(t,e)=>{let{details:i}=e;return y(i)}),p.on(h.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(t,e)=>{let i=this.getAssetPlayer(f);if(i&&e.tracks){i.off(h.BUFFER_CODECS,v),i.tracks=e.tracks;let t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};p.on(h.BUFFER_CODECS,v),p.on(h.BUFFERED_TO_END,()=>{var i;let r=this.getAssetPlayer(f);if(this.log("buffered to end of asset ".concat(r)),!r||!this.schedule)return;let s=this.schedule.findEventIndex(t.identifier),a=null==(i=this.schedule.items)?void 0:i[s];this.isInterstitial(a)&&this.advanceAssetBuffering(a,e)});let T=e=>()=>{if(!this.getAssetPlayer(f)||!this.schedule)return;this.shouldPlay=!0;let i=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return p.once(h.MEDIA_ENDED,T(i)),p.once(h.PLAYOUT_LIMIT_REACHED,T(1/0)),p.on(h.ERROR,(e,r)=>{if(!this.schedule)return;let s=this.getAssetPlayer(f);if(r.details===o.BUFFER_STALLED_ERROR){if(null!=s&&s.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(r,t,this.schedule.findEventIndex(t.identifier),i,"Asset player error ".concat(r.error," ").concat(t))}),p.on(h.DESTROYING,()=>{if(!this.getAssetPlayer(f)||!this.schedule)return;let e=Error("Asset player destroyed unexpectedly ".concat(f)),r={fatal:!0,type:l.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(r,t,this.schedule.findEventIndex(t.identifier),i,e.message)}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(sj(e))),this.hls.trigger(h.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:p}),p}clearInterstitial(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)}),t.reset()}resetAssetPlayer(t){let e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log('reset asset player "'.concat(t,'" after error'));let i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){let i=this.getAssetPlayerQueueIndex(t);if(-1!==i){let t=this.playerQueue[i];this.log("clear ".concat(t," toSegment: ").concat(e?sQ(e):e)),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}
1startAssetPlayer(t,e,i,r,s){let{interstitial:a,assetItem:n,assetId:l}=t,o=a.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=n,d&&d.identifier===l||(d&&(this.clearAssetPlayer(d.identifier,i[r]),delete d.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(e+1,"/").concat(o," ").concat(sj(n))),this.hls.trigger(h.INTERSTITIAL_ASSET_STARTED,{asset:n,assetListIndex:e,event:a,schedule:i.slice(0),scheduleIndex:r,player:t})),this.bufferAssetPlayer(t,s)}bufferAssetPlayer(t,e){var i,r;if(!this.schedule)return;let{interstitial:s,assetItem:a}=t,n=this.schedule.findEventIndex(s.identifier),h=null==(i=this.schedule.items)?void 0:i[n];if(!h)return;t.loadSource(),this.setBufferingItem(h),this.bufferingAsset=a;let d=this.getBufferingPlayer();if(d===t)return;let c=s.appendInPlace;if(c&&(null==d?void 0:d.interstitial.appendInPlace)===!1)return;let u=(null==d?void 0:d.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(c&&a!==this.playingAsset){if(!t.tracks){this.log("Waiting for track info before buffering ".concat(t));return}if(u&&!U(u,t.tracks)){let e=Error("Asset ".concat(sj(a)," SourceBuffer tracks ('").concat(Object.keys(t.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(u),"')")),i={fatal:!0,type:l.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},r=s.findAssetIndex(a);this.handleAssetItemError(i,s,n,r,e.message);return}}this.transferMediaTo(t,e)}handleInPlaceStall(t){let e=this.schedule,i=this.primaryMedia;if(!e||!i)return;let r=i.currentTime,s=e.findAssetIndex(t,r),a=t.assetList[s];if(a){let n=this.getAssetPlayer(a.identifier);if(n){let l=n.currentTime||r-a.timelineStart,o=n.duration-l;if(this.warn("Stalled at ".concat(l," of ").concat(l+o," in ").concat(n," ").concat(t," (media.currentTime: ").concat(r,")")),l&&(o/i.playbackRate<.5||n.bufferedInPlaceToEnd(i))&&n.hls){let i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,s)}}}}advanceInPlace(t){let e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,i,r,s){if(t.details===o.BUFFER_STALLED_ERROR)return;let a=e.assetList[r]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR ".concat(a?sj(a):a," ").concat(t.error)),!this.schedule)return;let n=(null==a?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(n),d=this.playerQueue[l]||null,c=this.schedule.items,u=k({},t,{fatal:!1,errorAction:ea(!0),asset:a,assetListIndex:r,event:e,schedule:c,scheduleIndex:i,player:d});if(this.hls.trigger(h.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;let f=this.playingAsset,g=this.bufferingAsset,m=Error(s);if(a&&(this.clearAssetPlayer(n,null),a.error=m),e.assetList.some(t=>!t.error))for(let t=r;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=m;this.updateSchedule(!0),e.error?this.primaryFallback(e):f&&f.identifier===n?this.advanceAfterAssetEnded(e,i,r):g&&g.identifier===n&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(t){let e=t.timelineStart,i=this.effectivePlayingItem;if(i){this.log('Fallback to primary from event "'.concat(t.identifier,'" start: ').concat(e," pos: ").concat(this.timelinePos," playing: ").concat(sQ(i)," error: ").concat(t.error));let r=this.timelinePos;-1===r&&(r=this.hls.startPosition);let s=this.updateItem(i,r);if(this.itemsMatch(i,s)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e)),!this.schedule)return;let a=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(a)}else this.checkStart()}onAssetListLoaded(t,e){var i,r,s;let a=e.event,n=a.identifier,l=e.assetListResponse.ASSETS;if(!(null!=(i=this.schedule)&&i.hasEvent(n)))return;let o=a.timelineStart,h=a.duration,d=0;l.forEach((t,e)=>{let i=parseFloat(t.DURATION);this.createAsset(a,e,d,o+d,i,t.URI),d+=i}),a.duration=d,this.log("Loaded asset-list with duration: ".concat(d," (was: ").concat(h,") ").concat(a));let c=this.waitingItem,u=(null==c?void 0:c.event.identifier)===n;this.updateSchedule();let f=null==(r=this.bufferingItem)?void 0:r.event;if(u){let t=this.schedule.findEventIndex(n),e=null==(s=this.schedule.items)?void 0:s[t];if(e){if(!this.playingItem&&this.timelinePos>e.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==t){a.error=Error("Interstitial no longer within playback range ".concat(this.timelinePos," ").concat(a)),this.updateSchedule(!0),this.primaryFallback(a);return}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==f?void 0:f.identifier)===n){let t=a.assetList[0];if(t){let e=this.getAssetPlayer(t.identifier);if(f.appendInPlace){let t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case o.ASSET_LIST_PARSING_ERROR:case o.ASSET_LIST_LOAD_ERROR:case o.ASSET_LIST_LOAD_TIMEOUT:{let t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case o.BUFFER_STALLED_ERROR:{let t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace){this.handleInPlaceStall(t.event);return}this.log("Primary player stall @".concat(this.timelinePos," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1}
1,this.onSeeking=()=>{var t,e;let i=this.currentTime;if(void 0===i||this.playbackDisabled||!this.schedule)return;let r=i-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let s=r<=-.01;this.timelinePos=i,this.bufferedPos=i;let a=this.playingItem;if(!a){this.checkBuffer();return}if(s&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(!0),this.checkBuffer(),s&&i<a.start||i>=a.end){let e=this.findItemIndex(a),r=this.schedule.findItemIndexAtTime(i);if(-1===r&&(r=e+(s?-1:1),this.log("seeked ".concat(s?"back ":"","to position not covered by schedule ").concat(i," (resolving from ").concat(e," to ").concat(r,")"))),!this.isInterstitial(a)&&null!=(t=this.media)&&t.paused&&(this.shouldPlay=!1),!s&&r>e){let t=this.schedule.findJumpRestrictedIndex(e+1,r);if(t>e){this.setSchedulePosition(t);return}}this.setSchedulePosition(r);return}let n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(a)){let t=a.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,t))}return}let l=n.timelineStart,o=n.duration||0;(s&&i<l||i>=l+o)&&(null!=(e=a.event)&&e.appendInPlace&&(this.clearInterstitial(a.event,a),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,n))},this.onTimeupdate=()=>{let t=this.currentTime;if(void 0===t||this.playbackDisabled||!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();let e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;let t=this.findItemIndex(e);this.setSchedulePosition(t+1)}let i=this.playingAsset;i&&t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{let i=this.schedule;if(!i)return;let r=this.playingItem,s=i.events||[],a=i.items||[],n=i.durations,l=t.map(t=>t.identifier),o=!!(s.length||l.length);(o||e)&&this.log("INTERSTITIALS_UPDATED (".concat(s.length,"): ").concat(s,"\nSchedule: ").concat(a.map(t=>sQ(t))," pos: ").concat(this.timelinePos)),l.length&&this.log("Removed events ".concat(l));let d=null,c=null;r&&(d=this.updateItem(r,this.timelinePos),this.itemsMatch(r,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let u=this.bufferingItem;if(u&&(c=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,c)?this.bufferingItem=c:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){let e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(r){Math.abs(i)>.025&&this.warn("".concat(r,' ("').concat(t.assetId,'" ').concat(t.timelineOffset,"->").concat(e,")"))}}}),o||e){if(this.hls.trigger(h.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:a.slice(0),durations:n,removedIds:l}),this.isInterstitial(r)&&l.includes(r.event.identifier)){this.warn('Interstitial "'.concat(r.event.identifier,'" removed while playing')),this.primaryFallback(r.event);return}r&&this.trimInPlace(d,r),u&&c!==d&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new sz(t),this.schedule=new sX(this.onScheduleUpdate,t.logger),this.registerListeners()}}class s0 extends ib{onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:t}=this;t.on(h.LEVEL_LOADED,this.onLevelLoaded,this),t.on(h.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(h.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(h.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(h.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:t}=this;t.off(h.LEVEL_LOADED,this.onLevelLoaded,this),t.off(h.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(h.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(h.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(h.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this)}
1startLoad(t,e){this.stopLoad(),this.state=iR.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){let i;let{frag:r,success:s}=e;if(this.fragContextChanged(r)||(q(r)&&(this.fragPrevious=r),this.state=iR.IDLE),!s)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let n=r.start;for(let t=0;t<a.length;t++)if(n>=a[t].start&&n<=a[t].end){i=a[t];break}let l=r.start+r.duration;i?i.end=l:(i={start:n,end:l},a.push(i)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(t,e){let{startOffset:i,endOffset:r}=e;if(0===i&&r!==Number.POSITIVE_INFINITY){let t=r-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{for(let i=0;i<e.length;){if(e[i].end<=t){e.shift();continue}if(e[i].start<t)e[i].start=t;else break;i++}}),this.fragmentTracker.removeFragmentsInRange(i,t,R.SUBTITLE)}}onError(t,e){let i=e.frag;(null==i?void 0:i.type)===R.SUBTITLE&&(e.details===o.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==iR.STOPPED&&(this.state=iR.IDLE))}onSubtitleTracksUpdated(t,e){let{subtitleTracks:i}=e;if(this.levels&&rG(this.levels,i)){this.levels=i.map(t=>new tK(t));return}this.tracksBuffered=[],this.levels=i.map(t=>{let e=new tK(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,R.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,!(null!=(i=this.levels)&&i.length)||-1===this.currentTrackId){this.clearInterval();return}let r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==iR.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i,r;let{currentTrackId:s,levels:a}=this,{details:n,id:l}=e;if(!a){this.warn("Subtitle tracks were reset while loading level ".concat(l));return}let o=a[l];if(l>=a.length||!o)return;this.log("Subtitle track ".concat(l," loaded [").concat(n.startSN,",").concat(n.endSN,"]").concat(n.lastPartSn?"[part-".concat(n.lastPartSn,"-").concat(n.lastPartIndex,"]"):"",",duration:").concat(n.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;let t=this.mainDetails;if(!t){this.startFragRequested=!1;return}let e=t.fragments[0];o.details?0===(d=this.alignPlaylists(n,o.details,null==(r=this.levelLastLoaded)?void 0:r.details))&&e&&ih(n,d=e.start):n.hasProgramDateTime&&t.hasProgramDateTime?(iS(n,t),d=n.fragmentStart):e&&ih(n,d=e.start),t&&!this.startFragRequested&&this.setStartPosition(t,d)}o.details=n,this.levelLastLoaded=o,l===s&&(this.hls.trigger(h.SUBTITLE_TRACK_UPDATED,{details:n,id:l,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===iR.IDLE&&!t1(null,n.fragments,this.media.currentTime,0)&&(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0))}_handleFragmentLoadComplete(t){let{frag:e,payload:i}=t,r=e.decryptdata,s=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&ex(r.method)){let t=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,eF(r.method)).catch(t=>{throw s.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(i=>{let r=performance.now();s.trigger(h.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:r}})}).catch(t=>{this.warn("".concat(t.name,": ").concat(t.message)),this.state=iR.IDLE})}}doTick(){if(!this.media){this.state=iR.IDLE;return}if(this.state===iR.IDLE){let{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details||this.waitForLive(i))return;let{config:r}=this,s=this.getLoadPosition(),{end:a,len:n}=eI.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),l=i.details;if(n>this.hls.maxBufferLength+l.levelTargetDuration)return;let o=l.fragments,h=o.length,d=l.edge,c=null,u=this.fragPrevious;if(a<d){let t=r.maxFragLookUpTolerance;(c=t1(u,o,Math.max(o[0].start,a),a>d-t?0:t))||!u||!(u.start<o[0].start)||(c=o[0])}else c=o[h-1];if(!(c=this.filterReplacedPrimary(c,i.details)))return;let f=o[c.sn-l.startSN-1];if(f&&f.cc===c.cc&&this.fragmentTracker.getState(f)===en.NOT_LOADED&&(c=f),this.fragmentTracker.getState(c)===e
1n.NOT_LOADED){let t=this.mapToInitFragWhenRequired(c);t&&this.loadFragment(t,i,a)}}}loadFragment(t,e,i){q(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new s1(this.tracksBuffered[this.currentTrackId]||[])}constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",R.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}}class s1{constructor(t){this.buffered=void 0;let e=(e,i,r)=>{if((i>>>=0)>r-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(i,") is greater than the maximum bound (").concat(r,")"));return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}let s2={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},s3=t=>String.fromCharCode(s2[t]||t),s4={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},s5={17:2,18:4,21:6,22:8,23:10,19:13,20:15},s8={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},s6={25:2,26:4,29:6,30:8,31:10,27:13,28:15},s9=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class s7{log(t,e){if(this.verboseLevel>=t){let i="function"==typeof e?e():e;F.log("".concat(this.time," [").concat(t,"] ").concat(i))}}constructor(){this.time=null,this.verboseLevel=0}}let at=function(t){let e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class ae{reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){let e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){let r=e[i];t.hasOwnProperty(r)&&(this[r]=t[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}}class ai{reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}constructor(){this.uchar=" ",this.penState=new ae}}class ar{equals(t){for(let e=0;e<100;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<100;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<100;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>100&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)}moveCursor(t){let e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();let e=s3(t);if(this.pos>=100){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1)}clearFromPos(t){let e;for(e=t;e<100;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let t=[],e=!0;for(let i=0;i<100;i++){let r=this.chars[i].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}constructor(t){this.chars=[],this.pos=0,this.currPenState=new ae,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<100;t++)this.chars.push(new ai);this.logger=t}}class as{reset(){for(let t=0;t<15;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<15;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<15;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<15;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+tY(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<15;t++)this.rows[t].clear();let t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){let r=i.rows[t].cueStartTime,s=this.logger.time;if(null!==r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[e-this.nrRollUpRows+r+1].copy(i.rows[t+r])}}this.currRow=e;let i=this.rows[this.currRow];if(null!==t.indent){let e=Math.max(t.indent-1,0);i.setCursor(t.indent),t.color=i.chars[e].penState.foreground}let r={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+tY(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;let e=[],i="",r=-1;for(let i=0;i<15;i++){let s=this.rows[i].getTextString();s&&(r=i+1,t?e.push("Row "+r+": '"+s+"'"):e.push(s.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<15;e++)this.rows.push(new ar(t));this.logger=t}}class aa{reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);let e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),("MODE_PAINT-ON"===this.mode||"MODE_ROLL-UP"===this.mode)&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}
1ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){let t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){let e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{let i=Math.floor(t/2)-16;e.foreground=["white","green","blue","cyan","red","yellow","magenta"][i]}this.logger.log(2,"MIDROW: "+tY(e)),this.writeScreen.setPen(e)}outputDataUpdate(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&!this.displayedMemory.isEmpty()&&(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t)}constructor(t,e,i){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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new as(i),this.nonDisplayedMemory=new as(i),this.lastOutputScreen=new as(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}}class an{getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){var i;let r=127&e[t],s=127&e[t+1],a=!1,n=null;if(0===r&&0===s)continue;this.logger.log(3,()=>"["+at([e[t],e[t+1]])+"] -> ("+at([r,s])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(l.a===r&&l.b===s){l.a=null,l.b=null,this.logger.log(3,()=>"Repeated command ("+at([r,s])+") is dropped");continue}(i=this.cmdHistory).a=r,i.b=s,(a=this.parseCmd(r,s))||(a=this.parseMidrow(r,s)),a||(a=this.parsePAC(r,s)),a||(a=this.parseBackgroundAttributes(r,s))}else l.a=null,l.b=null;if(!a&&(n=this.parseChars(r,s))){let t=this.currentChannel;t&&t>0?this.channels[t].insertChars(n):this.logger.log(2,"No channel found yet. TEXT-MODE?")}a||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+at([r,s])+" orig: "+at([e[t],e[t+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=33&&e<=35))return!1;let i=20===t||21===t||23===t?1:2,r=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?r.ccRCL():33===e?r.ccBS():34===e?r.ccAOF():35===e?r.ccAON():36===e?r.ccDER():37===e?r.ccRU(2):38===e?r.ccRU(3):39===e?r.ccRU(4):40===e?r.ccFON():41===e?r.ccRDC():42===e?r.ccTR():43===e?r.ccRTD():44===e?r.ccEDM():45===e?r.ccCR():46===e?r.ccENM():47===e&&r.ccEOC():r.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if((i=17===t?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[i];return!!r&&(r.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+at([t,e])+")"),!0)}return!1}parsePAC(t,e){let i;let r=(t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127,s=(16===t||24===t)&&e>=64&&e<=95;if(!(r||s))return!1;let a=t<=23?1:2;i=e>=64&&e<=95?1===a?s4[t]:s8[t]:1===a?s5[t]:s6[t];let n=this.channels[a];return!!n&&(n.setPAC(this.interpretPAC(i,e)),this.currentChannel=a,!0)}interpretPAC(t,e){let i;let r={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,r.underline=(1&i)==1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(t,e){let i;let r=null,s=null;if(t>=25?(i=2,s=t-8):(i=1,s=t),s>=17&&s<=19){let t;t=17===s?e+80:18===s?e+112:e+144,this.logger.log(2,()=>"Special char '"+s3(t)+"' in channel "+i),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);return r&&this.logger.log(3,()=>"Char codes =  "+at(r).join(",")),r}
1parseBackgroundAttributes(t,e){let i;if(!((16===t||24===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=45&&e<=47))return!1;let r={};return 16===t||24===t?(i=Math.floor((e-32)/2),r.background=s9[i],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0)),this.channels[t<=23?1:2].setBkgData(r),!0}reset(){var t;for(let t=0;t<Object.keys(this.channels).length;t++){let e=this.channels[t];e&&e.reset()}(t=this.cmdHistory).a=null,t.b=null}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){let i=this.channels[e];i&&i.cueSplitAtTime(t)}}constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;let r=this.logger=new s7;this.channels=[null,new aa(t,e,r),new aa(t+1,i,r)]}}var al=function(){if(null!=eK&&eK.VTTCue)return self.VTTCue;let t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e||!Array.isArray(t))return!1;let i=e.toLowerCase();return!!~t.indexOf(i)&&i}function r(t){for(var e=arguments.length,i=Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];let s=1;for(;s<arguments.length;s++){let e=arguments[s];for(let i in e)t[i]=e[i]}return t}function s(s,a,n){let l={enumerable:!0};this.hasBeenReset=!1;let o="",h=!1,d=s,c=a,u=n,f=null,g="",m=!0,p="auto",E="start",y=50,v="middle",T=50,S="middle";Object.defineProperty(this,"id",r({},l,{get:function(){return o},set:function(t){o=""+t}})),Object.defineProperty(this,"pauseOnExit",r({},l,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(this,"startTime",r({},l,{get:function(){return d},set:function(t){if("number"!=typeof t)throw TypeError("Start time must be set to a number.");d=t,this.hasBeenReset=!0}})),Object.defineProperty(this,"endTime",r({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw TypeError("End time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(this,"text",r({},l,{get:function(){return u},set:function(t){u=""+t,this.hasBeenReset=!0}})),Object.defineProperty(this,"region",r({},l,{get:function(){return f},set:function(t){f=t,this.hasBeenReset=!0}})),Object.defineProperty(this,"vertical",r({},l,{get:function(){return g},set:function(e){let r=i(t,e);if(!1===r)throw SyntaxError("An invalid or illegal string was specified.");g=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"snapToLines",r({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(this,"line",r({},l,{get:function(){return p},set:function(t){if("number"!=typeof t&&"auto"!==t)throw SyntaxError("An invalid number or illegal string was specified.");p=t,this.hasBeenReset=!0}})),Object.defineProperty(this,"lineAlign",r({},l,{get:function(){return E},set:function(t){let r=i(e,t);if(!r)throw SyntaxError("An invalid or illegal string was specified.");E=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"position",r({},l,{get:function(){return y},set:function(t){if(t<0||t>100)throw Error("Position must be between 0 and 100.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(this,"positionAlign",r({},l,{get:function(){return v},set:function(t){let r=i(e,t);if(!r)throw SyntaxError("An invalid or illegal string was specified.");v=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"size",r({},l,{get:function(){return T},set:function(t){if(t<0||t>100)throw Error("Size must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(this,"align",r({},l,{get:function(){return S},set:function(t){let r=i(e,t);if(!r)throw SyntaxError("An invalid or illegal string was specified.");S=r,this.hasBeenReset=!0}})),this.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class ao{decode(t,e){if(!t)return"";if("string"!=typeof t)throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function ah(t){function e(t,e,i,r){return(0|t)*3600+(0|e)*60+(0|i)+parseFloat(r||0)}let i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class ad{set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let r=0;r<i.length;++r)if(e===i[r]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){let i=parseFloat(e);
1if(i>=0&&i<=100)return this.set(t,i),!0}return!1}constructor(){this.values=Object.create(null)}}function ac(t,e,i,r){let s=r?t.split(r):[t];for(let t in s){if("string"!=typeof s[t])continue;let r=s[t].split(i);2===r.length&&e(r[0],r[1])}}let au=new al(0,0,""),af="middle"===au.align?"middle":"center";function ag(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class am{parse(t){let e=this;function i(){let t=e.buffer,i=0;for(t=ag(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;let r=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),r}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;let r=(t=i()).match(/^()?WEBVTT([ \t].*)?$/);if(!(null!=r&&r[0]))throw Error("Malformed WebVTT signature.");e.state="HEADER"}let s=!1;for(;e.buffer&&/\r\n|\n/.test(e.buffer);)switch(s?s=!1:t=i(),e.state){case"HEADER":if(/:/.test(t)){var r;r=t,ac(r,function(t,e){},/:/)}else t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new al(0,0,""),e.state="CUE",-1===t.indexOf("-->")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{!function(t,e,i){let r=t;function s(){let e=ah(t);if(null===e)throw Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),"-->"!==t.slice(0,3))throw Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);t=t.slice(3),a(),e.endTime=s(),a(),function(t,e){let r=new ad;ac(t,function(t,e){let s;switch(t){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===e){r.set(t,i[s].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":s=e.split(","),r.integer(t,s[0]),r.percent(t,s[0])&&r.set("snapToLines",!1),r.alt(t,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",af,"end"]);break;case"position":s=e.split(","),r.percent(t,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",af,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",af,"end","left","right"])}},/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===au.line&&(s=-1),e.line=s,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",af);let a=r.get("position","auto");"auto"===a&&50===au.position&&(a="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=a}(t,e)}(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{let i=-1!==t.indexOf("-->");if(!t||i&&(s=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){try{if((this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state||"BADWEBVTT"===this.state)throw Error("Malformed WebVTT signature.")}catch(t){this.onparsingerror&&this.onparsingerror(t)}return this.onflush&&this.onflush(),this}constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ao,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}}let ap=/\r\n|\n\r|\n|\r/g,aE=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return t.slice(i,i+e.length)===e},ay=function(t){let e=parseInt(t.slice(-3)),i=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),a=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!s(e)||!s(i)||!s(r)||!s(a))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(t));return e+(1e3*i+6e4*r+36e5*a)};function av(t,e,i){return sG(t.toString())+sG(e.toString())+sG(i)}let aT=function(t,e,i){let r=t[e],s=t[r.prevCC];if(!s||!s.new&&r.new){t.ccOffset=t.presentationOffset=r.start,r.new=!1;return}for(;null!=(a=s)&&a.new;){var a;t.ccOffset+=r.start-s.start,r.new=!1,s=t[(r=s).prevCC]}t.presentationOffset=i},aS="stpp.ttml.im1t",aA=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,aL=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,aI={left:"start",center:"center",right:"end",start:"start",end:"end"};function aR(t,e,i,r){let s=tr(new Uint8Array(t),["mdat"]);if(0===s.length){r(Error("Could not parse IMSC1 mdat"));return}let a=s.map(t=>B(t)),n=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return rE(t,1,1/i,r)}(e.baseTime,1,e.timescale);try{a.forEach(t=>i(function(t,e){let i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw Error("Invalid ttml");let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((t,e)=>(t[e]=i.getAttribute("ttp:".concat(e))||r[e],t),{}),a="preserve"!==i.getAttribute("xml:space"),n=aD(ab(i,"styling","style")),l=aD(ab(i,"layout","region")),o=ab(i,"body","[begin]");return[].map.call(o,t=>{let i=function t(e,i){return[].slice.call(e.childNodes).reduce((e,r,s)=>{var a;return"br"===r.nodeName&&s?e+"\n":null!=(a=r.childNodes)&&a.length?t(r,i):i?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}(t,a);if(!i||!t.hasAttribute("begin"))return null;let r=aP(t.getAttribute("begin"),s),o=aP(t.getAttribute("dur"),s),h=aP(t.getAttribute("end"),s);if(null===r)throw a_(t);if(null===h){if(null===o)throw a_(t);h=r+o}let d=new al(r-e,h-e,i);d.id=av(d.startTime,d.endTime,d.text);
1let c=l[t.getAttribute("region")],u=function(t,e,i){let r="http://www.w3.org/ns/ttml#styling",s=null,a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(s=i[a]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((i,a)=>{let n=ak(e,r,a)||ak(t,r,a)||ak(s,r,a);return n&&(i[a]=n),i},{})}(c,n[t.getAttribute("style")],n),{textAlign:f}=u;if(f){let t=aI[f];t&&(d.lineAlign=t),d.align=f}return k(d,u),d}).filter(t=>null!==t)}(t,n)))}catch(t){r(t)}}function ab(t,e,i){let r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function aD(t){return t.reduce((t,e)=>{let i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function ak(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function a_(t){return Error("Could not parse ttml timestamp ".concat(t))}function aP(t,e){if(!t)return null;let i=ah(t);return null===i&&(aA.test(t)?i=function(t,e){let i=aA.exec(t),r=(0|i[4])+(0|i[5])/e.subFrameRate;return(0|i[1])*3600+(0|i[2])*60+(0|i[3])+r/e.frameRate}(t,e):aL.test(t)&&(i=function(t,e){let i=aL.exec(t),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}(t,e))),i}class aC{dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}}class aO{destroy(){let{hls:t}=this;t.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(h.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(h.FRAG_LOADING,this.onFragLoading,this),t.off(h.FRAG_LOADED,this.onFragLoaded,this),t.off(h.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(h.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(h.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(h.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let t=new aC(this,"textTrack1"),e=new aC(this,"textTrack2"),i=new aC(this,"textTrack3"),r=new aC(this,"textTrack4");this.cea608Parser1=new an(1,t,e),this.cea608Parser2=new an(3,i,r)}addCues(t,e,i,r,s){let a=!1;for(let t=s.length;t--;){var n;let r=s[t],l=(n=r[0],Math.min(r[1],i)-Math.max(n,e));if(l>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],i),a=!0,l/(i-e)>.5))return}if(a||s.push([e,i]),this.config.renderTextTracksNatively){let s=this.captionsTracks[t];this.Cues.newCue(s,e,i,r)}else{let s=this.Cues.newCue(null,e,i,r);this.hls.trigger(h.CUES_PARSED,{type:"captions",cues:s,track:t})}}onInitPtsFound(t,e){let{frag:i,id:r,initPTS:s,timescale:a,trackId:n}=e,{unparsedVttFrags:l}=this;r===R.MAIN&&(this.initPTS[i.cc]={baseTime:s,timescale:a,trackId:n}),l.length&&(this.unparsedVttFrags=[],l.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(h.FRAG_LOADED,t):this.hls.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,e){let{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){let s=i.textTracks[r];if(aM(s,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;let{captionsProperties:e,captionsTracks:i,media:r}=this,{label:s,languageCode:a}=e[t],n=this.getExistingTrack(s,a);if(n)i[t]=n,sF(i[t]),sM(i[t],r);else{let e=this.createTextTrack("captions",s,a);e&&(e[t]=!0,i[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;let e=this.captionsProperties[t];
1if(!e)return;let i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(h.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){let r=this.media;if(r)return r.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){let i=!!e.transferMedia;if(this.media=null,i)return;let{captionsTracks:r}=this;Object.keys(r).forEach(t=>{sF(r[t]),delete r[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ax(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:t}=this;if(!t)return;let e=t.textTracks;if(e)for(let t=0;t<e.length;t++)sF(e[t])}onSubtitleTracksUpdated(t,e){let i=e.subtitleTracks||[],r=i.some(t=>t.textCodec===aS);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(rG(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let t=this.media,e=t?sU(t.textTracks):null;if(this.tracks.forEach((t,i)=>{let r;if(e){let i=null;for(let r=0;r<e.length;r++)if(e[r]&&aM(e[r],t)){i=e[r],e[r]=null;break}i&&(r=i)}if(r)sF(r);else{let e=aw(t);(r=this.createTextTrack(e,t.name,t.lang))&&(r.mode="disabled")}r&&this.textTracks.push(r)}),null!=e&&e.length){let t=e.filter(t=>null!==t).map(t=>t.label);t.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: ".concat(t.join(", "),". Replace media element for each source to clear TextTracks and captions menu."))}}else if(this.tracks.length){let t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(h.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{let e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;let i="textTrack".concat(e[1]),r=this.captionsProperties[i];r&&(r.label=t.name,t.lang&&(r.languageCode=t.lang),r.media=t)})}closedCaptionsForLevel(t){let e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===R.MAIN){var i,r;let{cea608Parser1:t,cea608Parser2:s,lastSn:a}=this,{cc:n,sn:l}=e.frag,o=null!=(i=null==(r=e.part)?void 0:r.index)?i:-1;t&&s&&(l!==a+1||l===a&&o!==this.lastPartIndex+1||n!==this.lastCc)&&(t.reset(),s.reset()),this.lastCc=n,this.lastSn=l,this.lastPartIndex=o}}onFragLoaded(t,e){let{frag:i,payload:r}=e;if(i.type===R.SUBTITLE){if(r.byteLength){let t=i.decryptdata,s="stats"in e;if(null==t||!t.encrypted||s){let t=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),t&&t.textCodec===aS?this._parseIMSC1(i,r):this._parseVTTs(e)}}else this.hls.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:Error("Empty subtitle payload")})}}_parseIMSC1(t,e){let i=this.hls;aR(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{i.logger.log("Failed to parse IMSC1: ".concat(e)),i.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;let{frag:i,payload:r}=t,{initPTS:s,unparsedVttFrags:a}=this,n=s.length-1;if(!s[i.cc]&&-1===n){a.push(t);return}let l=this.hls;!function(t,e,i,r,s,a,n){let l;let o=new am,h=B(new Uint8Array(t)).trim().replace(ap,"\n").split("\n"),d=[],c=e?function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return rE(t,9e4,1/e)}(e.baseTime,e.timescale):0,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(t){let a=i[r],n=i.ccOffset,o=(f-c)/9e4;if(null!=a&&a.new&&(void 0!==g?n=i.ccOffset=a.start:aT(i,r,o)),o){if(!e){l=Error("Missing initPTS for VTT MPEGTS");return}n=o-i.presentationOffset}let h=t.endTime-t.startTime,u=rI((t.startTime+n-g)*9e4,9e4*s)/9e4;
1t.startTime=Math.max(u,0),t.endTime=Math.max(u+h,0);let m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=av(t.startTime,t.endTime,m)),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){l=t},o.onflush=function(){if(l){n(l);return}a(d)},h.forEach(t=>{if(m){if(aE(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach(t=>{aE(t,"LOCAL:")?u=t.slice(6):aE(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=ay(u)/1e3}catch(t){l=t}return}""===t&&(m=!1)}o.parse(t+"\n")}),o.flush()}(null!=(e=i.initSegment)&&e.data?tc(i.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,t=>{this._appendCues(t,i.level),l.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},e=>{let s="Missing initPTS for VTT MPEGTS"===e.message;s?a.push(t):this._fallbackToIMSC1(i,r),l.logger.log("Failed to parse VTT cue: ".concat(e)),s&&n>i.cc||l.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})})}_fallbackToIMSC1(t,e){let i=this.tracks[t.level];i.textCodec||aR(e,this.initPTS[t.cc],()=>{i.textCodec=aS,this._parseIMSC1(t,e)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){let i=this.hls;if(this.config.renderTextTracksNatively){let i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach(t=>sx(i,t))}else{let r=this.tracks[e];if(!r)return;let s=r.default?"default":"subtitles"+e;i.trigger(h.CUES_PARSED,{type:"subtitles",cues:t,track:s})}}onFragDecrypted(t,e){let{frag:i}=e;i.type===R.SUBTITLE&&this.onFragLoaded(h.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=e;if(i.type!==R.MAIN||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<r.length;t++){let e=r[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();let i=this.extractCea608Data(e);this.cea608Parser1.addData(r[t].pts,i[0]),this.cea608Parser2.addData(r[t].pts,i[1])}}}onBufferFlushing(t,e){let{startOffset:i,endOffset:r,endOffsetSubtitles:s,type:a}=e,{media:n}=this;if(n&&!(n.currentTime<r)){if(!a||"video"===a){let{captionsTracks:t}=this;Object.keys(t).forEach(e=>sN(t[e],i,r))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==s){let{textTracks:t}=this;Object.keys(t).forEach(e=>sN(t[e],i,s))}}}extractCea608Data(t){let e=[[],[]],i=31&t[0],r=2;for(let s=0;s<i;s++){let i=t[r++],s=127&t[r++],a=127&t[r++];if((0!==s||0!==a)&&(4&i)!=0){let t=3&i;(0===t||1===t)&&(e[t].push(s),e[t].push(a))}}return e}constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ax(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(h.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(h.FRAG_LOADING,this.onFragLoading,this),t.on(h.FRAG_LOADED,this.onFragLoaded,this),t.on(h.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(h.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(h.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(h.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this)}}function aw(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function aM(t,e){return!!t&&t.kind===aw(e)&&rV(e,t)}function ax(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}let aF=/\s/,aN=/(\d+)-(\d+)\/(\d+)/;class aU{destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){let r=this.stats;if(r.loading.start)throw Error("Loader can only be used once.");r.loading.start=self.performance.now();let a=function(t,e){let i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(k({},t.headers))};return t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),i}(t,this.controller.signal),n="arraybuffer"===t.responseType,l=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,a),self.clearTimeout(this.requestTimeout),e.timeout=o&&s(o)?o:h,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))},e.timeout),(rw(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var a;this.response=this.loader=i;let l=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))},h-(l-r.loading.start)),!i.ok){let{status:t,statusText:e}=i;throw new aG(e||"fetch, bad network response",t,i)}r.loading.first=l,r.total=function(t){let e=t.get("Content-Range");if(e){let t=function(t){let e=aN.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(s(t))return t}let i=t.get("Content-Length");if(i)return parseInt(i)}(i.headers)||r.total;let o=null==(a=this.callbacks)?void 0:a.onProgress;return o&&s(e.highWaterMark)?this.loadProgressively(i,r,t,e.highWaterMark,o):n?i.arrayBuffer():"json"===t.responseType?i.json():i.text()}).then(i=>{var a,n;let o=this.response;if(!o)throw Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let h=i[l];h&&(r.loaded=r.total=h);let d={url:o.url,data:i,code:o.status},c=null==(a=this.callbacks)?void 0:a.onProgress;c&&!s(e.highWaterMark)&&c(r,t,i,o),null==(n=this.callbacks)||n.onSuccess(d,r,t,o)}).catch(e=>{var i;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let s=e&&e.code||0,a=e?e.message:null;null==(i=this.callbacks)||i.onError({code:s,text:a},t,e?e.details:null,r)}
1)}getCacheAge(){let t=null;if(this.response){let e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,s=arguments.length>4?arguments[4]:void 0,a=new ik,n=t.body.getReader(),l=()=>n.read().then(n=>{if(n.done)return a.dataLength&&s(e,i,a.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));let o=n.value,h=o.length;return e.loaded+=h,h<r||a.dataLength?(a.push(o),a.dataLength>=r&&s(e,i,a.flush().buffer,t)):s(e,i,o.buffer,t),l()}).catch(()=>Promise.reject());return l()}constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||aB,this.controller=new self.AbortController,this.stats=new Y}}function aB(t,e){return new self.Request(t.url,e)}class aG extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}let aK=/^age:\s*[\d.]+\s*$/im;class aV{destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){let{config:t,context:e}=this;if(!t||!e)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let s=this.xhrSetup;s?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return s(i,e.url)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),s(i,e.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var s;null==(s=this.callbacks)||s.onError({code:i.status,text:t.message},e,i,r)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);let r=e.headers,{maxTimeToFirstByteMs:a,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(let e in r)t.setRequestHeader(e,r[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=a&&s(a)?a:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){let{context:t,loader:e,stats:i}=this;if(!t||!e)return;let r=e.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){var a,n,l;self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;let r=e.status,o="text"===e.responseType?e.responseText:null;if(r>=200&&r<300){let s=null!=o?o:e.response;if(null!=s){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l="arraybuffer"===e.responseType?s.byteLength:s.length;i.loaded=i.total=l,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);let o=null==(a=this.callbacks)?void 0:a.onProgress;o&&o(i,t,s,e);let h={url:e.responseURL,data:s,code:r};null==(n=this.callbacks)||n.onSuccess(h,i,t,e);return}}let h=s.loadPolicy.errorRetry;et(h,i.retry,!1,{url:t.url,data:void 0,code:r})?this.retry(h):(F.error("".concat(r," while loading ").concat(t.url)),null==(l=this.callbacks)||l.onError({code:r,text:e.statusText},t,e,i))}}loadtimeout(){if(!this.config)return;let t=this.config.loadPolicy.timeoutRetry;if(et(t,this.stats.retry,!0))this.retry(t);else{var e;F.warn("timeout while loading ".concat(null==(e=this.context)?void 0:e.url));let t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){let{context:e,stats:i}=this;this.retryDelay=t9(t,i.retry),i.retry++,F.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==e?void 0:e.url,", retrying ").concat(i.retry,"/").concat(t.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){let e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&aK.test(this.loader.getAllResponseHeaders())){let e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&RegExp("^".concat(t,":\\s*[\\d.]+\\s*$"),"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new Y,this.retryDelay=0}}let aH=P(P({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftw
1areAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:aV,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:tJ,bufferController:rX,capLevelController:r$,errorController:es,fpsController:sw,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:eq,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:{newCue(t,e,i,r){let s,a,n,l,o;let h=[],d=self.VTTCue||self.TextTrackCue;for(let u=0;u<r.rows.length;u++)if(s=r.rows[u],n=!0,l=0,o="",!s.isEmpty()){var c;for(let t=0;t<s.chars.length;t++)aF.test(s.chars[t].uchar)&&n?l++:(o+=s.chars[t].uchar,n=!1);s.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;let r=ag(o.trim()),f=av(e,i,r);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||((a=new d(e,i,r)).id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),h.push(a))}return t&&h.length&&(h.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),h.forEach(e=>sx(t,e))),h}},enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:s0,subtitleTrackController:sB,timelineController:aO,audioStreamController:rU,audioTrackController:rH,emeController:s_,cmcdController:sR,contentSteeringController:sb,interstitialsController:sJ});class aY extends eT{registerListeners(){let{hls:t}=this;
1t&&(t.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(h.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:t}=this;t&&(t.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(h.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;let i=this.media=e.media;iA(i,"playing",this.onMediaPlaying),iA(i,"waiting",this.onMediaWaiting),iA(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();let{media:i}=this;i&&(iL(i,"playing",this.onMediaPlaying),iL(i,"waiting",this.onMediaWaiting),iL(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!(null!=(t=this.media)&&t.readyState)||!this.hasBuffered)return;let e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var i,r,s;let a=null==(i=this.hls)?void 0:i.config;if(!a)return;let n=this.media;if(!n)return;let{seeking:l}=n,o=this.seeking&&!l,d=!this.seeking&&l,c=n.paused&&!l||n.ended||0===n.playbackRate;if(this.seeking=l,t!==e){e&&(this.ended=0),this.moved=!0,!l&&(this.nudgeRetry=0,a.nudgeOnVideoHole&&!c&&t>e&&this.nudgeOnVideoHole(t,e)),0===this.waiting&&this.stallResolved(t);return}if(d||o){o&&this.stallResolved(t);return}if(c){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(h.MEDIA_ENDED,{stalled:!1}));return}if(!eI.getBuffered(n).length){this.nudgeRetry=0;return}let u=eI.bufferInfo(n,t,0),f=u.nextStart||0,g=this.fragmentTracker;if(l&&g&&this.hls){let e=aW(this.hls.inFlightFragments,t),i=u.len>2,r=!f||e||f-t>2&&!g.getPartialFragment(t);if(i||r)return;this.moved=!1}let m=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&g){if(!(u.len>0)&&!f)return;let e=Math.max(f,u.start||0)-t,i=null!=m&&m.live?2*m.targetduration:2,r=aq(t,g);if(e>0&&(e<=i||r)){n.paused||this._trySkipBufferHole(r);return}}let p=a.detectStallWithCurrentTimeMs,E=self.performance.now(),y=this.waiting,v=this.stalled;if(null===v){if(y>0&&E-y<p)v=this.stalled=y;else{this.stalled=E;return}}let T=E-v;if(!l&&(T>=p||y)&&this.hls){if((null==(s=this.mediaSource)?void 0:s.readyState)==="ended"&&!(null!=m&&m.live)&&1>Math.abs(t-((null==m?void 0:m.edge)||0))){if(this.ended)return;this.ended=t||1,this.hls.trigger(h.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}let S=eI.bufferInfo(n,t,a.maxBufferHole);this._tryFixBufferStall(S,T,t)}stallResolved(t){let e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-e;this.log("playback not stuck anymore @".concat(t,", after ").concat(Math.round(i),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(h.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&t>r.end(0)){let i=eI.bufferedInfo(eI.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){let i=eI.timeRangesToArray(r),s=eI.bufferedInfo(i,e,0).bufferedIndex;if(s>-1&&s<i.length-1){let e=eI.bufferedInfo(i,t,0).bufferedIndex,r=i[s].end,a=i[s+1].start;if((-1===e||e>s)&&a-r<1&&t-r<2){let i=Error("nudging playhead to flush pipeline after video hole. currentTime: ".concat(t," hole: ").concat(r," -> ").concat(a," buffered index: ").concat(e));this.warn(i.message),this.media.currentTime+=1e-6;let s=aq(t,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);let n=eI.bufferInfo(this.media,t,0);this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:s,buffer:n.len,bufferInfo:n})}}}}}_tryFixBufferStall(t,e,i){var r,s;let{fragmentTracker:a,media:n}=this,l=null==(r=this.hls)?void 0:r.config;if(!n||!a||!l)return;let o=null==(s=this.hls)?void 0:s.latestLevelDetails,h=aq(i,a);if((h||null!=o&&o.live&&i<o.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;let d=t.buffered,c=this.adjacentTraversal(t,i);(d&&d.length>1&&t.len>l.maxBufferHole||t.nextStart&&(t.nextStart-i<l.maxBufferHole||c))&&(e>1e3*l.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){let i=this.fragmentTracker,r=t.nextStart;if(i&&r){let t=i.getFragAtPos(e,R.MAIN),s=i.getFragAtPos(r,R.MAIN);if(t&&s)return s.sn-t.sn<2}return!1}_reportStall(t){let{hls:e,media:i,stallReported:r,stalled:s}=this;if(!r&&null!==s&&i&&e){this.stallReported=!0;let r=Error("Playback stalling at @".concat(i.currentTime," due to low buffer (").concat(tY(t),")"));this.warn(r.message),e.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len,bufferInfo:t,stalled:{start:s}})}}_trySkipBufferHole(t){var e,i;let{fragmentTracker:r,media:s}=this,a=null==(e=this.hls)?void 0:e.config;if(!s||!r||!a)return 0;let n=s.currentTime,d=eI.bufferInfo(s,n,0),c=n<d.start?d.start:d.nextStart;if(c&&this.hls){let e=d.len<=a.maxBufferHole,u=d.len>0&&d.len<1&&s.readyState<3,f=c-n;if(f>0&&(e||u)){if(f>a.maxBufferHole){let e=!1;if(0===n){let t=r.getAppendedFrag(0,R.MAIN);t&&c<t.end&&(e=!0)}if(!e&&t){if(!(null!=(i=this.hls.loadLevelObj)&&i.details)||aW(this.hls.inFlightFragments,c))return 0;let e=!1,s=t.end;for(;s<c;){let t=aq(s,r);if(t)s+=t.duration;else{e=!0;break}}if(e)return 0}}let e=Math.max(c+.05,n+.1);if(this.warn("skipping hole, adjusting currentTime from ".concat(n," to ").concat(e)),this.moved=!0,s.currentTime=e,!(null!=t&&t.gap)){let i=Error("fragment loaded with buffer holes, seeking from ".concat(n," to ").concat(e)),r={type:l.MEDIA_ERROR,details:o.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:d.len,bufferInfo:d};t&&("fragment"in t?r.part=t:r.frag=t),this.hls.trigger(h.ERROR,r)}return e}}return 0}_tryNudgeBuffer(t){let{hls:e,media:i,nudgeRetry:r}=this,s=null==e?void 0:e.config;if(!i||!s)return 0;let a=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){let n=a+(r+1)*s.nudgeOffset,d=Error("Nudging 'currentTime' from ".concat(a," to ").concat(n));this.warn(d.message),i.currentTime=n,e.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_NUDGE_ON_STALL,error:d,fatal:!1,buffer:t.len,bufferInfo:t})}else{let i=Error("Playhead still not moving while enough data buffered @".concat(a," after ").concat(s.nudgeMaxRetry," nudges"));this.error(i.message),e.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>
1{if(this.hls){var t;this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(h.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=e,this.registerListeners()}}function aW(t,e){let i=aj(t.main);if(i&&i.start<=e)return i;let r=aj(t.audio);return r&&r.start<=e?r:null}function aj(t){if(!t)return null;switch(t.state){case iR.IDLE:case iR.STOPPED:case iR.ENDED:case iR.ERROR:return null}return t.frag}function aq(t,e){return e.getAppendedFrag(t,R.MAIN)||e.getPartialFragment(t)}function aX(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function aQ(t,e,i,r,s){let a=new t(e,i,"");try{a.value=r,s&&(a.type=s)}catch(n){a=new t(e,i,tY(s?P({type:s},r):r))}return a}let az=(()=>{let t=aX();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class a${destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:t}=this;t&&(t.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(h.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(h.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:t}=this;t&&(t.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(h.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(h.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var i;this.media=e.media,(null==(i=e.overrides)?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var t;let e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null,e.transferMedia||(this.id3Track&&(this.removeCues&&sF(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){let e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){let i=t[e];if("metadata"===i.kind&&"id3"===i.label)return sM(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;let{samples:s}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=aX();if(a)for(let t=0;t<s.length;t++){let e=s[t].type;if(e===iq.emsg&&!i||!r)continue;let n=iY(s[t].data),l=s[t].pts,o=l+s[t].duration;o>az&&(o=az),o-l<=0&&(o=l+.25);for(let t=0;t<n.length;t++){let i=n[t];if(!iW(i)){this.updateId3CueEnds(l,e);let t=aQ(a,l,o,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(t,e){var i;let r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){let s=r[i];s.type===e&&s.startTime<t&&s.endTime===az&&(s.endTime=t)}}onBufferFlushing(t,e){let{startOffset:i,endOffset:r,type:s}=e,{id3Track:a,hls:n}=this;if(!n)return;let{config:{enableEmsgMetadataCues:l,enableID3MetadataCues:o}}=n;a&&(l||o)&&sN(a,i,r,"audio"===s?t=>t.type===iq.audioId3&&o:"video"===s?t=>t.type===iq.emsg&&l:t=>t.type===iq.audioId3&&o||t.type===iq.emsg&&l)}onLevelUpdated(t,e){let{details:i}=e;this.updateDateRangeCues(i,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){var i,r;if(!this.hls||!this.media)return;let{assetPlayerId:a,timelineOffset:n,enableDateRangeMetadataCues:l,interstitialsController:o}=this.hls.config;if(!l)return;let h=aX();if(a&&n&&!o){let{fragmentStart:e,fragmentEnd:i}=t,r=this.assetCue;r?(r.startTime=e,r.endTime=i):h&&(r=this.assetCue=aQ(h,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(r.id=a,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter))}if(!t.hasProgramDateTime)return;let{id3Track:d}=this,{dateRanges:c}=t,u=Object.keys(c),f=this.dateRangeCuesAppended;if(d&&e){if(null!=(i=d.cues)&&i.length){let t=Object.keys(f).filter(t=>!u.includes(t));for(let e=t.length;e--;){let i=t[e],s=null==(r=f[i])?void 0:r.cues;
1delete f[i],s&&Object.keys(s).forEach(t=>{let e=s[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{d.removeCue(e)}catch(t){}}})}}else f=this.dateRangeCuesAppended={}}let g=t.fragments[t.fragments.length-1];if(0!==u.length&&s(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<u.length;t++){let e=u[t],i=c[e],r=i.startTime,s=f[e],a=(null==s?void 0:s.cues)||{},n=(null==s?void 0:s.durationKnown)||!1,l=az,{duration:d,endDate:g}=i;if(g&&null!==d)l=r+d,n=!0;else if(i.endOnNext&&!n){let t=u.reduce((t,e)=>{if(e!==i.id){let r=c[e];if(r.class===i.class&&r.startDate>i.startDate&&(!t||i.startDate<t.startDate))return r}return t},null);t&&(l=t.startTime,n=!0)}let m=Object.keys(i.attr);for(let t=0;t<m.length;t++){let d=m[t];if(!("ID"!==d&&"CLASS"!==d&&"CUE"!==d&&"START-DATE"!==d&&"DURATION"!==d&&"END-DATE"!==d&&"END-ON-NEXT"!==d))continue;let c=a[d];if(c)n&&!(null!=s&&s.durationKnown)?c.endTime=l:Math.abs(c.startTime-r)>.01&&(c.startTime=r,c.endTime=l);else if(h){let t=i.attr[d];("SCTE35-OUT"===d||"SCTE35-IN"===d||"SCTE35-CMD"===d)&&(t=K(t));let s=aQ(h,r,l,{key:d,data:t},iq.dateRange);s&&(s.id=e,this.id3Track.addCue(s),a[d]=s,o&&("X-ASSET-LIST"===d||"X-ASSET-URL"===d)&&s.addEventListener("enter",this.onEventCueEnter))}}f[e]={cues:a,dateRange:i,durationKnown:n}}}}constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(h.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}}class aZ{get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;let e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){let t=this.levelDetails;if(null===t||null===this.hls)return null;let{holdBack:e,partHoldBack:i,targetduration:r}=t,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:n}=this.config,l=this.hls.userConfig,o=n&&i||e;return(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===o)&&(o=void 0!==s?s:a*r),o+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,r)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){let t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;let i=this.levelDetails;if(null===i)return null;let r=i.edge,s=t-e-this.edgeStalled;return Math.min(Math.max(r-i.totalduration,s),r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration))}get drift(){let t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){let t=this.levelDetails;if(null===t)return 0;let e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){let{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;let i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:t}=this;t&&(t.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(h.ERROR,this.onError,this))}unregisterListeners(){let{hls:t}=this;t&&(t.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(h.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,e){let{details:i}=e;i.advanced&&this.onTimeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var i;e.details===o.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var i,r;t.playbackRate!==e&&(null==(i=this.hls)||i.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(r=this.targetLatency)?void 0:r.toFixed(3),", forwardBufferLength=").concat(this.forwardBufferLength.toFixed(3),": adjusting playback rate from ").concat(t.playbackRate," to ").concat(e)),t.playbackRate=e)}estimateLiveEdge(){let t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){let t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;let i=this.computeLatency();if(null===i)return;this._latency=i;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!e.live)return;let a=this.targetLatency;if(null===a)return;let n=i-a;if(n<Math.min(this.maxLatency,a+e.targetduration)&&n>.05&&this.forwardBufferLength>1){let e=Math.round(2/(1+Math.exp(-.75*n-this.edgeStalled))*20)/20;this.changeMediaPlaybackRate(t,Math.min(Math.min(2,Math.max(1,s)),Math.max(1,e)))}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}}class aJ extends rB{_registerListeners(){let{hls:t}=this;t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(h.LEVEL_LOADED,this.onLevelLoaded,this),t.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(h.FRAG_BUFFERED,this.onFragBuffered,this),t.on(h.ERROR,this.onError,this)}_unregisterListeners(){let{hls:t}=this;t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(h.LEVEL_LOADED,this.onLevelLoaded,this),t.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(h.FRAG_BUFFERED,this.onFragBuffered,this),t.off(h.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}
1stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){let i=this.hls.config.preferManagedMediaSource,r=[],s={},a={},n=!1,l=!1,o=!1;e.levels.forEach(t=>{let e=t.attrs,{audioCodec:h,videoCodec:d}=t;h&&(t.audioCodec=h=tb(h,i)||void 0),d&&(d=t.videoCodec=function(t){let e=t.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]="avc1.".concat(parseInt(i[1]).toString(16)).concat(("000"+parseInt(i[2]).toString(16)).slice(-4)))}return e.join(",")}(d));let{width:c,height:u,unknownCodecs:f}=t,g=(null==f?void 0:f.length)||0;if(n||(n=!!(c&&u)),l||(l=!!d),o||(o=!!h),g||h&&!this.isAudioSupported(h)||d&&!this.isVideoSupported(d)){this.log('Some or all CODECS not supported "'.concat(e.CODECS,'"'));return}let{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":E,"PATHWAY-ID":y,RESOLUTION:v,"VIDEO-RANGE":T}=e,S="".concat("".concat(y||".","-")).concat(t.bitrate,"-").concat(v,"-").concat(p,"-").concat(m,"-").concat(T,"-").concat(E);if(s[S]){if(s[S].uri===t.url||t.attrs["PATHWAY-ID"])s[S].addGroupId("audio",e.AUDIO),s[S].addGroupId("text",e.SUBTITLES);else{let e=a[S]+=1;t.attrs["PATHWAY-ID"]=Array(e+1).join(".");let i=this.createLevel(t);s[S]=i,r.push(i)}}else{let e=this.createLevel(t);s[S]=e,a[S]=1,r.push(e)}}),this.filterAndSortMediaOptions(r,e,n,l,o)}createLevel(t){let e=new tK(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let t=Error('SUPPLEMENTAL-CODECS not supported "'.concat(i.videoCodec,'"'));this.log(t.message),e.supportedResult=tw(t,[])}return e}isAudioSupported(t){return tv(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return tv(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,r,s){var a,n;let d=[],c=[],u=t,f=(null==(a=e.stats)?void 0:a.parsing)||{};if((i||r)&&s&&(u=u.filter(t=>{var e;let{videoCodec:i,videoRange:r,width:s,height:a}=t;return(!!i||!!(s&&a))&&!!(e=r)&&tN.indexOf(e)>-1})),0===u.length){Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i="one or more CODECS in variant not supported: ".concat(tY(e.levels.map(t=>t.attrs.CODECS).filter((t,e,i)=>i.indexOf(t)===e))),this.warn(i),t+=" (".concat(i,")"));let r=Error(t);this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:r,reason:i})}}),f.end=performance.now();return}e.audioTracks&&a0(d=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec))),e.subtitles&&a0(c=e.subtitles);let g=u.slice(0);u.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return tN.indexOf(t.videoRange)-tN.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){let i=tA(t.videoCodec),r=tA(e.videoCodec);if(i!==r)return r-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){let i=tL(t.codecSet),r=tL(e.codecSet);if(i!==r)return r-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let m=g[0];if(this.steering&&(u=this.steering.filterParsedLevels(u)).length!==g.length){for(let t=0;t<g.length;t++)if(g[t].pathwayId===u[0].pathwayId){m=g[t];break}}this._levels=u;for(let t=0;t<u.length;t++)if(u[t]===m){this._firstLevel=t;let e=m.bitrate,i=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(u.length," level(s) found, first bitrate: ").concat(e)),(null==(n=this.hls.userConfig)?void 0:n.abrEwmaDefaultEstimate)===void 0){let t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}let p=s&&!r,E=this.hls.config,y=!!(E.audioStreamController&&E.audioTrackController),v={levels:u,audioTracks:d,subtitleTracks:c,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:s,video:r,altAudio:y&&!p&&d.some(t=>!!t.url)};f.end=performance.now(),this.hls.trigger(h.MANIFEST_PARSED,v)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){let e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){let i=Error("invalid level idx"),r=t<0;if(this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:i,reason:i.message}),r)return;t=Math.min(t,e.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,a=e[t],n=a.attrs["PATHWAY-ID"];
1if(this.currentLevelIndex=t,this.currentLevel=a,i===t&&r&&s===n)return;this.log("Switching to level ".concat(t," (").concat(a.height?a.height+"p ":"").concat(a.videoRange?a.videoRange+" ":"").concat(a.codecSet?a.codecSet+" ":"","@").concat(a.bitrate,")").concat(n?" with Pathway "+n:""," from level ").concat(i).concat(s?" with Pathway "+s:""));let d={level:t,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(h.LEVEL_SWITCHING,d);let c=a.details;if(!c||c.live){let t=this.switchParams(a.uri,null==r?void 0:r.details,c);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){let t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){let e=this.steering.pathways(),i=t.filter(t=>-1!==e.indexOf(t));if(t.length<1){this.warn("pathwayPriority ".concat(t," should contain at least one pathway from list: ").concat(e));return}this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===I.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,e){let{frag:i}=e;if(void 0!==i&&i.type===R.MAIN){let t=i.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;let e=this._levels[i.level];null!=e&&e.loadError&&(this.log("Resetting level error count of ".concat(e.loadError," on frag buffered")),e.loadError=0)}}onLevelLoaded(t,e){var i,r;let{level:s,details:a}=e,n=e.levelInfo;if(!n){this.warn("Invalid level index ".concat(s)),null!=(r=e.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0);return}if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(s,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);let i=this.getUrlWithDirectives(t.uri,e),r=this.currentLevelIndex,s=t.attrs["PATHWAY-ID"],a=t.details,n=null==a?void 0:a.age;this.log("Loading level index ".concat(r).concat((null==e?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:"").concat(s?" Pathway "+s:"").concat(n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""," ").concat(i)),this.hls.trigger(h.LEVEL_LOADING,{url:i,level:r,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return -1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;let i=this._levels.filter((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));im(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(h.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,e){let{levels:i}=e;this._levels=i}checkMaxAutoUpdated(){let{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(h.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}}function a0(t){let e={};t.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function a1(){return self.SourceBuffer||self.WebKitSourceBuffer}function a2(){if(!N())return!1;let t=a1();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class a3 extends ib{registerListeners(){super.registerListeners();let{hls:t}=this;t.on(h.MANIFEST_PARSED,this.onManifestParsed,this),t.on(h.LEVEL_LOADING,this.onLevelLoading,this),t.on(h.LEVEL_LOADED,this.onLevelLoaded,this),t.on(h.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(h.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(h.BUFFER_CREATED,this.onBufferCreated,this),t.on(h.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(h.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:t}=this;t.off(h.MANIFEST_PARSED,this.onManifestParsed,this),t.off(h.LEVEL_LOADED,this.onLevelLoaded,this),t.off(h.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(h.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(h.BUFFER_CREATED,this.onBufferCreated,this),t.off(h.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(h.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}
1startLoad(t,e){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=r.startLevel;-1===t&&(r.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=r.firstAutoLevel),r.nextLoadLevel=t,this.level=r.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&(this.log("Override startPosition with lastCurrentTime @".concat(i.toFixed(3))),t=i),this.state=iR.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=iR.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case iR.WAITING_LEVEL:{let{levels:t,level:e}=this,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(!r||r.live&&(this.levelLastLoaded!==i||this.waitForLive(i)))this.hls.nextLoadLevel!==this.level&&(this.state=iR.IDLE);else{if(this.waitForCdnTuneIn(r))break;this.state=iR.IDLE}break}case iR.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===iR.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:t,levelLastLoaded:e,levels:i,media:r}=this;if(null===e||!r&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let s=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(null!=i&&i[s]))return;let a=i[s],n=this.getMainFwdBufferInfo();if(null===n)return;let l=this.getLevelDetails();if(l&&this._streamEnded(n,l)){let t={};2===this.altAudio&&(t.type="video"),this.hls.trigger(h.BUFFER_EOS,t),this.state=iR.ENDED;return}if(!this.buffering)return;t.loadLevel!==s&&-1===t.manualLevel&&this.log("Adapting to level ".concat(s," from level ").concat(this.level)),this.level=t.nextLoadLevel=s;let o=a.details;if(!o||this.state===iR.WAITING_LEVEL||this.waitForLive(a)){this.level=s,this.state=iR.WAITING_LEVEL,this.startFragRequested=!1;return}let d=n.len,c=this.getMaxBufferLength(a.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>n.end&&(this.backtrackFragment=null);let u=this.backtrackFragment?this.backtrackFragment.start:n.end,f=this.getNextFragment(u,o);if(this.couldBacktrack&&!this.fragPrevious&&f&&q(f)&&this.fragmentTracker.getState(f)!==en.OK){var g;let t=(null!=(g=this.backtrackFragment)?g:f).sn-o.startSN,e=o.fragments[t-1];e&&f.cc===e.cc&&(f=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&n.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,u)){if(!f.gap){let t=this.audioOnly&&!this.altAudio?W.AUDIO:W.VIDEO,e=(t===W.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,R.MAIN)}f=this.getNextFragmentLoopLoading(f,o,n,R.MAIN,c)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,u))}loadFragment(t,e,i){let r=this.fragmentTracker.getState(t);r===en.NOT_LOADED||r===en.PARTIAL?q(t)?this.bitrateTest?(this.log("Fragment ".concat(t.sn," of level ").concat(t.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,i):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,R.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;let r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let s=this.getLevelDetails();if(null!=s&&s.live){let t=this.getMainFwdBufferInfo();if(!t||t.len<2*s.targetduration)return}if(!e.paused&&t){let e=t[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*r)+1:0}else i=0;let a=this.getBufferedFrag(e.currentTime+i);if(a){let t=this.followingBufferedFrag(a);if(t){this.abortCurrentFrag();let e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,r=Math.max(a.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case iR.KEY_LOADING:case iR.FRAG_LOADING:case iR.FRAG_LOADING_WAITING_RETRY:case iR.PARSING:case iR.PARSED:this.state=iR.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);let i=e.media;iA(i,"playing",this.onMediaPlaying),iA(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){let{media:i}=this;i&&(iL(i,"playing",this.onMediaPlaying),iL(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e),e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(h.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,r=!1;for(let t=0;t<e.levels.length;t++){let s=e.levels[t].audioCodec;s&&(i=i||-1!==s.indexOf("mp4a.40.2"),r=r||-1!==s.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&r&&!function(){var t;let e=a1();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){let{levels:i}=this;if(!i||this.state!==iR.IDLE)return;let r=e.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=iR.WAITING_LEVEL)}onLevelLoaded(t,e){var i,r;let{levels:s,startFragRequested:a}=this,n=e.level,l=e.details,o=l.totalduration;if(!s){this.warn("Levels were reset while loading level ".concat(n));return}this.log("Level ".concat(n," loaded [").concat(l.startSN,",").concat(l.endSN,"]").concat(l.lastPartSn?"[part-".concat(l.lastPartSn,"-").concat(l.lastPartIndex,"]"):"",", cc [").concat(l.startCC,", ").concat(l.endCC,"] duration:").concat(o));let d=e.levelInfo,c=this.fragCurrent;c&&(this.state===iR.FRAG_LOADING||this.state===iR.FRAG_LOADING_WAITING_RETRY)&&c.level!==e.level&&c.loader&&this.abortCurrentFrag();let u=0;if(l.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(l),l.deltaUpdateFailed)return;u=this.alignPlaylists(l,d.details,null==(r=this.levelLastLoaded)?void 0:r.details)}if(d.details=l,this.levelLastLoaded=d,a||this.setStartPosition(l,u),this.hls.trigger(h.LEVEL_UPDATED,{details:l,level:n}),this.state===iR.WAITING_LEVEL){if(this.waitForCdnTuneIn(l))return;this.state=iR.IDLE}a&&l.live&&this.synchronizeToLiveEdge(l),this.tick()}synchronizeToLiveEdge(t){let{config:e,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,s=this.getLoadPosition(),a=t.fragmentStart,n=t.edge,l=s>=a-e.maxFragLookUpTolerance&&s<=n;if(null!==r&&i.duration>r&&(s<r||!l)){let a=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!l&&i.readyState<4||s<n-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState)){if(this.warn("Playback: ".concat(s.toFixed(3)," is located too far from the end of live sliding playlist: ").concat(n,", reset currentTime to : ").concat(r.toFixed(3))),"buffered"===this.config.liveSyncMode){var o;let t=eI.bufferInfo(i,r,0);if(!(null!=(o=t.buffered)&&o.length)||t.start<=s){i.currentTime=r;return}let{nextStart:e}=eI.bufferedInfo(t.buffered,s,0);e&&(i.currentTime=e)}else i.currentTime=r}}}_handleFragmentLoadProgress(t){var e;let i=t.frag,{part:r,payload:s}=t,{levels:a}=this;if(!a){this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(i.sn," of level ").concat(i.level," will not be buffered"));return}let n=a[i.level];if(!n){this.warn("Level ".concat(i.level," not found on progress"));return}let l=n.details;if(!l){this.warn("Dropping fragment ".concat(i.sn," of level ").concat(i.level," after level details were reset")),this.fragmentTracker.removeFragment(i);return}let o=n.videoCodec,h=l.PTSKnown||!l.live,d=null==(e=i.initSegment)?void 0:e.data,c=this._getAudioCodec(n),u=this.transmuxer=this.transmuxer||new rN(this.hls,R.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=new eS(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,-1!==f),m=this.initPTS[i.cc];u.push(s,d,c,o,i,r,l.totalduration,h,g,m)}onAudioTrackSwitching(t,e){let i=this.hls,r=2===this.altAudio;if(tZ(e.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.fragmentTracker.removeAllFragments(),i.once(h.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(h.AUDIO_TRACK_SWITCHED,e)}),i.trigger(h.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(h.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){let i=tZ(e.url,this.hls);if(i){let t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i?2:0,this.tick()}onBufferCreated(t,e){let i,r;let s=e.tracks,a=!1;for(let t in s){let e=s[t];if("main"===e.id){if(r=t,i=e,"video"===t){let e=s[t];e&&(this.videoBuffer=e.buffer)}}else a=!0}a&&i?(this.log("Alternate track found, use ".concat(r,".buffered to schedule main fragment loading")),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){let{frag:i,part:r}=e,s=i.type===R.MAIN;if(s){if(this.fragContextChanged(i)){this.warn("Fragment ".concat(i.sn).concat(r?" p: "+r.index:""," of level ").concat(i.level," finished buffering, but was aborted. state: ").concat(this.state)),this.state===iR.PARSED&&(this.state=iR.IDLE);return}let t=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),q(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}let a=this.media;a&&(!this._hasEnoughToStart&&eI.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal){this.state=iR.ERROR;return}switch(e.details){case o.FRAG_GAP:case o.FRAG_PARSING_ERROR:case o.FRAG_DECRYPT_ERROR:case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(R.MAIN,e);break;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==iR.WAITING_LEVEL||(null==(i=e.context)?void 0:i.type)!==I.LEVEL||(this.state=iR.IDLE);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;
1case o.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=iR.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,e){let{type:i}=e;if(i!==W.AUDIO||!this.altAudio){let t=(i===W.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,i,R.MAIN),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:t}=this;if(!t)return;let e=t.currentTime,i=this.startPosition;if(i>=0&&e<i){if(t.seeking){this.log("could not seek to ".concat(i,", already seeking at ").concat(e));return}let r=this.timelineOffset;r&&i&&(i+=r);let s=this.getLevelDetails(),a=eI.getBuffered(t),n=a.length?a.start(0):0,l=n-i,o=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<o||this.loadingParts&&l<2*((null==s?void 0:s.partTarget)||0)))&&(this.log("adjusting start position by ".concat(l," to match buffer start")),i+=l,this.startPosition=i),e<i&&(this.log("seek to target start position ".concat(i," from current time ").concat(e," buffer start ").concat(n)),t.currentTime=i)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{let{hls:i}=this,r=null==t?void 0:t.frag;if(!r||this.fragContextChanged(r))return;e.fragmentError=0,this.state=iR.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let s=r.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(h.FRAG_LOADED,t),r.bitrateTest=!1}).catch(e=>{this.state!==iR.STOPPED&&this.state!==iR.ERROR&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){let e=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:a}=t,n=this.getCurrentContext(a);if(!n){this.resetWhenMissingContext(a);return}let{frag:l,part:o,level:d}=n,{video:c,text:u,id3:f,initSegment:g}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=iR.PARSING,g){let t=g.tracks;if(t){let r=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(d,t,r,a),i.trigger(h.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:e,tracks:t})}let r=g.initPTS,n=g.timescale,o=this.initPTS[l.cc];if(s(r)&&(!o||o.baseTime!==r||o.timescale!==n)){let t=g.trackId;this.initPTS[l.cc]={baseTime:r,timescale:n,trackId:t},i.trigger(h.INIT_PTS_FOUND,{frag:l,id:e,initPTS:r,timescale:n,trackId:t})}}if(c&&m){p&&"audiovideo"===c.type&&this.logMuxedErr(l);let t=m.fragments[l.sn-1-m.startSN],e=l.sn===m.startSN,i=!t||l.cc>t.cc;if(!1!==r.independent){let{startPTS:t,endPTS:r,startDTS:s,endDTS:n}=c;if(o)o.elementaryStreams[c.type]={startPTS:t,endPTS:r,startDTS:s,endDTS:n};else if(c.firstKeyFrame&&c.independent&&1===a.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){let s=this.getMainFwdBufferInfo(),a=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,o=c.firstKeyFramePTS?c.firstKeyFramePTS:t;if(e||!(a<o-this.config.maxBufferHole)||i)i&&(l.gap=!0);else{this.backtrack(l);return}l.setElementaryStreamInfo(c.type,l.start,r,l.start,n,!0)}else e&&t-(m.appliedTimelineOffset||0)>2&&(l.gap=!0);l.setElementaryStreamInfo(c.type,t,r,s,n),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,o,a,e||i)}else if(e||i)l.gap=!0;else{this.backtrack(l);return}}if(p){let{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=p;o&&(o.elementaryStreams[W.AUDIO]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(W.AUDIO,t,e,i,r),this.bufferFragmentData(p,l,o,a)}if(m&&null!=f&&f.samples.length){let t={id:e,frag:l,details:m,samples:f.samples};i.trigger(h.FRAG_PARSING_METADATA,t)}if(m&&u){let t={id:e,frag:l,details:m,samples:u.samples};i.trigger(h.FRAG_PARSING_USERDATA,t)}}logMuxedErr(t){this.warn("".concat(q(t)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(t.url))}_bufferInitSegment(t,e,i,r){if(this.state!==iR.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));let{audio:s,video:a,audiovideo:n}=e;if(s){let i=t.audioCodec,r=tD(s.codec,i);"mp4a"===r&&(r="mp4a.40.5");let a=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){r&&(r=-1!==r.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");let t=s.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===a.indexOf("firefox")&&(r="mp4a.40.5")}r&&-1!==r.indexOf("mp4a.40.5")&&-1!==a.indexOf("android")&&"audio/mpeg"!==s.container&&(r="mp4a.40.2",this.log("Android: force audio codec to ".concat(r))),i&&i!==r&&this.log('Swapping manifest audio codec "'.concat(i,'" for "').concat(r,'"')),s.levelCodec=r,s.id=R.MAIN,this.log("Init audio buffer, container:".concat(s.container,", codecs[selected/level/parsed]=[").concat(r||"","/").concat(i||"","/").concat(s.codec,"]")),delete e.audiovideo}if(a){a.levelCodec=t.videoCodec,a.id=R.MAIN;let i=a.codec;if((null==i?void 0:i.length)===4)switch(i){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e"}this.log("Init video buffer, container:".concat(a.container,", codecs[level/parsed]=[").concat(t.videoCodec||"","/").concat(i,"]").concat(a.codec!==i?" parsed-corrected="+a.codec:"").concat(a.supplemental?" supplemental="+a.supplemental:"")),delete e.audiovideo}n&&(this.log("Init audiovideo buffer, container:".concat(n.container,", codecs[level/parsed]=[").concat(t.codecs,"/").concat(n.codec,"]")),delete e.video,delete e.audio);let l=Object.keys(e);if(l.length){if(this.hls.trigger(h.BUFFER_CODECS,e),!this.hls)return;l.forEach(t=>{let s=e[t].initSegment;null!=s&&s.byteLength&&this.hls.trigger(h.BUFFER_APPENDING,{type:t,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,R.MAIN)}get maxBufferLength(){let{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=iR.IDLE}checkFragmentChanged(){let t=this.media,e=null;if(t&&t.readyState>1&&!1===t.seeking){let i=t.currentTime;if(eI.isBuffered(t,i)?e=this.getAppendedFrag(i):eI.isBuffered(t,i+.1)&&
1(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;let t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(h.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(h.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){let t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;let e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return s(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;let e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(s(e)){let t=this.getLevelDetails(),i=this.currentFrag||(t?t1(null,t.fragments,e):null);if(i){let t=i.programDateTime;if(null!==t)return new Date(t+(e-i.start)*1e3)}}return null}get currentLevel(){let t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){let t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}constructor(t,e,i){super(t,e,i,"stream-controller",R.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let t=this.media,e=t?t.currentTime:null;if(null===e||!s(e)||(this.log("Media seeked to ".concat(e.toFixed(3))),!this.getBufferedFrag(e)))return;let i=this.getFwdBufferInfoAtPos(t,e,R.MAIN,0);if(null===i||0===i.len){this.warn("Main forward buffer length at ".concat(e,' on "seeked" event ').concat(i?i.len:"empty",")"));return}this.tick()},this.registerListeners()}}class a4 extends C{abort(t){for(let i in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[i].loader;if(r){var e;if(t&&t!==(null==(e=r.context)?void 0:e.frag.type))return;r.abort()}}}detach(){for(let t in this.keyIdToKeyInfo){let e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){for(let t in this.detach(),this.keyIdToKeyInfo){let e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o.KEY_LOAD_ERROR,i=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;return new ev({type:l.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:s,error:i,networkDetails:r})}loadClear(t,e,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let r=0,s=e.length;r<s;r++){let a=e[r];if(t.cc<=a.cc&&(!q(t)||!q(a)||t.sn<a.sn)||!i&&r==s-1)return this.emeController.selectKeySystemFormat(a).then(t=>{if(!this.emeController)return;a.setKeyFormat(t);let e=eY(t);if(e)return this.emeController.getKeySystemAccess([e])})}if(this.config.requireKeySystemAccessOnStart){let t=ej(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var i,r;e&&t.setKeyFormat(e);let s=t.decryptdata;if(!s){let i=Error(e?"Expected frag.decryptdata to be defined after setting format ".concat(e):"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"));return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,i))}let a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,Error('Invalid key URI: "'.concat(a,'"'))));let n=a5(s),l=this.keyIdToKeyInfo[n];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:t,keyInfo:l});if(this.emeController&&null!=(r=l)&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(e=>{let{keyInfo:i}=e;return s.key=i.decryptdata.key,{frag:t,keyInfo:i}})}switch(this.log("".concat(this.keyIdToKeyInfo[n]?"Rel":"L","oading").concat(s.keyId?" keyId: "+G(s.keyId):""," URI: ").concat(s.uri," from ").concat(t.type," ").concat(t.level)),l=this.keyIdToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":if("identity"===s.keyFormat)return this.loadKeyHTTP(l,t);return this.loadKeyEME(l,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,t);default:return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,Error('Key supplied with unsupported METHOD: "'.concat(s.method,'"'))))}}loadKeyEME(t,e){let i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var r;if(!t.decryptdata.keyId&&null!=(r=e.initSegment)&&r.data){let i=function(t){let e=[];return th(t,t=>
1e.push(t.subarray(8,24))),e}(e.initSegment.data);if(i.length){let e=i[0];e.some(t=>0!==t)&&(this.log("Using keyId found in init segment ".concat(G(e))),t.decryptdata.keyId=e,ez.setKeyIdForUri(t.decryptdata.uri,e))}}let s=this.emeController.loadKey(i);return(t.keyLoadPromise=s.then(e=>(t.mediaKeySessionContext=e,i))).catch(i=>{throw t.keyLoadPromise=null,"data"in i&&(i.data.frag=e),i})}return Promise.resolve(i)}loadKeyHTTP(t,e){let i=this.config,r=new i.loader(i);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise((s,a)=>{let n={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=i.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(n,h,{onSuccess:(t,e,i,r)=>{let{frag:n,keyInfo:l}=i,h=a5(l.decryptdata);if(!n.decryptdata||l!==this.keyIdToKeyInfo[h])return a(this.createKeyLoadError(n,o.KEY_LOAD_ERROR,Error("after key load, decryptdata unset or changed"),r));l.decryptdata.key=n.decryptdata.key=new Uint8Array(t.data),n.keyLoader=null,l.loader=null,s({frag:n,keyInfo:l})},onError:(t,i,r,s)=>{this.resetLoader(i),a(this.createKeyLoadError(e,o.KEY_LOAD_ERROR,Error("HTTP Error ".concat(t.code," loading key ").concat(t.text)),r,P({url:n.url,data:void 0},t)))},onTimeout:(t,i,r)=>{this.resetLoader(i),a(this.createKeyLoadError(e,o.KEY_LOAD_TIMEOUT,Error("key loading timed out"),r))},onAbort:(t,i,r)=>{this.resetLoader(i),a(this.createKeyLoadError(e,o.INTERNAL_ABORTED,Error("key loading aborted"),r))}})})}resetLoader(t){let{frag:e,keyInfo:i,url:r}=t,s=i.loader;e.keyLoader===s&&(e.keyLoader=null,i.loader=null);let a=a5(i.decryptdata)||r;delete this.keyIdToKeyInfo[a],s&&s.destroy()}constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}}function a5(t){if(t.keyFormat!==eH.FAIRPLAY){let e=t.keyId;if(e)return G(e)}return t.uri}function a8(t){let{type:e}=t;switch(e){case I.AUDIO_TRACK:return R.AUDIO;case I.SUBTITLE_TRACK:return R.SUBTITLE;default:return R.MAIN}}function a6(t,e){let i=t.url;return(void 0===i||0===i.indexOf("data:"))&&(i=e.url),i}class a9{startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:t}=this;t.on(h.MANIFEST_LOADING,this.onManifestLoading,this),t.on(h.LEVEL_LOADING,this.onLevelLoading,this),t.on(h.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(h.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:t}=this;t.off(h.MANIFEST_LOADING,this.onManifestLoading,this),t.off(h.LEVEL_LOADING,this.onLevelLoading,this),t.off(h.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(h.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){let e=this.hls.config,i=e.pLoader,r=e.loader,s=new(i||r)(e);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(let t in this.loaders){let e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){let{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:I.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){let{id:i,level:r,pathwayId:s,url:a,deliveryDirectives:n,levelInfo:l}=e;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:I.LEVEL,url:a,deliveryDirectives:n,levelOrTrack:l})}onAudioTrackLoading(t,e){let{id:i,groupId:r,url:s,deliveryDirectives:a,track:n}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:I.AUDIO_TRACK,url:s,deliveryDirectives:a,levelOrTrack:n})}onSubtitleTrackLoading(t,e){let{id:i,groupId:r,url:s,deliveryDirectives:a,track:n}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:I.SUBTITLE_TRACK,url:s,deliveryDirectives:a,levelOrTrack:n})}onLevelsUpdated(t,e){let i=this.loaders[I.LEVEL];if(i){let t=i.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(i.abort(),delete this.loaders[I.LEVEL])}}load(t){var e;let i;let r=this.hls.config,a=this.getInternalLoader(t);if(a){let e=this.hls.logger,i=a.context;if(i&&i.levelOrTrack===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives)){i.url===t.url?e.log("[playlist-loader]: ignore ".concat(t.url," ongoing request")):e.log("[playlist-loader]: ignore ".concat(t.url," in favor of ").concat(i.url));return}e.log("[playlist-loader]: aborting previous loader for type: ".concat(t.type)),a.abort()}if(i=t.type===I.MANIFEST?r.manifestLoadPolicy.default:k({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),s(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===I.LEVEL&&null!==t.level?e=this.hls.levels[t.level].details:t.type===I.AUDIO_TRACK&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===I.SUBTITLE_TRACK&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){let t=e.partTarget,r=e.targetduration;if(t&&r){let e=1e3*Math.max(3*t,.8*r);i=k({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}let n=i.errorRetry||i.timeoutRetry||{},l={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};a.load(t,l,{onSuccess:(t,e,i,r)=>{let s=this.getInternalLoader(i);this.resetInternalLoader(i.type);let a=t.data;e.parsing.start=performance.now(),e3.isMediaPlaylist(a)||i.type!==I.MANIFEST?this.handleTrackOrLevelPlaylist(t,e,i,r||null,s):this.handleMasterPlaylist(t,e,i,r)},onError:(t,e,i,r)=>{this.handleNetworkError(e,i,!1,t,r)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}})}
1checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log("".concat(t?"auto":"force"," startLoad with configured startPosition ").concat(e)),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,r){let s=this.hls,a=t.data,n=a6(t,i),l=e3.parseMasterPlaylist(a,n);if(l.playlistParsingError){e.parsing.end=performance.now(),this.handleManifestParsingError(t,i,l.playlistParsingError,r,e);return}let{contentSteering:o,levels:d,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g}=l;this.variableList=g,d.forEach(t=>{let{unknownCodecs:e}=t;if(e){let{preferManagedMediaSource:i}=this.hls.config,{audioCodec:r,videoCodec:s}=t;for(let a=e.length;a--;){let n=e[a];tv(n,"audio",i)?(t.audioCodec=r=r?"".concat(r,",").concat(n):n,tE.audio[r.substring(0,4)]=2,e.splice(a,1)):tv(n,"video",i)&&(t.videoCodec=s=s?"".concat(s,",").concat(n):n,tE.video[s.substring(0,4)]=2,e.splice(a,1))}}});let{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":E}=e3.parseMasterPlaylistMedia(a,n,l);m.length&&!m.some(t=>!t.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new eP({}),bitrate:0,url:""})),s.trigger(h.MANIFEST_LOADED,{levels:d,audioTracks:m,subtitles:p,captions:E,contentSteering:o,url:n,stats:e,networkDetails:r,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,i,r,a){let n=this.hls,{id:l,level:o,type:d}=i,c=a6(t,i),u=s(o)?o:s(l)?l:0,f=a8(i),g=e3.parseLevelPlaylist(t.data,c,u,f,0,this.variableList);if(d===I.MANIFEST){let t={attrs:new eP({}),bitrate:0,details:g,name:"",url:c};g.requestScheduled=e.loading.start+id(g,0),n.trigger(h.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:c,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=g,this.handlePlaylistLoaded(g,t,e,i,r,a)}handleManifestParsingError(t,e,i,r,s){this.hls.trigger(h.ERROR,{type:l.NETWORK_ERROR,details:o.MANIFEST_PARSING_ERROR,fatal:e.type===I.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:r,stats:s})}handleNetworkError(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0,a="A network ".concat(i?"timeout":"error"+(r?" (status "+r.code+")":"")," occurred while loading ").concat(t.type);t.type===I.LEVEL?a+=": ".concat(t.level," id: ").concat(t.id):(t.type===I.AUDIO_TRACK||t.type===I.SUBTITLE_TRACK)&&(a+=" id: ".concat(t.id,' group-id: "').concat(t.groupId,'"'));let n=Error(a);this.hls.logger.warn("[playlist-loader]: ".concat(a));let d=o.UNKNOWN,c=!1,u=this.getInternalLoader(t);switch(t.type){case I.MANIFEST:d=i?o.MANIFEST_LOAD_TIMEOUT:o.MANIFEST_LOAD_ERROR,c=!0;break;case I.LEVEL:d=i?o.LEVEL_LOAD_TIMEOUT:o.LEVEL_LOAD_ERROR,c=!1;break;case I.AUDIO_TRACK:d=i?o.AUDIO_TRACK_LOAD_TIMEOUT:o.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case I.SUBTITLE_TRACK:d=i?o.SUBTITLE_TRACK_LOAD_TIMEOUT:o.SUBTITLE_LOAD_ERROR,c=!1}u&&this.resetInternalLoader(t.type);let f={type:l.NETWORK_ERROR,details:d,fatal:c,url:t.url,loader:u,context:t,error:n,networkDetails:e,stats:s};if(r){let i=(null==e?void 0:e.url)||t.url;f.response=P({url:i,data:void 0},r)}this.hls.trigger(h.ERROR,f)}handlePlaylistLoaded(t,e,i,r,s,a){let n=this.hls,{type:d,level:c,levelOrTrack:u,id:f,groupId:g,deliveryDirectives:m}=r,p=a6(e,r),E=a8(r),y="number"==typeof r.level&&E===R.MAIN?c:void 0,v=t.playlistParsingError;if(v){if(this.hls.logger.warn("".concat(v," ").concat(t.url)),!n.config.ignorePlaylistParsingErrors){n.trigger(h.ERROR,{type:l.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:v,reason:v.message,response:e,context:r,level:y,parent:E,networkDetails:s,stats:i});return}t.playlistParsingError=null}if(!t.fragments.length){let a=t.playlistParsingError=Error("No Segments found in Playlist");
1n.trigger(h.ERROR,{type:l.NETWORK_ERROR,details:o.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:e,context:r,level:y,parent:E,networkDetails:s,stats:i});return}switch(t.live&&a&&(a.getCacheAge&&(t.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),d){case I.MANIFEST:case I.LEVEL:if(y){if(u){if(u!==n.levels[y]){let t=n.levels.indexOf(u);t>-1&&(y=t)}}else y=0}n.trigger(h.LEVEL_LOADED,{details:t,levelInfo:u||n.levels[0],level:y||0,id:f||0,stats:i,networkDetails:s,deliveryDirectives:m,withoutMultiVariant:d===I.MANIFEST});break;case I.AUDIO_TRACK:n.trigger(h.AUDIO_TRACK_LOADED,{details:t,track:u,id:f||0,groupId:g||"",stats:i,networkDetails:s,deliveryDirectives:m});break;case I.SUBTITLE_TRACK:n.trigger(h.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:f||0,groupId:g||"",stats:i,networkDetails:s,deliveryDirectives:m})}}constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}}class a7{static get version(){return iC}static isMSESupported(){return a2()}static isSupported(){return function(){if(!a2())return!1;let t=N();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(tS(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(tS(e,"audio"))))}()}static getMediaSource(){return N()}static get Events(){return h}static get MetadataSchema(){return iq}static get ErrorTypes(){return l}static get ErrorDetails(){return o}static get DefaultConfig(){return a7.defaultConfig?a7.defaultConfig:aH}static set DefaultConfig(t){a7.defaultConfig=t}createController(t,e){if(t){let i=new t(this);return e&&e.push(i),i}return null}on(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(t,e,i)}once(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,r=arguments.length>3?arguments[3]:void 0;this._emitter.off(t,e,i,r)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;let i=t===h.ERROR;this.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(h.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){let e=Error("attachMedia failed: invalid argument (".concat(t,")"));this.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.ATTACH_MEDIA_ERROR,fatal:!0,error:e});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let e="media"in t,i=e?t.media:t,r=e?t:{media:i};this._media=i,this.trigger(h.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(h.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let t=this.bufferController.transferMedia();return this.trigger(h.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();let e=this.media,i=this._url,r=this._url=H.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(r)),e&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(h.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,e=arguments.length>1?arguments[1]:void 0;this.logger.log("startLoad(".concat(t+(e?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEac
1h(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){let t={[R.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[R.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[R.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{let t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(e){let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)})}}}()),t}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log("set currentLevel:".concat(t)),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log("set nextLevel:".concat(t)),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log("set loadLevel:".concat(t)),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log("set firstLevel:".concat(t)),this.levelController.firstLevel=t}get startLevel(){let t=this.levelController.startLevel;return -1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log("set startLevel:".concat(t)),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){let e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){let{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log("set autoLevelCapping:".concat(t)),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){tF.indexOf(t)>-1&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return -1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;let i=t.length;for(let r=0;r<i;r++)if(t[r].maxBitrate>=e)return r;return 0}get maxAutoLevel(){let t;let{levels:e,autoLevelCapping:i,maxHdcpLevel:r}=this;if(t=-1===i&&null!=e&&e.length?e.length-1:i,r)for(let i=t;i--;){let t=e[i].attrs["HDCP-LEVEL"];if(t&&t<=r)return i}return t}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}
1setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){let t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){let t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){let t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){let e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){let t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){let t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){let t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){let e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){let t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){let e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!(null!=(t=this.bufferController)&&t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks;return tM(t,tj(e),navigator.mediaCapabilities)}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new iP,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let e=this.logger=function(t,e,i){let r=M();if("object"==typeof console&&!0===t||"object"==typeof t){let s=["debug","log","info","warn","error"];s.forEach(e=>{r[e]=x(e,t,i)});try{r.log('Debug logs enabled for "'.concat(e,'" in hls.js version ',"1.6.13"))}catch(t){return M()}s.forEach(e=>{F[e]=x(e,t)})}else k(F,r);return r}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(t,e,i){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let r=function t(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(t):Object.keys(e).reduce((i,r)=>(i[r]=t(e[r]),i),{}):e}(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{let a="".concat("level"===t?"playlist":t,"LoadPolicy"),n=void 0===e[a],l=[];
1s.forEach(i=>{let s="".concat(t,"Loading").concat(i),o=e[s];if(void 0!==o&&n){l.push(s);let t=r[a].default;switch(e[a]={default:t},i){case"TimeOut":t.maxLoadTimeMs=o,t.maxTimeToFirstByteMs=o;break;case"MaxRetry":t.errorRetry.maxNumRetry=o,t.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":t.errorRetry.retryDelayMs=o,t.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=o,t.timeoutRetry.maxRetryDelayMs=o}}}),l.length&&i.warn('hls.js config: "'.concat(l.join('", "'),'" setting(s) are deprecated, use "').concat(a,'": ').concat(tY(e[a])))}),P(P({},r),e)}(a7.DefaultConfig,t,e);this.userConfig=t,i.progressive&&function(t,e){let i=t.loader;i!==aU&&i!==aV?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=aU,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,e);let{abrController:r,bufferController:s,capLevelController:a,errorController:n,fpsController:l}=i,o=new n(this),d=this.abrController=new r(this),c=new el(this),u=i.interstitialsController,f=u?this.interstitialsController=new u(this,a7):null,g=this.bufferController=new s(this,c),m=this.capLevelController=new a(this),p=new l(this),E=new a9(this),y=i.contentSteeringController,v=y?new y(this):null,T=this.levelController=new aJ(this,v),S=new a$(this),A=new a4(this.config,this.logger),L=this.streamController=new a3(this,c,A),I=this.gapController=new aY(this,c);m.setStreamController(L),p.setStreamController(L);let R=[E,T,L];f&&R.splice(1,0,f),v&&R.splice(1,0,v),this.networkControllers=R;let b=[d,g,I,m,p,S,c];this.audioTrackController=this.createController(i.audioTrackController,R);let D=i.audioStreamController;D&&R.push(this.audioStreamController=new D(this,c,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,R);let _=i.subtitleStreamController;_&&R.push(this.subtititleStreamController=new _(this,c,A)),this.createController(i.timelineController,b),A.emeController=this.emeController=this.createController(i.emeController,b),this.cmcdController=this.createController(i.cmcdController,b),this.latencyController=this.createController(aZ,b),this.coreComponents=b,R.push(o);let C=o.onErrorOut;"function"==typeof C&&this.on(h.ERROR,C,o),this.on(h.MANIFEST_LOADED,E.onManifestLoaded,E)}}a7.defaultConfig=void 0}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.