news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9910],{47207:(e,t,i)=>{let r;i.d(t,{Ay:()=>aZ});let s=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},a=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=n},n=Number.MAX_SAFE_INTEGER||0x1fffffffffffff,l=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),o=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),h=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var d,u,f={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},c={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class g{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class m{constructor(e,t,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_=new g(e),this.fast_=new g(t),this.defaultTTFB_=r,this.ttfb_=new g(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new g(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new g(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new g(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){let i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){let t=Math.sqrt(2)*Math.exp(-Math.pow(e/1e3,2)/2);this.ttfb_.sample(t,Math.max(e,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(){}}function p(){return(p=Object.assign?Object.assign.bind():function(e){for(var t=1;t`):T}(e,i)}let R=A();function I(e=!0){if("undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function b(e,t){let i=Object.keys(e),r=Object.keys(t),s=i.length,a=r.length;return!s||!a||s===a&&!i.some(e=>-1===r.indexOf(e))}function D(e,t=!1){let i,r;if("undefined"!=typeof TextDecoder){let i=new TextDecoder("utf-8").decode(e);if(t){let e=i.indexOf("\0");return -1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}let s=e.length,a="",n=0;for(;n>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:a+=String.fromCharCode((31&i)<<6|63&(r=e[n++]));break;case 14:a+=String.fromCharCode((15&i)<<12|(63&(r=e[n++]))<<6|63&e[n++])}return a}function k(e){let t="";for(let i=0;i1||1===i&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!s(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return M(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let r=t[e];r&&!(null!=(i=this._decryptdata)&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,a=!1){let{elementaryStreams:n}=this,l=n[e];if(!l){n[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,s)}}class N extends w{constructor(e,t,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=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}let U=[].push,B={video:1,audio:2,id3:3,text:4};function $(e){return String.fromCharCode.apply(null,e)}function G(e,t){let i=e[t]<<8|e[t+1];return i<0?65536+i:i}function K(e,t){let i=H(e,t);return i<0?0x100000000+i:i}function V(e,t){let i=K(e,t);return i*=0x100000000,i+=K(e,t+4)}function H(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Y(e,t){let i=[];if(!t.length)return i;let r=e.byteLength;for(let s=0;s1?s+a:r;if(n===t[0])if(1===t.length)i.push(e.subarray(s+8,l));else{let r=Y(e.subarray(s+8,l),t.slice(1));r.length&&U.apply(i,r)}s=l}return i}function W(e){let t=[],i=Y(e,["moov","trak"]);for(let e=0;e{let t=Y(e,["schm"])[0];if(t){let i=$(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=Y(e,["frma"])[0];t&&(a=$(t))}}})}let l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{let e=Y(r,["avcC"])[0];e&&e.length>3&&(a+="."+X(e[1])+X(e[2])+X(e[3]),t=j("avc1"===l?"dva1":"dvav",r));break}case"mp4a":{let e=Y(i,[s])[0],t=Y(e.subarray(28),["esds"])[0];if(t&&t.length>7){let e=4;if(3!==t[e++])break;e=q(t,e)+2;let i=t[e++];if(128&i&&(e+=2),64&i&&(e+=t[e++]),4!==t[e++])break;e=q(t,e);let r=t[e++];if(64===r)a+="."+X(r);else break;if(e+=12,5!==t[e++])break;e=q(t,e);let s=t[e++],n=(248&s)>>3;31===n&&(n+=1+((7&s)<<3)+((224&t[e])>>5)),a+="."+n}break}case"hvc1":case"hev1":{let e=Y(r,["hvcC"])[0];if(e&&e.length>12){let t=e[1],i=["","A","B","C"][t>>6],r=K(e,2),s=e[12],n=e.subarray(6,12);a+="."+i+(31&t),a+="."+(function(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0})(r).toString(16).toUpperCase(),a+="."+((32&t)>>5?"H":"L")+s;let l="";for(let e=n.length;e--;){let t=n[e];(t||l)&&(l="."+t.toString(16).toUpperCase()+l)}a+=l}t=j("hev1"==l?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=j(a,r)||a;break;case"vp09":{let e=Y(r,["vpcC"])[0];if(e&&e.length>6){let t=e[4],i=e[5],r=e[6]>>4&15;a+="."+Q(t)+"."+Q(i)+"."+Q(r)}break}case"av01":{let e=Y(r,["av1C"])[0];if(e&&e.length>2){let i=e[1]>>>5,s=31&e[1],n=e[2]>>>7?"H":"M",l=(64&e[2])>>6,o=(32&e[2])>>5,h=(16&e[2])>>4,d=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2];a+="."+i+"."+Q(s)+n+"."+Q(2===i&&l?o?12:10:l?10:8)+"."+h+"."+d+u+f+"."+Q(1)+"."+Q(1)+"."+Q(1)+".0",t=j("dav1",r)}}}return{codec:a,encrypted:n,supplemental:t}}(Y(r,["mdia","minf","stbl","stsd"])[0]);a?(t[i]={timescale:s,type:a,stsd:l},t[a]=y({timescale:s,id:i},l)):t[i]={timescale:s,type:e,stsd:l}}}}}return Y(e,["moov","mvex","trex"]).forEach(e=>{let i=t[K(e,4)];i&&(i.default={duration:K(e,12),flags:K(e,20)})}),t}function j(e,t){let i=Y(t,["dvvC"]),r=i.length?i[0]:Y(t,["dvcC"])[0];if(r){let t=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return e+"."+Q(t)+"."+Q(i)}}function q(e,t){let i=t+5;for(;128&e[t++]&&t{let i=Y(e,["mdia","minf","stbl","stsd"])[0];if(!i)return;let r=i.subarray(8),s=Y(r,["enca"]),a=s.length>0;a||(s=Y(r,["encv"])),s.forEach(e=>{Y(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{let i=Z(e);i&&t(i,a)})})})}function Z(e){let t=Y(e,["schm"])[0];if(t){let i=$(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=Y(e,["schi","tenc"])[0];if(t)return t}}}function J(e,t){let i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function ee(e,t){let i=[],r=t.samples,s=t.timescale,a=t.id,n=!1;return Y(r,["moof"]).map(l=>{let o=l.byteOffset-8;Y(l,["traf"]).map(l=>{let h=Y(l,["tfdt"]).map(e=>{let t=e[0],i=K(e,4);return 1===t&&(i*=0x100000000,i+=K(e,8)),i/s})[0];return void 0!==h&&(e=h),Y(l,["tfhd"]).map(h=>{let d=K(h,4),u=0xffffff&K(h,0),f=0,c=0,g=8;d===a&&((1&u)!=0&&(g+=8),(2&u)!=0&&(g+=4),(8&u)!=0&&(f=K(h,g),g+=4),(16&u)!=0&&(c=K(h,g),g+=4),(32&u)!=0&&(g+=4),"video"===t.type&&(n=et(t.codec)),Y(l,["trun"]).map(a=>{let l=a[0],h=0xffffff&K(a,0),d=0,u=(256&h)!=0,g=0,m=(512&h)!=0,p=0,E=(1024&h)!=0,y=(2048&h)!=0,v=0,T=K(a,4),S=8;(1&h)!=0&&(d=K(a,S),S+=4),(4&h)!=0&&(S+=4);let A=d+o;for(let o=0;o>1&63;return 39===e||40===e}}(n,r[A])&&ei(r.subarray(A,A+a),n?2:1,e+v/s,i),A+=a,t+=a+4}}e+=g/s}}))})})}),i}function et(e){if(!e)return!1;let t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function ei(e,t,i,r){let s,a=er(e);s=0+t;let n=0,l=0,o=0;for(;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 e=a.length-s,t=s;if(le){R.error(`Malformed SEI payload. ${l} is too small, only ${e} bytes left to parse.`);break}if(4===n){if(181===a[t++]){let e=G(a,t);if(t+=2,49===e){let e=K(a,t);if(t+=4,0x47413934===e){let e=a[t++];if(3===e){let s=a[t++],l=31&s,o=64&s,h=o?2+3*l:0,d=new Uint8Array(h);if(o){d[0]=s;for(let e=1;e16){let e=[];for(let i=0;i<16;i++){let r=a[t++].toString(16);e.push(1==r.length?"0"+r:r),(3===i||5===i||7===i||9===i)&&e.push("-")}let s=l-16,o=new Uint8Array(s);for(let e=0;e/\(Windows.+Firefox\//i.test(navigator.userAgent),ea={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 en(e,t){let i=ea[t];return!!i&&!!i[e.slice(0,4)]}function el(e,t,i=!0){return!e.split(",").some(e=>!eo(e,t,i))}function eo(e,t,i=!0){var r;let s=I(i);return null!=(r=null==s?void 0:s.isTypeSupported(eh(e,t)))&&r}function eh(e,t){return`${t}/mp4;codecs=${e}`}function ed(e){if(e){let t=e.substring(0,4);return ea.video[t]}return 2}function eu(e){let t=es();return e.split(",").reduce((e,i)=>{let r=t&&et(i)?9:ea.video[i];return r?(2*r+e)/(e?3:2):(ea.audio[i]+e)/(e?2:1)},0)}let ef={},ec=/flac|opus|mp4a\.40\.34/i;function eg(e,t=!0){return e.replace(ec,e=>(function(e,t=!0){if(ef[e])return ef[e];let i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let s=0;s4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(ep(e,"audio")||ep(e,"video")))return e;if(t){let i=t.split(",");if(i.length>1){if(e){for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t]}return i[0]}}return t||e}function ep(e,t){return en(e,t)&&eo(e,t)}function eE(e){let t=I(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ey(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}let ev={supported:!1,smooth:!1,powerEfficient:!1},eT={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function eS(e,t){return{supported:!1,configurations:t,decodingInfoResults:[ev],error:e}}function eA(e,t,i,r={}){let s=e.videoCodec;if(!s&&!e.audioCodec||!i)return Promise.resolve(eT);let a=[],n=function(e){var t;let i=null==(t=e.videoCodec)?void 0:t.split(","),r=eL(e),s=e.width||640,a=e.height||480,n=e.frameRate||30,l=e.videoRange.toLowerCase();return i?i.map(e=>{let t={contentType:eh(function(e){if(e.startsWith("av01.")){let t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}(e),"video"),width:s,height:a,bitrate:r,framerate:n};return"sdr"!==l&&(t.transferFunction=l),t}):[]}(e),l=n.length,o=function(e,t,i){var r;let s=null==(r=e.audioCodec)?void 0:r.split(","),a=eL(e);return s&&e.audioGroups?e.audioGroups.reduce((e,r)=>{var n;let l=r?null==(n=t.groups[r])?void 0:n.tracks:null;return l?l.reduce((e,t)=>{if(t.groupId===r){let r=parseFloat(t.channels||"");s.forEach(t=>{let s={contentType:eh(t,"audio"),bitrate:i?function(e,t){if(t<=1)return 1;let i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}(t,a):a};r&&(s.channels=""+r),e.push(s)})}return e},e):e},[]):[]}(e,t,l>0),h=o.length;for(let e=l||+h||1;e--;){let t={type:"media-source"};if(l&&(t.video=n[e%l]),h){t.audio=o[e%h];let i=t.audio.bitrate;t.video&&i&&(t.video.bitrate-=i)}a.push(t)}if(s){let e=navigator.userAgent;if(s.split(",").some(e=>et(e))&&es())return Promise.resolve(eS(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),a))}return Promise.all(a.map(e=>{let t=function(e){let t="",{audio:i,video:r}=e;if(r){let e=ey(r.contentType);t+=`${e}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(i){let e=ey(i.contentType);t+=`${r?"_":""}${e}_c${i.channels}`}return t}(e);return r[t]||(r[t]=i.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:a,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:a,decodingInfoResults:[],error:e}))}function eL(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}let eR=["NONE","TYPE-0","TYPE-1",null],eI=["SDR","PQ","HLG"];var eb={No:"",Yes:"YES",v2:"v2"};function eD(e){let{canSkipUntil:t,canSkipDateRanges:i,age:r}=e;return t&&r!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}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(e){return eP(this._audioGroups,e)}hasSubtitleGroup(e){return eP(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function eP(e,t){return!!t&&!!e&&-1!==e.indexOf(t)}let eC=(e,t)=>JSON.stringify(e,(e=>{let t=new WeakSet;return(i,r)=>{if(e&&(r=e(i,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}})(t));function eO(e,t){R.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function ex(e){return e.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ew(e){if(!e)return e;let{lang:t,assocLang:i,characteristics:r,channels:s,audioCodec:a}=e;return{lang:t,assocLang:i,characteristics:r,channels:s,audioCodec:a}}function eM(e,t,i){if("attrs"in e){let i=t.indexOf(e);if(-1!==i)return i}for(let r=0;r-1===r.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function eN(e,t){let{audioCodec:i,channels:r}=e;return(void 0===i||(t.audioCodec||"").substring(0,4)===i.substring(0,4))&&(void 0===r||r===(t.channels||"2"))}function eU(e,t,i){for(let r=t;r>-1;r--)if(i(e[r]))return r;for(let r=t+1;r{var t;let i,{fragCurrent:r,partCurrent:a,hls:n}=this,{autoLevelEnabled:l,media:o}=n;if(!r||!o)return;let d=performance.now(),u=a?a.stats:r.stats,f=a?a.duration:r.duration,c=d-u.loading.start,g=n.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||m<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!l)return;let E=p>-1&&p!==m,y=!!e||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(c<=Math.max(T,f/(2*S)*1e3))return;let A=v?v.len/S:0,L=u.loading.first?u.loading.first-u.loading.start:-1,R=u.loaded&&L>-1,I=this.getBwEstimate(),b=n.levels,D=b[m],k=Math.max(u.loaded,Math.round(f*(r.bitrate||D.averageBitrate)/8)),_=R?c-L:c;_<1&&R&&(_=Math.min(c,8*u.loaded/I));let P=R?1e3*u.loaded/_:0,C=T/1e3,O=P?(k-u.loaded)/P:8*k/I+C;if(O<=A)return;let x=P?8*P:I,w=(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live)===!0,M=this.hls.config.abrBandWidthUpFactor,F=1/0;for(i=m-1;i>g;i--){let e=b[i].maxBitrate,t=!b[i].details||w;if((F=this.getTimeToLoadFrag(C,x,f*e,t))=O||F>10*f)return;R?this.bwEstimator.sample(c-Math.min(T,L),u.loaded):this.bwEstimator.sampleTTFB(c);let N=b[i].maxBitrate;this.getBwEstimate()*M>N&&this.resetEstimator(N);let U=this.findBestLevel(N,g,i,0,A,1,1);U>-1&&(i=U),this.warn(`Fragment ${r.sn}${a?" part "+a.index:""} of level ${m} is loading too slowly; Fragment duration: ${r.duration.toFixed(3)} Time to underbuffer: ${A.toFixed(3)} s Estimated load time for current fragment: ${O.toFixed(3)} s Estimated load time for down switch fragment: ${F.toFixed(3)} s TTFB estimate: ${0|L} ms Current BW estimate: ${s(I)?0|I:"Unknown"} bps New BW estimate: ${0|this.getBwEstimate()} bps Switching to level ${i} @ ${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 e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${i>0?"and switching down":""} Fragment duration: ${r.duration.toFixed(3)} s Time to underbuffer: ${e.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,i>g){let t=this.findBestLevel(this.hls.levels[g].bitrate,g,i,0,e,1,1);-1===t&&(t=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].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:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new m(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.FRAG_LOADING,this.onFragLoading,this),e.on(h.FRAG_LOADED,this.onFragLoaded,this),e.on(h.FRAG_BUFFERED,this.onFragBuffered,this),e.on(h.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(h.LEVEL_LOADED,this.onLevelLoaded,this),e.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(h.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.FRAG_LOADING,this.onFragLoading,this),e.off(h.FRAG_LOADED,this.onFragLoaded,this),e.off(h.FRAG_BUFFERED,this.onFragBuffered,this),e.off(h.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(h.LEVEL_LOADED,this.onLevelLoaded,this),e.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(h.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(h.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){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(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.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 e=t.frag,{fragCurrent:i,partCurrent:r}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){let t=performance.now(),i=r?r.stats:e.stats,s=t-i.loading.start,a=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&a>-1){let e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,a),i.loaded)}else this.bwEstimator.sampleTTFB(s)}}}}getTimeToLoadFrag(e,t,i,r){let s=r?e+this.lastLevelLoadSec:0;return e+i/t+s}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,a=r.end-r.first;s(a)&&(this.lastLevelLoadSec=a/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===c.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let e=i?i.duration:t.duration,s=this.hls.levels[t.level],a=(s.loaded?s.loaded.bytes:0)+r.loaded,n=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:a,duration:n},s.realBitrate=Math.round(8*a/n)}if(t.bitrateTest){let e={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(h.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:i,part:r}=t,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(e){return e.type!==c.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,r,1,1);if(s>-1)return s;let a=this.hls.firstLevel,n=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${n}`),n}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(-1!==e&&(!t||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){let t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:s,minAutoLevel:a}=i,n=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),o=this.getStarvationDelay(),h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(o){let e=this.findBestLevel(l,a,r,o,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let u=n?Math.min(n,s.maxStarvationDelay):s.maxStarvationDelay;if(!o){let e=this.bitrateTestDelay;e&&(u=(n?Math.min(n,s.maxLoadingDelay):s.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=d=1)}let f=this.findBestLevel(l,a,r,o,u,h,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${o?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let c=i.levels[a],g=i.loadLevelObj;return g&&(null==c?void 0:c.bitrate)0),c=Math.min(c,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter(e=>i.videoRanges[e]>0).length>0&&(f=!0)}c=s(c)?c:0,g=s(g)?g:0;let S=Math.max(1080,c),A=Math.max(30,g);i=Math.max(m=s(m)?m:i,i),f||(t=void 0);let L=n.length>1;return{codecSet:n.reduce((t,r)=>{let s=e[r];if(r===t)return t;if(y=f?T.filter(e=>s.videoRanges[e]>0):[],L){if(s.minBitrate>i)return eO(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return eO(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return eO(r,`audio codec preference "${o}" not found`),t;if(l&&!d){if(!s.channels[l])return eO(r,`no renditions with ${l} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!o||d)&&u&&0===s.channels["2"])return eO(r,"no renditions with stereo sound found"),t;if(s.minHeight>S)return eO(r,`min resolution of ${s.minHeight} > maximum of ${S}`),t;if(s.minFramerate>A)return eO(r,`min framerate of ${s.minFramerate} > maximum of ${A}`),t;if(!y.some(e=>s.videoRanges[e]>0))return eO(r,`no variants with VIDEO-RANGE of ${eC(y)} found`),t;if(h&&r.indexOf(h.substring(0,4))%5!=0)return eO(r,`video codec preference "${h}" not found`),t;if(s.maxScore=eu(t)||s.fragmentError>e[t].fragmentError)?t:(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(t,i+1).reduce((e,t,i)=>{if(!t.codecSet)return e;let r=t.audioGroups,s=e[t.codecSet];s||(e[t.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,t.bitrate);let a=Math.min(t.height,t.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,t.frameRate),s.minIndex=Math.min(s.minIndex,i),s.maxScore=Math.max(s.maxScore,t.score),s.fragmentError+=t.fragmentError,s.videoRanges[t.videoRange]=(s.videoRanges[t.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;let t=D.groups[e];t&&(s.hasDefaultAudio=s.hasDefaultAudio||D.hasDefaultAudio?t.hasDefault:t.hasAutoSelect||!D.hasDefaultAudio&&!D.hasAutoSelectAudio,Object.keys(t.channels).forEach(e=>{s.channels[e]=(s.channels[e]||0)+t.channels[e]}))}),e},{})),L,e,I,b),{codecSet:a,videoRanges:n,minFramerate:l,minBitrate:o,minIndex:h,preferHDR:u}=r;k=h,d=a,L=u?n[n.length-1]:n[0],R=l,e=Math.max(e,o),this.log(`picked start tier ${eC(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>=t;o--){let t,g=p[o],E=o>c;if(!g)continue;if(v.useMediaCapabilities&&!g.supportedResult&&!g.supportedPromise){let t=navigator.mediaCapabilities;"function"==typeof(null==t?void 0:t.decodingInfo)&&function(e,t,i,r,a,n){let l=e.videoCodec,o=e.audioCodec?e.audioGroups:null,h=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,u=d?parseInt(d):h?1/0:2,f=null;if(null!=o&&o.length)try{f=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,i)=>{if(i){let r=t.groups[i];if(!r)throw Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach(t=>{e[t]=(e[t]||0)+r.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==l&&(l.split(",").some(e=>et(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(a,8e6))||!!f&&s(u)&&Object.keys(f).some(e=>parseInt(e)>u)}(g,D,L,R,e,I)?(g.supportedPromise=eA(g,D,t,this.supportedCache),g.supportedPromise.then(e=>{if(!this.hls)return;g.supportedResult=e;let t=this.hls.levels,i=t.indexOf(g);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${eC(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${eC(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${eC(e)}`),i>-1&&t.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):g.supportedResult=eT}if((d&&g.codecSet!==d||L&&g.videoRange!==L||E&&R>g.frameRate||!E&&R>0&&R!1===e.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)||_;t=E?l*e:n*e;let O=_&&r>=2*_&&0===a?g.averageBitrate:g.maxBitrate,x=this.getTimeToLoadFrag(P,t,O*b,void 0===T);if(t>=O&&(o===f||0===g.loadError&&0===g.fragmentError)&&(x<=P||!s(x)||S&&!this.bitrateTestDelay||x${o} adjustedbw(${Math.round(t)})-bitrate=${Math.round(t-O)} ttfb:${P.toFixed(1)} avgDuration:${b.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${A} codecSet:${g.codecSet} videoRange:${g.videoRange} hls.loadLevel:${y}`)),A&&(this.firstSelection=o),o}}return -1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}let eG={search:function(e,t){let i=0,r=e.length-1,s=null,a=null;for(;i<=r;){let n=t(a=e[s=(i+r)/2|0]);if(n>0)i=s+1;else{if(!(n<0))return a;r=s-1}}return null}};function eK(e,t,i=0,r=0,s=.005){let a=null;if(e){a=t[1+e.sn-t[0].sn]||null;let r=e.endDTS-i;r>0&&r<15e-7&&(i+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===eV(i,r,a)||function(e,t,i){if(t&&0===t.start&&t.level0){let r=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),i);return e.start<=r}return!1}(a,e,Math.min(s,r))))return a;let n=eG.search(t,eV.bind(null,i,r));return n&&(n!==e||!a)?n:a}function eV(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;let r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function eH(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let r,s=e.fragments,{fragmentHint:a}=e;return a&&(s=s.concat(a)),eG.search(s,e=>e.cct?-1:(r=e,e.end<=i)?1:e.start>i?-1:0),r||null}return null}function eY(e){switch(e.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 eW(e){return e.details.startsWith("key")}function ej(e){return eW(e)&&!!e.frag&&!e.frag.decryptdata}function eq(e,t){let i=eY(t);return e.default[`${i?"timeout":"error"}Retry`]}function eX(e,t){return Math.min(("linear"===e.backoff?1:Math.pow(2,t))*e.retryDelayMs,e.maxRetryDelayMs)}function eQ(e){return y(y({},e),{errorRetry:null,timeoutRetry:null})}function ez(e,t,i,r){var s;if(!e)return!1;let a=null==r?void 0:r.code,n=t499)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}function eZ(e){return 0===e&&!1===navigator.onLine}var eJ={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},e0={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class e1 extends v{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(h.ERROR,this.onError,this),e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(h.ERROR,this.onError,this),e.off(h.ERROR,this.onErrorOut,this),e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===c.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(e=>r.indexOf(e.groupId)>=0).some(e=>{var i;return null==(i=e.details)?void 0:i.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r,s;if(t.fatal)return;let a=this.hls,n=t.context;switch(t.details){case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case o.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap){t.errorAction=e2();return}case o.FRAG_GAP:case o.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=eJ.SendAlternateToPenaltyBox;return;case o.LEVEL_EMPTY_ERROR:case o.LEVEL_PARSING_ERROR:{let e=t.parent===c.MAIN?t.level:a.loadLevel;t.details===o.LEVEL_EMPTY_ERROR&&null!=(r=t.context)&&null!=(r=r.levelDetails)&&r.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:"number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,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 e=a.loadLevelObj;e&&(n.type===f.AUDIO_TRACK&&e.hasAudioGroup(n.groupId)||n.type===f.SUBTITLE_TRACK&&e.hasSubtitleGroup(n.groupId))&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.loadLevel),t.errorAction.action=eJ.SendAlternateToPenaltyBox,t.errorAction.flags=e0.MoveAllAlternatesMatchingHost)}return;case o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:eJ.SendAlternateToPenaltyBox,flags:e0.MoveAllAlternatesMatchingHDCP};return;case o.KEY_SYSTEM_SESSION_UPDATE_FAILED:case o.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case o.KEY_SYSTEM_NO_SESSION:t.errorAction={action:eJ.SendAlternateToPenaltyBox,flags:e0.MoveAllAlternatesMatchingKey};return;case o.BUFFER_ADD_CODEC_ERROR:case o.REMUX_ALLOC_ERROR:case o.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(s=t.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:t.errorAction=e2();return}t.type===l.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=e2())}getPlaylistRetryOrSwitchAction(e,t){let i=eq(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(ez(i,r,eY(e),e.response))return{action:eJ.RetryRequest,flags:e0.None,retryConfig:i,retryCount:r};let s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:a}=t.config,n=eq(eW(e)?a:s,e),l=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(r&&(e.details!==o.FRAG_GAP&&r.fragmentError++,!ej(e))&&ez(n,l,eY(e),e.response))return{action:eJ.RetryRequest,flags:e0.None,retryConfig:n,retryCount:l};let h=this.getLevelSwitchAction(e,i);return n&&(h.retryConfig=n,h.retryCount=l),h}getLevelSwitchAction(e,t){let i=this.hls;null==t&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var s,a,n,l;let t=e.details;r.loadError++,t===o.BUFFER_APPEND_ERROR&&r.fragmentError++;let h=-1,{levels:d,loadLevel:u,minAutoLevel:g,maxAutoLevel:m}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);let p=null==(s=e.frag)?void 0:s.type,E=(p===c.AUDIO&&t===o.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===o.BUFFER_ADD_CODEC_ERROR||t===o.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:e})=>r.audioCodec!==e),y="video"===e.sourceBufferName&&(t===o.BUFFER_ADD_CODEC_ERROR||t===o.BUFFER_APPEND_ERROR)&&d.some(({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t),{type:v,groupId:T}=null!=(a=e.context)?a:{};for(let i=d.length;i--;){let s=(i+u)%d.length;if(s!==u&&s>=g&&s<=m&&0===d[s].loadError){let i=d[s];if(t===o.FRAG_GAP&&p===c.MAIN&&e.frag){let t=d[s].details;if(t){let i=eK(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else if(v===f.AUDIO_TRACK&&i.hasAudioGroup(T)||v===f.SUBTITLE_TRACK&&i.hasSubtitleGroup(T))continue;else if(p===c.AUDIO&&null!=(n=r.audioGroups)&&n.some(e=>i.hasAudioGroup(e))||p===c.SUBTITLE&&null!=(l=r.subtitleGroups)&&l.some(e=>i.hasSubtitleGroup(e))||E&&r.audioCodec===i.audioCodec||y&&r.codecSet===i.codecSet||!E&&r.codecSet!==i.codecSet)continue;h=s;break}}if(h>-1&&i.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:eJ.SendAlternateToPenaltyBox,flags:e0.None,nextAutoLevel:h}}return{action:eJ.SendAlternateToPenaltyBox,flags:e0.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case eJ.DoNothing:break;case eJ.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===o.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0;case eJ.RetryRequest:}if(t.fatal)return void this.hls.stopLoad()}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r}=i,s=i.nextAutoLevel;switch(r){case e0.None:this.switchLevel(e,s);break;case e0.MoveAllAlternatesMatchingHDCP:{let r=this.getVariantLevelIndex(e.frag),s=t.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){t.maxHdcpLevel=eR[eR.indexOf(a)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case e0.MoveAllAlternatesMatchingKey:{let t=e.decryptdata;if(t){let r=this.hls.levels,s=r.length;for(let i=s;i--;)if(this.variantHasKey(r[i],t)){var a,n;this.log(`Banned key found in level ${i} (${r[i].bitrate}bps) or audio group "${null==(a=r[i].audioGroups)?void 0:a.join(",")}" (${null==(n=e.frag)?void 0:n.type} fragment) ${k(t.keyId||[])}`),r[i].fragmentError++,r[i].loadError++,this.log(`Removing level ${i} with key error (${e.error})`),this.hls.removeLevel(i)}let l=e.frag;if(this.hls.levels.length{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[e];if(l){if(0===l.time.length)return void this.removeFragment(n.body);l.time.some(e=>{let i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(n.body),i})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;let i=e.frag,r=e8(i),s=this.fragments[r];if(!s||s.buffered&&i.gap)return;let a=!i.relurl;Object.keys(t).forEach(r=>{let n=i.elementaryStreams[r];if(!n)return;let l=t[r],o=a||!0===n.partial;s.range[r]=this.getBufferedTimes(i,e.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),e5(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=e6(i,t=>t.fragment.sn>=e))}fragBuffered(e,t){let i=e8(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){let s={time:[],partial:i},a=e.start,n=e.end,l=e.minEndPTS||n,o=e.maxStartPTS||a;for(let e=0;e=t&&l<=i){s.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(n,r.end(e))});break}if(at){let t=Math.max(a,r.start(e)),i=Math.min(n,r.end(e));i>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:i}))}else if(n<=t)break}return s}getPartialFragment(e){let t,i,r,s=null,a=0,{bufferPadding:n,fragments:l}=this;return Object.keys(l).forEach(o=>{let h=l[o];h&&e5(h)&&(i=h.body.start-n,r=h.body.end+n,e>=i&&e<=r&&a<=(t=Math.min(e-i,r-e))&&(s=h.body,a=t))}),s}isEndListAppended(e){let t=this.endListFragments[e];return void 0!==t&&(t.buffered||e5(t))}getState(e){let t=e8(e),i=this.fragments[t];if(i)if(!i.buffered)return e3.APPENDING;else if(e5(i))return e3.PARTIAL;else return e3.OK;return e3.NOT_LOADED}isTimeBuffered(e,t,i){let r,s;for(let a=0;a=r&&t<=s)return!0;if(t<=r)break}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;let i=t.frag,r=t.part?null:t,s=e8(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:s,type:a}=t;if("initSegment"===i.sn)return;let n=i.type;if(r){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(r)}this.timeRanges=s;let l=s[a];this.detectEvictedFragments(a,l,n,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=e8(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){let s=t[i[r]];if((null==s?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!!(null!=(t=this.activePartLists[e])&&t.length)}removeFragmentsInRange(e,t,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.starte&&(n.buffered||s)&&this.removeFragment(l)})}removeFragment(e){let t=e8(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let t=e.sn;this.activePartLists[e.type]=e6(i,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function e5(e){var t,i,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(r=e.range.audiovideo)&&r.partial)}function e8(e){return`${e.type}_${e.level}_${e.sn}`}function e6(e,t){return e.filter(e=>{let i=t(e);return i||e.clearElementaryStreamInfo(),i})}var e9={cbc:0,ctr:1};class e7{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case e9.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case e9.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class te{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()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){let e=this.sBox,t=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],u=l[3],f=new Uint32Array(256),c=0,g=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[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,e[c]=i,t[i]=c;let l=f[c],m=f[l],p=f[m],E=257*f[i]^0x1010100*i;r[c]=E<<24|E>>>8,s[c]=E<<16|E>>>16,a[c]=E<<8|E>>>24,n[c]=E,E=0x1010101*p^65537*m^257*l^0x1010100*c,o[i]=E<<24|E>>>8,h[i]=E<<16|E>>>16,d[i]=E<<8|E>>>24,u[i]=E,c?(c=l^f[f[f[p^l]]],g^=f[f[g]]):c=g=1}}expandKey(e){let t,i,r,s,a=this.uint8ArrayToUint32Array_(e),n=!0,l=0;for(;l{let n=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(n,t,i,r);let l=this.flush();l?s(l.buffer):a(Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){let{currentIV:s,currentResult:a,remainderData:n}=this;if(r!==e9.cbc||16!==t.byteLength)return R.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),n&&(e=J(n,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;s&&(i=s);let o=this.softwareDecrypter;return(o||(o=this.softwareDecrypter=new te),o.expandKey(t),this.currentResult=o.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,a)?a:null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new tt(this.subtle,t,r)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new e7(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(Error("web crypto not initialized"))).catch(s=>(R.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i,r)))}onWebCryptoError(e,t,i,r){let s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);let s=this.flush();if(s)return s.buffer}throw Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(R.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}class tr{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){let i=e.url;if(!i)return Promise.reject(new tn({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${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(),e.gap)if(e.tagList.some(e=>"GAP"===e[0]))return void h(ta(e));else e.gap=!1;let d=this.loader=s?new s(r):new a(r),u=ts(e);e.loader=d;let f=eQ(r.fragLoadPolicy.default),c={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:131072};e.stats=d.stats;let g={onSuccess:(t,i,r,s)=>{this.resetLoader(e,d);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),n({frag:e,part:null,payload:a,networkDetails:s})},onError:(t,r,s,a)=>{this.resetLoader(e,d),h(new tn({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:y({url:i,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:a}))},onAbort:(t,i,r)=>{this.resetLoader(e,d),h(new tn({type:l.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,d),h(new tn({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:t}))}};t&&(g.onProgress=(i,r,s,a)=>t({frag:e,part:null,payload:s,networkDetails:a})),d.load(u,c,g)})}loadPart(e,t,i){this.abort();let r=this.config,s=r.fLoader,a=r.loader;return new Promise((n,h)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void h(ta(e,t));let d=this.loader=s?new s(r):new a(r),u=ts(e,t);e.loader=d;let f=eQ(r.fragLoadPolicy.default),c={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:131072};t.stats=d.stats,d.load(u,c,{onSuccess:(r,s,a,l)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let o={frag:e,part:t,payload:r.data,networkDetails:l};i(o),n(o)},onError:(i,r,s,a)=>{this.resetLoader(e,d),h(new tn({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:y({url:u.url,data:void 0},i),error:Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:a}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),h(new tn({type:l.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,d),h(new tn({type:l.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${c.timeout}ms`),networkDetails:s,stats:i}))}})})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){let r=Math.round(e.duration/t.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(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function ts(e,t=null){let i=t||e,r={frag:e,part:t,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 t=a,i=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(l=e.decryptdata)?void 0:l.method)||"AES-256"===o)){let e=n-a;e%16&&(i=n+(16-e%16)),0!==a&&(r.resetIV=!0,t=a-16)}r.rangeStart=t,r.rangeEnd=i}return r}function ta(e,t){let i=Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:l.MEDIA_ERROR,details:o.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new tn(r)}class tn extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class tl extends v{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!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(){}}class to{constructor(e,t,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=th(),this.buffering={audio:th(),video:th(),audiovideo:th()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=a}}function th(){return{start:0,executeStart:0,executeEnd:0,end:0}}let td={length:0,start:()=>0,end:()=>0};class tu{static isBuffered(e,t){if(e){let i=tu.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){let t=tu.getBuffered(e);return tu.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let s=-1,a=[];if(i)for(let r=0;r=e[r].start&&t<=e[r].end&&(s=r);let n=a.length;if(n){let t=a[n-1].end;e[r].start-tt&&(a[n-1].end=e[r].end):a.push(e[r])}else a.push(e[r])}else a=e;let n=0,l=t,o=t;for(let e=0;e=h&&t<=d&&(s=e),t+i>=h&&t{let r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s})}return t}function tg(e,t,i){let r,s,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{let e=new self.URL(i).searchParams;if(e.has(r))s=e.get(r);else throw Error(`"${r}" does not match any query parameter in URI: "${i}"`)}catch(t){e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in a?e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):a[r]=s||""}let tm=/^(\d+)x(\d+)$/,tp=/(.+?)=(".*?"|.*?)(?:,|$)/g;class tE{constructor(e,t){"string"==typeof e&&(e=tE.parseAttrList(e,t)),p(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2),i=new Uint8Array((t=(1&t.length?"0":"")+t).length/2);for(let e=0;eNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){let t=tm.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,r={};for(tp.lastIndex=0;null!==(i=tp.exec(e));){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(t&&(n||l))a=tc(t,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":R.warn(`${e}: attribute ${s} is missing quotes`)}r[s]=a}return r}}class ty{constructor(e,t,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==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:i,t){let i=t.attr;for(let t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){R.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=p(new tE({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);s(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return null===e||null===e.programDateTime?(R.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(s(e))return e}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)}}class tv{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.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=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&s(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.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 e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function tT(e,t){return e.length===t.length&&!e.some((e,i)=>e!==t[i])}function tS(e,t){return!e&&!t||!!e&&!!t&&tT(e,t)}function tA(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function tL(e){switch(e){case"AES-128":case"AES-256":return e9.cbc;case"AES-256-CTR":return e9.ctr;default:throw Error(`invalid full segment method ${e}`)}}function tR(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function tI(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function tb(e){let t=function(e,t,i){let r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function tD(e){let t=e.split(":"),i=null;if("data"===t[0]&&2===t.length){let e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){let t="base64"===r[0],s=r[1];t?(e.splice(-1,1),i=tR(s)):i=function(e){let t=tI(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(s)}}return i}let tk="undefined"!=typeof self?self:void 0;var t_={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},tP={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function tC(e){switch(e){case tP.FAIRPLAY:return t_.FAIRPLAY;case tP.PLAYREADY:return t_.PLAYREADY;case tP.WIDEVINE:return t_.WIDEVINE;case tP.CLEARKEY:return t_.CLEARKEY}}function tO(e){switch(e){case t_.FAIRPLAY:return tP.FAIRPLAY;case t_.PLAYREADY:return tP.PLAYREADY;case t_.WIDEVINE:return tP.WIDEVINE;case t_.CLEARKEY:return tP.CLEARKEY}}function tx(e){let{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[t_.FAIRPLAY,t_.WIDEVINE,t_.PLAYREADY,t_.CLEARKEY].filter(e=>!!t[e]):[];return!r[t_.WIDEVINE]&&i&&r.push(t_.WIDEVINE),r}let tw=function(e){return null!=tk&&null!=(e=tk.navigator)&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function tM(e){let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){let e=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(e){let t=tR(e).subarray(0,16);return tb(t),t}}return null}let tF={};class tN{static clearKeyUriToKeyIdMap(){tF={}}static setKeyIdForUri(e,t){tF[e]=t}constructor(e,t,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=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!tA(e),null!=a&&a.startsWith("0x")&&(this.keyId=new Uint8Array(_(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&tT(e.keyFormatVersions,this.keyFormatVersions)&&tS(e.iv,this.iv)&&tS(e.keyId,this.keyId)}isSupported(){if(this.method){if(tA(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case tP.FAIRPLAY:case tP.WIDEVINE:case tP.PLAYREADY:case tP.CLEARKEY:return -1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(tA(this.method)){let t=this.iv;return t||("number"!=typeof e&&(R.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e)),new tN(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){let e=tF[this.uri];if(e&&!tT(this.keyId,e)&&tN.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let i=tD(this.uri);if(i)switch(this.keyFormat){case tP.WIDEVINE:if(this.pssh=i,!this.keyId){let e=function(e){let t=[];if(e instanceof ArrayBuffer){let i=e.byteLength,r=0;for(;r+32>>24;if(0!==s&&1!==s)return{offset:i,size:t};let a=e.buffer,n=k(new Uint8Array(a,i+12,16)),l=null,o=0;if(0===s)o=28;else{let s=e.getUint32(28);if(!s||r<32+16*s)return{offset:i,size:t};l=[];for(let e=0;e0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){let i=t.length,r=8,s=i;for(;s--;)r+=t[s].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=255&r,a.set(e,4),s=0,r=8;s0&&a.length({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:a.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(t$.lastIndex=0;null!==(r=t$.exec(e));){let e=new tE(r[1],i),a=e.TYPE;if(a){let i=n[a],r=s[a]||[];s[a]=r;let o=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],d=e.CHANNELS,u=e.CHARACTERISTICS,f=e["INSTREAM-ID"],c={attrs:e,bitrate:0,id:l++,groupId:e["GROUP-ID"]||"",name:e.NAME||o||"",type:a,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:o,url:e.URI?tH.resolve(e.URI,t):""};if(h&&(c.assocLang=h),d&&(c.channels=d),u&&(c.characteristics=u),f&&(c.instreamId=f),null!=i&&i.length){let e=tH.findGroup(i,c.groupId)||i[0];tX(c,e,"audioCodec"),tX(c,e,"textCodec")}r.push(c)}}return s}static parseLevelPlaylist(e,t,i,r,a,n){var l;let o,h,d,u,f={url:t},c=new tv(t),g=c.fragments,m=[],E=null,y=0,v=0,T=0,S=0,A=0,L=null,I=new F(r,f),b=-1,D=!1,k=null;if(tK.lastIndex=0,c.m3u8=e,c.hasVariableRefs=tf.test(e),(null==(l=tK.exec(e))?void 0:l[0])!=="#EXTM3U")return c.playlistParsingError=Error("Missing format identifier #EXTM3U"),c;for(;null!==(o=tK.exec(e));){D&&(D=!1,(I=new F(r,f)).playlistOffset=T,I.setStart(T),I.sn=y,I.cc=S,A&&(I.bitrate=A),I.level=i,E&&(I.initSegment=E,E.rawProgramDateTime&&(I.rawProgramDateTime=E.rawProgramDateTime,E.rawProgramDateTime=null),k&&(I.setByteRange(k),k=null)));let e=o[1];if(e){I.duration=parseFloat(e);let t=(" "+o[2]).slice(1);I.title=t||null,I.tagList.push(t?["INF",e,t]:["INF",e])}else if(o[3]){if(s(I.duration)){I.playlistOffset=T,I.setStart(T),d&&tZ(I,d,c),I.sn=y,I.level=i,I.cc=S,g.push(I);let e=(" "+o[3]).slice(1);I.relurl=tc(c,e),tQ(I,L,m),L=I,T+=I.duration,y++,v=0,D=!0}}else{if(!(o=o[0].match(tV))){R.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h0&&t0(c,e,o),y=c.startSN=parseInt(a);break;case"SKIP":{c.skippedSegments&&tJ(c,e,o);let t=new tE(a,c),i=t.decimalInteger("SKIPPED-SEGMENTS");if(s(i)){c.skippedSegments+=i;for(let e=i;e--;)g.push(null);y+=i}let r=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(r.split(" ")));break}case"TARGETDURATION":0!==c.targetduration&&tJ(c,e,o),c.targetduration=Math.max(parseInt(a),1);break;case"VERSION":null!==c.version&&tJ(c,e,o),c.version=parseInt(a);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||tJ(c,e,o),c.live=!1;break;case"#":(a||l)&&I.tagList.push(l?[a,l]:[a]);break;case"DISCONTINUITY":S++,I.tagList.push(["DIS"]);break;case"GAP":I.gap=!0,I.tagList.push([e]);break;case"BITRATE":I.tagList.push([e,a]),s(A=1e3*parseInt(a))?I.bitrate=A:A=0;break;case"DATERANGE":{let e=new tE(a,c),t=new ty(e,c.dateRanges[e.ID],c.dateRangeTagCount);c.dateRangeTagCount++,t.isValid||c.skippedSegments?c.dateRanges[t.id]=t:R.warn(`Ignoring invalid DATERANGE tag: "${a}"`),I.tagList.push(["EXT-X-DATERANGE",a]);break}case"DEFINE":{let e=new tE(a,c);"IMPORT"in e?function(e,t,i){let r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}(c,e,n):tg(c,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==c.startCC?tJ(c,e,o):g.length>0&&t0(c,e,o),c.startCC=S=parseInt(a);break;case"KEY":{let e=tW(a,t,c);if(e.isSupported()){if("NONE"===e.method){d=void 0;break}d||(d={});let t=d[e.keyFormat];null!=t&&t.matches(e)||(t&&(d=p({},d)),d[e.keyFormat]=e)}else R.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${a}"`);break}case"START":c.startTimeOffset=tj(a);break;case"MAP":{let e=new tE(a,c);if(I.duration){let t=new F(r,f);tz(t,e,i,d),E=t,I.initSegment=E,E.rawProgramDateTime&&!I.rawProgramDateTime&&(I.rawProgramDateTime=E.rawProgramDateTime)}else{let t=I.byteRangeEndOffset;if(t){let e=I.byteRangeStartOffset;k=`${t-e}@${e}`}else k=null;tz(I,e,i,d),E=I,D=!0}E.cc=S;break}case"SERVER-CONTROL":u&&tJ(c,e,o),c.canBlockReload=(u=new tE(a)).bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=u.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&u.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=u.optionalFloat("PART-HOLD-BACK",0),c.holdBack=u.optionalFloat("HOLD-BACK",0);break;case"PART-INF":c.partTarget&&tJ(c,e,o),c.partTarget=new tE(a).decimalFloatingPoint("PART-TARGET");break;case"PART":{let e=c.partList;e||(e=c.partList=[]);let t=v>0?e[e.length-1]:void 0,i=v++,r=new N(new tE(a,c),I,f,i,t);e.push(r),I.duration+=r.duration;break}case"PRELOAD-HINT":{let e=new tE(a,c);c.preloadHint=e;break}case"RENDITION-REPORT":{let e=new tE(a,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(e);break}default:R.warn(`line parsed but not handled: ${o}`)}}}L&&!L.relurl?(g.pop(),T-=L.duration,c.partList&&(c.fragmentHint=L)):c.partList&&(tQ(I,L,m),I.cc=S,c.fragmentHint=I,d&&tZ(I,d,c)),c.targetduration||(c.playlistParsingError=Error("Missing Target Duration"));let _=g.length,P=g[0],C=g[_-1];if((T+=c.skippedSegments*c.targetduration)>0&&_&&C){c.averagetargetduration=T/_;let e=C.sn;c.endSN="initSegment"!==e?e:0,c.live||(C.endList=!0),b>0&&(function(e,t){let i=e[t];for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(g,b),P&&m.unshift(P))}return c.fragmentHint&&(T+=c.fragmentHint.duration),c.totalduration=T,m.length&&c.dateRangeTagCount&&P&&tY(m,c),c.endCC=S,c}}function tY(e,t){let i=e.length;if(!i)if(!t.hasProgramDateTime)return;else{let r=t.fragments[t.fragments.length-1];e.push(r),i++}let r=e[i-1],s=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let l=a.length;l--;){let o=t.dateRanges[a[l]],h=o.startDate.getTime();o.tagAnchor=r.ref;for(let r=i;r--;){var n;if((null==(n=e[r])?void 0:n.sn)=l||0===r){var n;if(t<=l+1e3*(((null==(n=i[r+1])?void 0:n.start)||s)-a.start)){let s=i[r].sn-e.startSN;if(s<0)return -1;let a=e.fragments;if(a.length>i.length){let n=(i[r+1]||a[a.length-1]).sn-e.startSN;for(let e=n;e>s;e--){let i=a[e].programDateTime;if(t>=i&&te);["video","audio","text"].forEach(e=>{let r=i.filter(t=>en(t,e));r.length&&(t[`${e}Codec`]=r.map(e=>e.split("/")[0]).join(","),i=i.filter(e=>-1===r.indexOf(e)))}),t.unknownCodecs=i}function tX(e,t,i){let r=t[i];r&&(e[i]=r)}function tQ(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function tz(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function tZ(e,t,i){e.levelkeys=t;let{encryptedFragments:r}=i;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}function tJ(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function t0(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function t1(e,t){let i=t.startPTS;if(s(i)){let r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&r.setDuration(s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function t2(e,t,i,r,a,n,l){let o;r-i<=0&&(l.warn("Fragment should have a positive duration",t),r=i+t.duration,n=a+t.duration);let h=i,d=r,u=t.startPTS,f=t.endPTS;if(s(u)){let o=Math.abs(u-i);e&&o>e.totalduration?l.warn(`media timestamps and playlist times differ by ${o}s for level ${t.level} ${e.url}`):s(t.deltaPTS)?t.deltaPTS=Math.max(o,t.deltaPTS):t.deltaPTS=o,h=Math.max(i,u),i=Math.min(i,u),a=void 0!==t.startDTS?Math.min(a,t.startDTS):a,d=Math.min(r,f),r=Math.max(r,f),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}let c=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=h,t.startDTS=a,t.endPTS=r,t.minEndPTS=d,t.endDTS=n;let g=t.sn;if(!e||ge.endSN)return 0;let m=g-e.startSN,p=e.fragments;for(p[m]=t,o=m;o>0;o--)t1(p[o],p[o-1]);for(o=m;o=0,n=0;if(a&&rt){let e=1e3*r[r.length-1].duration;e{var i;null==(i=e.details)||i.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function it(e){return e.replace(/\?[^?]*$/,"")}function ii(e,t){for(let r=0,s=e.length;rt.startCC))&&1)return;let i=Math.min(t.endCC,e.endCC),r=ii(t.fragments,i),s=ii(e.fragments,i);r&&s&&(R.log(`Aligning playlist at start of dicontinuity sequence ${i}`),is(r.start-s.start,e))}function il(e,t){let i,r;if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let s=e.fragments,a=t.fragments;if(!s.length||!a.length)return;let n=Math.min(t.endCC,e.endCC);t.startCC{let{config:e,fragCurrent:t,media:i,mediaBuffer:r,state:a}=this,n=i?i.currentTime:0,l=tu.bufferInfo(r||i,n,e.maxBufferHole),o=!l.len;if(this.log(`Media seeking to ${s(n)?n.toFixed(3):n}, state: ${a}, ${o?"out of":"in"} buffer`),this.state===iu.ENDED)this.resetLoadingState();else if(t){let i=e.maxFragLookUpTolerance,r=t.start-i,s=t.start+t.duration+i;if(o||sl.end){let e=n>s;(nthis.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts)){let e=Math.max(l.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}!this.hls.hasEnoughToStart&&(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===iu.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=a,this.hls=e,this.fragmentLoader=new tr(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ti(e.config)}registerListeners(){let{hls:e}=this;e.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(h.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===iu.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=iu.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return -1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;let s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=tu.bufferedInfo(s,e.start,0));let a=e.nextStart;if(a&&a>r&&a{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(e)};this._doFragLoad(e,t,i,r).then(e=>{if(!e)return;let t=this.state,i=e.frag;if(this.fragContextChanged(i)){t!==iu.FRAG_LOADING&&(this.fragCurrent||t!==iu.PARSING)||(this.fragmentTracker.removeFragment(i),this.state=iu.IDLE);return}"payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(h.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state!==iu.STOPPED&&this.state!==iu.ERROR&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===e3.APPENDING){let t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?e.sn-a.sn:0)||this.reduceMaxBufferLength(s,e.duration))&&i.removeFragment(e)}else(null==(t=this.mediaBuffer)?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===e3.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){e-t&&this.hls.trigger(h.BUFFER_FLUSHING,{startOffset:e,endOffset:t,type:i})}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{let t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw Error("init load aborted");return e}).then(e=>{let{hls:t}=this,{frag:i,payload:r}=e,s=i.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&tA(s.method)){let a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,tL(s.method)).catch(e=>{throw t.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(r=>{let s=self.performance.now();return t.trigger(h.FRAG_DECRYPTED,{frag:i,payload:r,stats:{tstart:a,tdecrypt:s}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==iu.STOPPED&&this.state!==iu.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw Error("init load aborted, missing levels");let i=e.frag.stats;this.state!==iu.STOPPED&&(this.state=iu.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,r;let s=e.tracks;if(s&&!t.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,i=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(i.message),!!e&&!e.mediaKeys&&(this.hls.trigger(h.ERROR,{type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?id.toString(tu.getBuffered(i)):"(detached)"})`),M(e)){var r;if(e.type!==c.SUBTITLE){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=iu.IDLE;return}}let t=null==(r=this.levels)?void 0:r[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=iu.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:s}=e,a=!s||0===s.length||s.some(e=>!e),n=new to(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(n)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var a,n;let l;this.fragCurrent=e;let o=t.details;if(!this.levels||!o)throw Error(`frag load aborted, missing level${o?"":" detail"}s`);let d=null;if(e.encrypted&&!(null!=(a=e.decryptdata)&&a.key)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=iu.KEY_LOADING,this.fragCurrent=e,d=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(h.KEY_LOADED,e),this.state===iu.KEY_LOADING&&(this.state=iu.IDLE),e}),this.hls.trigger(h.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else!e.encrypted&&(d=this.keyLoader.loadClear(e,o.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");let u=this.fragPrevious;if(M(e)&&(!u||e.sn!==u.sn)){let i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==u?void 0:u.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&M(e)){let s=o.partList;if(s&&r){i>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);let a=this.getNextPart(s,e,i);if(a>-1){let n,l=s[a];return(e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${a}/${s.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=iu.FRAG_LOADING,n=d?d.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,r)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,r).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(h.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts")):n}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}if(M(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(n=o.partList)?void 0:n.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),s(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=iu.FRAG_LOADING;let f=this.config.progressive;return(l=f&&d?d.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,r)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,f?r:void 0),d]).then(([e])=>(!f&&r&&r(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(h.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,i,r){return new Promise((s,a)=>{var n;let l=[],o=null==(n=i.details)?void 0:n.partList,d=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{l[t.index]=r;let a=r.part;this.hls.trigger(h.FRAG_LOADED,r);let n=t9(i.details,e.sn,t.index+1)||t7(o,e.sn,t.index+1);if(!n)return s({frag:e,part:a,partsLoaded:l});d(n)}).catch(a)};d(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===o.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===l.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(h.ERROR,t)}else this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==iu.PARSING){this.fragCurrent||this.state===iu.STOPPED||this.state===iu.ERROR||(this.state=iu.IDLE);return}let{frag:i,part:r,level:s}=t,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 ${l?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(i,r,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i,r;let s=e.partList[0];if(s.fragment.type===c.SUBTITLE)return!1;if(t>=s.end+((null==(i=e.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(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:a}=e;if(!(null!=t&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let n=t[r],l=n.details,o=a>-1?t9(l,s,a):null,h=o?o.fragment:t6(l,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:o,level:n}):null}bufferFragmentData(e,t,i,r,s){if(this.state!==iu.PARSING)return;let{data1:a,data2:n}=e,l=a;if(n&&(l=J(a,n)),!l.length)return;let o=this.initPTS[t.cc],d=o?-o.baseTime/o.timescale:void 0,u={type:e.type,frag:t,part:i,chunkMeta:r,offset:d,parent:t.type,data:l};if(this.hls.trigger(h.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!tu.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);let i=t.currentTime,r=tu.bufferInfo(t,i,0),s=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),n=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-n>a&&this.flushMainBuffer(n,e.start)}getFwdBufferInfo(e,t){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(e,r,t,a)}getFwdBufferInfoAtPos(e,t,i,r){let s=tu.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(s.nextStart<=a.end||a.gap)){let i=Math.max(Math.min(s.nextStart,a.end)-t,r);return tu.bufferInfo(e,t,i)}}return s}getMaxBufferLength(e){let{config:t}=this;return Math.min(e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(e,t=c.MAIN){let i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:s}=this,a=i[0].start,n=s.lowLatencyMode&&!!t.partList,l=null;if(t.live){let i=s.initialLiveManifestSize;if(r=a?i:r)||l.start:e;this.log(`Setting startPosition to ${s} to match start frag at live edge. mainStart: ${i} liveSyncPosition: ${r} frag.start: ${null==(o=l)?void 0:o.start}`),this.startPosition=this.nextLoadPosition=s}}else e<=a&&(l=i[0]);if(!l){let i=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,i,t)}let h=this.filterReplacedPrimary(l,t);if(!h&&l){let e=l.sn-t.startSN;h=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){let i=this.fragmentTracker.getState(e);return(i===e3.OK||i===e3.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,s){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&i.nextStart){let e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==e&&i.len+e.len>=s){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(ig(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(ig(this.config)&&e.type!==c.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(e.start-r.start)>1||0===r.start)return null}else if(e.end<=r.start&&(null==t?void 0:t.live)===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let s=null==i?void 0:i.playerQueue;if(s)for(let t=s.length;t--;){let i=s[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let r=-1,s=!1,a=!0;for(let n=0,l=e.length;n-1&&ii.start)return!0;return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!s(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let r=0;re}(t,i,s))return s}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){let a=t[s-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}!r&&(r=eH(e,i.cc,i.end))&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`)}}else{let t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){let r,{config:s}=this,{fragPrevious:a}=this,{fragments:n,endSN:l}=i,{fragmentHint:o}=i,{maxFragLookUpTolerance:h}=s,d=i.partList,u=!!(this.loadingParts&&null!=d&&d.length&&o);if(u&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),l=o.sn),et-h||null!=(f=this.media)&&f.paused||!this.startFragRequested?0:h;r=eK(a,n,e,i)}else r=n[n.length-1];if(r){let e=r.sn-i.startSN,t=this.fragmentTracker.getState(r);if((t===e3.OK||t===e3.PARTIAL&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!u||d[0].fragment.sn>r.sn||!i.live)&&r.level===a.level){let t=n[e+1];r=r.sn${e.startSN} fragments: ${r}`),s}return a}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&M(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===iu.FRAG_LOADING_WAITING_RETRY)||(this.state=iu.IDLE)}onFragmentOrKeyLoadError(e,t){var i,r,s;if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let a=t.frag;if(!a||a.type!==e||!this.levels)return;if(this.fragContextChanged(a))return void this.warn(`Frag load error must match current frag to retry ${a.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);let n=t.details===o.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(a,!0);let l=t.errorAction;if(!l){this.state=iu.ERROR;return}let{action:h,flags:d,retryCount:u=0,retryConfig:f}=l,c=!!f,g=c&&h===eJ.RetryRequest,m=c&&!l.resolved&&d===e0.MoveAllAlternatesMatchingHost,p=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!g&&m&&M(a)&&!a.endList&&p&&!ej(t))this.resetFragmentErrors(e),this.treatAsGap(a),l.resolved=!0;else if((g||m)&&u=t||i&&!eZ(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=iu.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===iu.PARSING||this.state===iu.PARSED){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);let a=!s;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===c.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==iu.STOPPED&&(this.state=iu.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;let r=tu.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===iu.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==iu.STOPPED&&(this.state=iu.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){let s=i.details;if(!s)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((t,a)=>{let n=e.elementaryStreams[a];if(n){let l=n.endPTS-n.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${e.sn} ${a} duration reliably (${l})`),t||!1;let o=r?0:t2(s,e,n.startPTS,n.endPTS,n.startDTS,n.endDTS,this);return this.hls.trigger(h.LEVEL_PTS_UPDATED,{details:s,level:i,drift:o,type:a,frag:e,start:n.startPTS,end:n.endPTS}),!0}return t},!1)){var a;if(0===i.fragmentError&&this.treatAsGap(e,i),(null==(a=this.transmuxer)?void 0:a.error)===null){let t=Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=iu.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(h.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===c.MAIN?"level":"track"}fragInfo(e,t=!0,i){var r,s;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN).toFixed(3)}-${(null!=(s=t&&!i?e.endPTS:(i||e).end)?s:NaN).toFixed(3)}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function ig(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class im{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let e,{chunks:t,dataLength:i}=this;return t.length?(e=1===t.length?t[0]:function(e,t){let i=new Uint8Array(t),r=0;for(let t=0;t0)return e.subarray(i,i+r)}function iR(e,t){return 255===e[t]&&(246&e[t+1])==240}function iI(e,t){return 1&e[t+1]?7:9}function ib(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function iD(e,t){return t+1>2&15;if(a>12){let t=Error(`invalid ADTS sampling index:${a}`);e.emit(h.ERROR,h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let n=(s>>6&3)+1,d=t[i+3]>>6&3|(1&s)<<2,u="mp4a.40."+n,f=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],c=a;(5===n||29===n)&&(c-=3);let g=[n<<3|(14&c)>>1,(1&c)<<7|d<<3];return R.log(`manifest codec:${r}, parsed codec:${u}, channels:${d}, rate:${f} (ADTS object type:${n} sampling index:${a})`),{config:g,samplerate:f,channelCount:d,codec:u,parsedCodec:u,manifestCodec:r}}(t,i,r,s);a&&p(e,a)}}function i_(e,t,i,r,s){let a,n=r+s*(9216e4/e.samplerate),l=function(e,t){let i=iI(e,t);if(t+i<=e.length){let r=ib(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(l){let{frameLength:r,headerLength:s}=l,o=s+r,h=Math.max(0,i+o-t.length);h?(a=new Uint8Array(o-s)).set(t.subarray(i+s,t.length),0):a=t.subarray(i+s,i+o);let d={unit:a,pts:n};return h||e.samples.push(d),{sample:d,length:o,missing:h}}let o=t.length-i;return(a=new Uint8Array(o)).set(t.subarray(i,t.length),0),{sample:{unit:a,pts:n},length:o,missing:-1}}function iP(e,t=0,i=1/0){return function(e,t,i,r){var s,a;let n=(s=e)instanceof ArrayBuffer?s:s.buffer,l=1;"BYTES_PER_ELEMENT"in r&&(l=r.BYTES_PER_ELEMENT);let o=(a=e)&&a.buffer instanceof ArrayBuffer&&void 0!==a.byteLength&&void 0!==a.byteOffset?e.byteOffset:0,h=(o+e.byteLength)/l,d=Math.floor(Math.max(0,Math.min((o+t)/l,h))),u=Math.floor(Math.min(d+Math.max(i,0),h));return new r(n,d,u-d)}(e,t,i,Uint8Array)}function iC(e){let t=0,i=[];for(;iS(e,t);){let r=iA(e,t+6);e[t+5]>>6&1&&(t+=10);let s=(t+=10)+r;for(;t+100&&l.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:iw.audioId3,duration:1/0});as(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0),iU=null,iB=[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],i$=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],iG=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],iK=[0,1,1,4];function iV(e,t,i,r,s){if(i+24>t.length)return;let a=iH(t,i);if(a&&i+a.frameLength<=t.length){let n=r+s*(9e4*a.samplesPerFrame/a.sampleRate),l={unit:t.subarray(i,i+a.frameLength),pts:n,dts:n};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(l),{sample:l,length:a.frameLength,missing:0}}}function iH(e,t){let i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==a){let n=e[t+2]>>1&1,l=e[t+3]>>6,o=1e3*iB[14*(3===i?3-r:3===r?3:4)+s-1],h=i$[3*(3===i?0:2===i?1:2)+a],d=iG[i][r],u=iK[r],f=Math.floor(d*o/h+n)*u;if(null===iU){let e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);iU=e?parseInt(e[1]):0}return iU&&iU<=87&&2===r&&o>=224e3&&0===l&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:3===l?1:2,frameLength:f,samplesPerFrame:8*d*u}}}function iY(e,t){return 255===e[t]&&(224&e[t+1])==224&&(6&e[t+1])!=0}function iW(e,t){return t+1=e.length)return!1;let r=ib(e,t);if(r<=i)return!1;let s=t+r;return s===e.length||iD(e,s)}return!1}(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return t+5{let i=0,r=5;t+=5;let s=new Uint32Array(1),a=new Uint32Array(1),n=new Uint8Array(1);for(;r>0;){n[0]=e[t];let l=Math.min(r,8),o=8-l;a[0]=0xff000000>>>24+o<>o,i=i?i<iX(e,i))}}function iz(e,t,i,r,s){if(i+8>t.length||11!==t[i]||119!==t[i+1])return -1;let a=t[i+4]>>6;if(a>=3)return -1;let n=[48e3,44100,32e3][a],l=63&t[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>t.length)return -1;let h=t[i+6]>>5,d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));let u=(t[i+6]<<8|t[i+7])>>12-d&1,f=[2,1,2,3,3,4,4,5][h]+u,c=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([a<<6|c<<1|g>>2,(3&g)<<6|h<<3|u<<2|l>>4,l<<4&224]),p=t.subarray(i,i+o);return e.config=m,e.channelCount=f,e.samplerate=n,e.samples.push({unit:p,pts:r+1536/n*9e4*s}),o}class iZ extends iF{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=iL(e,0),i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==ix(t)&&16>=iX(e,i))return!1;for(let t=e.length;i8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}demux(e,t){this.timeOffset=t;let i=e,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=J(this.remainderData,e));let t=function(e){let t={valid:null,remainder:null},i=Y(e,["moof"]);if(i.length<2)return t.remainder=e,t;let r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;let a=this.extractID3Track(r,t);return s.samples=ee(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return i.samples=ee(e,t),{videoTrack:t,audioTrack:iM(),id3Track:r,textTrack:iM()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=Y(e.samples,["emsg"]);r&&r.forEach(e=>{let r=function(e){let t=e[0],i="",r="",s=0,n=0,l=0,o=0,h=0,d=0;if(0===t){for(;"\0"!==$(e.subarray(d,d+1));)i+=$(e.subarray(d,d+1)),d+=1;for(i+=$(e.subarray(d,d+1)),d+=1;"\0"!==$(e.subarray(d,d+1));)r+=$(e.subarray(d,d+1)),d+=1;r+=$(e.subarray(d,d+1)),d+=1,s=K(e,12),n=K(e,16),o=K(e,20),h=K(e,24),d=28}else if(1===t){d+=4,s=K(e,d);let t=K(e,d+=4),n=K(e,d+=4);for(d+=4,a(l=0x100000000*t+n)||(l=Number.MAX_SAFE_INTEGER,R.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=K(e,d),d+=4,h=K(e,d),d+=4;"\0"!==$(e.subarray(d,d+1));)i+=$(e.subarray(d,d+1)),d+=1;for(i+=$(e.subarray(d,d+1)),d+=1;"\0"!==$(e.subarray(d,d+1));)r+=$(e.subarray(d,d+1)),d+=1;r+=$(e.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:l,presentationTimeDelta:n,eventDuration:o,id:h,payload:e.subarray(d,e.byteLength)}}(e);if(iJ.test(r.schemeIdUri)){let e=i1(r,t),s=0xffffffff===r.eventDuration?1/0:r.eventDuration/r.timeScale;s<=.001&&(s=1/0);let a=r.payload;i.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:iw.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let e=i1(r,t);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:iw.misbklv,duration:1/0})}})}return i}demuxSampleAes(e,t,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}}function i1(e,t){return s(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class i2{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ti(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,e9.cbc)}decryptAacSample(e,t,i){let r=e[t].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(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=new Int8Array(16*Math.floor((e.length-48)/160)+16),i=0;for(let r=32;r{s.data=this.getAvcDecryptedUnit(a,n),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}).catch(r)}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();let s=e[t].units;for(;!(i>=s.length);i++){let a=s[i];if(!(a.data.length<=48)&&(1===a.type||5===a.type)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}}class i3{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){let e=r.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){let i=t.samples,r=i.length;if(!r)return void t.dropped++;{let t=i[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){let r,s,a,n=t.byteLength,l=e.naluState||0,o=l,h=[],d=0,u=-1,f=0;for(-1===l&&(u=0,f=this.getNALuType(t,0),l=0,d=1);d=0){let e={data:t.subarray(u,s),type:f};h.push(e)}else{let i=this.getLastNalUnit(e.samples);i&&(o&&d<=4-o&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-o)),s>0&&(i.data=J(i.data,t.subarray(0,s)),i.state=0))}d=0&&l>=0){let e={data:t.subarray(u,n),type:f,state:l};h.push(e)}if(0===h.length){let i=this.getLastNalUnit(e.samples);i&&(i.data=J(i.data,t))}return e.naluState=l,h}}class i4{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e||(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord()),this.word<<=e,this.bitsAvailable-=e}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&R.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error("no bits available");return(t=e-t)>0&&this.bitsAvailable?i<>>e)!=0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class i5 extends i3{parsePES(e,t,i,r){let s,a=this.parseNALu(e,i.data,r),n=this.VideoSample,l=!1;i.data=null,n&&a.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach(r=>{var a,o,h,d,u;switch(r.type){case 1:{let t=!1;s=!0;let a=r.data;if(l&&a.length>4){let e=this.readSliceType(a);(2===e||4===e||7===e||9===e)&&(t=!0)}t&&null!=(h=n)&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.frame=!0,n.key=t;break}case 5:s=!0,null!=(a=n)&&a.frame&&!n.key&&(this.pushAccessUnit(n,e),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,ei(r.data,1,i.pts,t.samples);break;case 7:{s=!0,l=!0;let t=r.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(d=e.pixelRatio)?void 0:d[0])!==i.pixelRatio[0]||(null==(u=e.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];let r=t.subarray(1,4),s="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),s+=t}e.codec=s}break}case 8:s=!0,e.pps=[r.data];break;case 9:s=!0,e.audFound=!0,null!=(o=n)&&o.frame&&(this.pushAccessUnit(n,e),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,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){let t=new i4(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,r=8;for(let s=0;s{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,e),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,e),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,ei(r.data,2,i.pts,t.samples);break;case 32:s=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=p(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(s=!0,l=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],r.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(r.data);for(let i in e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,r.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),n.key=!0;break;case 34:if(s=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];let t=this.readPPS(r.data);for(let i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:s=!0,e.audFound=!0,null!=(o=n)&&o.frame&&(this.pushAccessUnit(n,e),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,e),this.VideoSample=null)}pushParameterSet(e,t,i){(!i||i[0]!==this.initVPS)&&(i||e.length)||e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let r=0;r=2)||3!==e[r]||0!==e[r-1]||0!==e[r-2])&&(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new i4(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){let t=new i4(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let r=t.readBits(2),s=t.readBoolean(),a=t.readBits(5),n=t.readUByte(),l=t.readUByte(),o=t.readUByte(),h=t.readUByte(),d=t.readUByte(),u=t.readUByte(),f=t.readUByte(),c=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),E=[],y=[];for(let e=0;e0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e1&&t.readEG();for(let e=0;e0&&e<16?(w=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(w=t.readBits(16),M=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(N=t.readBits(32),U=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),r=t.readBoolean(),s=!1;(e||r)&&((s=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=i;a++){let i=(F=t.readBoolean())||t.readBoolean(),a=!1;i?t.readEG():a=t.readBoolean();let n=a?1:t.readUEG()+1;if(e)for(let e=0;e>e&1)<<31-e)>>>0;let H=V.toString(16);return 1===a&&"2"===H&&(H="6"),{codecString:`hvc1.${G}${a}.${H}.${s?"H":"L"}${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,u,f,c,g,m],general_level_idc:p,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:x,chroma_format_idc:v,frame_rate:{fixed:F,fps:U/N}},width:B,height:$,pixelRatio:[w,M]}}readPPS(e){let t=new i4(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let i=t.readBoolean(),r=t.readBoolean(),s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}class i6{constructor(e,t,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=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}static probe(e,t){let i=i6.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){let t=e.length,i=Math.min(940,t-188)+1,r=0;for(;r1&&(0===a&&n>2||l+188>i))return a}else if(n)return -1;else break;r++}return -1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:B[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=i6.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=i6.createTrack("audio",r),this._id3Track=i6.createTrack("id3"),this._txtTrack=i6.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){let s;i||(this.sampleAes=null);let a=this._videoTrack,n=this._audioTrack,l=this._id3Track,o=this._txtTrack,h=a.pid,d=a.pesData,u=n.pid,f=l.pid,c=n.pesData,g=l.pesData,m=null,p=this.pmtParsed,E=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=J(this.remainderData,e)).length,this.remainderData=null),y<188&&!r)return this.remainderData=e,{audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};let v=Math.max(0,i6.syncOffset(e));(y-=(y-v)%188)>4>1){if((r=t+5+e[t+4])===t+188)continue}else r=t+4;switch(T){case h:y&&(d&&(s=rt(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,o,s,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(r,t+188)),d.size+=t+188-r);break;case u:if(y){if(c&&(s=rt(c,this.logger)))switch(n.segmentCodec){case"aac":this.parseAACPES(n,s);break;case"mp3":this.parseMPEGPES(n,s);break;case"ac3":this.parseAC3PES(n,s)}c={data:[],size:0}}c&&(c.data.push(e.subarray(r,t+188)),c.size+=t+188-r);break;case f:y&&(g&&(s=rt(g,this.logger))&&this.parseID3PES(l,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(r,t+188)),g.size+=t+188-r);break;case 0:var S,A;y&&(r+=e[r]+1),E=this._pmtId=(31&(S=e)[(A=r)+10])<<8|S[A+11];break;case E:{y&&(r+=e[r]+1);let s=function(e,t,i,r,s,a){let n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(15&e[t+1])<<8|e[t+2],o=t+3+l-4,h=(15&e[t+10])<<8|e[t+11];for(t+=12+h;t0){let r=t+5,s=o;for(;s>2;){106===e[r]&&(!0!==i.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=l,n.segmentAudioCodec="ac3"));let t=e[r+1]+2;r+=t,s-=t}}break;case 194:case 135:return i7(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"))}t+=o+5}return n}(e,r,this.typeSupported,i,this.observer,this.logger);(h=s.videoPid)>0&&(a.pid=h,a.segmentCodec=s.segmentVideoCodec),(u=s.audioPid)>0&&(n.pid=u,n.segmentCodec=s.segmentAudioCodec),(f=s.id3Pid)>0&&(l.pid=f),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${v} to parse all TS packets.`),m=null,t=v-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=T}}else T++;T>0&&i7(this.observer,Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=d,n.pesData=c,l.pesData=g;let L={audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};return r&&this.extractRemainingSamples(L),L}flush(){let e,{remainderData:t}=this;return(this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes)?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(e){let t,{audioTrack:i,videoTrack:r,id3Track:s,textTrack:a}=e,n=r.pesData,l=i.pesData,o=s.pesData;if(n&&(t=rt(n,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,a,t,!0),r.pesData=null)):r.pesData=n,l&&(t=rt(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;o&&(t=rt(o,this.logger))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=o}demuxSampleAes(e,t,i){let r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new i2(this.observer,this.config,t);return this.decrypt(r,s)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new i5:"hevc"===e&&(this.videoParser=new i8))}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{i(e)}):i(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{i(e)})})}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(e,t){let i,r,s,a,n=0,l=this.aacOverFlow,o=t.data;if(l){this.aacOverFlow=null;let t=l.missing,i=l.sample.unit.byteLength;-1===t?o=J(l.sample.unit,o):(l.sample.unit.set(o.subarray(0,t),i-t),e.samples.push(l.sample),n=l.missing)}for(i=n,r=o.length;i0;)l+=i}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");let i=p({},t,{type:this._videoTrack?iw.emsg:iw.audioId3,duration:1/0});e.samples.push(i)}}function i9(e,t){return((31&e[t+1])<<8)+e[t+2]}function i7(e,t,i,r){r.warn(`parsing error: ${t.message}`),e.emit(h.ERROR,h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function re(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function rt(e,t){let i,r,s,a,n,l=0,o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=J(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>e.size-6)return null;let h=i[7];192&h&&(a=(14&i[9])*0x20000000+(255&i[10])*4194304+(254&i[11])*16384+(255&i[12])*128+(254&i[13])/2,64&h?a-(n=(14&i[14])*0x20000000+(255&i[15])*4194304+(254&i[16])*16384+(255&i[17])*128+(254&i[18])/2)>54e5&&(t.warn(`${Math.round((a-n)/9e4)}s delta between PTS and DTS, align them`),a=n):n=a);let d=(s=i[8])+9;if(e.size<=d)return null;e.size-=d;let u=new Uint8Array(e.size);for(let e=0,t=o.length;et){d-=t;continue}else i=i.subarray(d),t-=d,d=0;u.set(i,l),l+=t}return r&&(r-=s+3),{data:u,pts:a,dts:n,len:r}}return null}class ri{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);else if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);else if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}class rr{static init(){let e;for(e in rr.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:[]},rr.types)rr.types.hasOwnProperty(e)&&(rr.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);rr.HDLR_TYPES={video: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]),audio: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])};let t=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);rr.STTS=rr.STSC=rr.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),rr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),rr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let i=new Uint8Array([105,115,111,109]),r=new Uint8Array([97,118,99,49]),s=new Uint8Array([0,0,0,1]);rr.FTYP=rr.box(rr.types.ftyp,i,s,i,r),rr.DINF=rr.box(rr.types.dinf,rr.box(rr.types.dref,t))}static box(e,...t){let i=8,r=t.length,s=r;for(;r--;)i+=t[r].byteLength;let a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=255&i,a.set(e,4),r=0,i=8;r>24&255,e>>16&255,e>>8&255,255&e,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(e){return rr.box(rr.types.mdia,rr.mdhd(e.timescale||0,e.duration||0),rr.hdlr(e.type),rr.minf(e))}static mfhd(e){return rr.box(rr.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?rr.box(rr.types.minf,rr.box(rr.types.smhd,rr.SMHD),rr.DINF,rr.stbl(e)):rr.box(rr.types.minf,rr.box(rr.types.vmhd,rr.VMHD),rr.DINF,rr.stbl(e))}static moof(e,t,i){return rr.box(rr.types.moof,rr.mfhd(e),rr.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=rr.trak(e[t]);return rr.box.apply(null,[rr.types.moov,rr.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(rr.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=rr.trex(e[t]);return rr.box.apply(null,[rr.types.mvex,...i])}static mvhd(e,t){let i=Math.floor((t*=e)/0x100000000),r=Math.floor(t%0x100000000),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,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 rr.box(rr.types.mvhd,s)}static sdtp(e){let t,i,r=e.samples||[],s=new Uint8Array(4+r.length);for(t=0;t>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(t=0;t>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(i));let n=rr.box(rr.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(a))),l=e.width,o=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return rr.box(rr.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,rr.box(rr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rr.box(rr.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(e){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.config,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return rr.box(rr.types.mp4a,rr.audioStsd(e),rr.box(rr.types.esds,rr.esds(e)))}static mp3(e){return rr.box(rr.types[".mp3"],rr.audioStsd(e))}static ac3(e){return rr.box(rr.types["ac-3"],rr.audioStsd(e),rr.box(rr.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return rr.box(rr.types.stsd,rr.STSD,rr.mp4a(e));if("ac3"===t&&e.config)return rr.box(rr.types.stsd,rr.STSD,rr.ac3(e));if("mp3"===t&&"mp3"===e.codec)return rr.box(rr.types.stsd,rr.STSD,rr.mp3(e))}else if(e.pps&&e.sps){if("avc"===t)return rr.box(rr.types.stsd,rr.STSD,rr.avc1(e));if("hevc"===t&&e.vps)return rr.box(rr.types.stsd,rr.STSD,rr.hvc1(e))}else throw Error("video track missing pps or sps");throw Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,s=e.height||0,a=Math.floor(i/0x100000000),n=Math.floor(i%0x100000000);return rr.box(rr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,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(e,t){let i=rr.sdtp(e),r=e.id,s=Math.floor(t/0x100000000),a=Math.floor(t%0x100000000);return rr.box(rr.types.traf,rr.box(rr.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),rr.box(rr.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])),rr.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||0xffffffff,rr.box(rr.types.trak,rr.tkhd(e),rr.mdia(e))}static trex(e){let t=e.id;return rr.box(rr.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i,r,s,a,n,l,o=e.samples||[],h=o.length,d=12+16*h,u=new Uint8Array(d);for(t+=8+d,u.set([+("video"===e.type),0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),i=0;i>>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 rr.box(rr.types.trun,u)}static initSegment(e){rr.types||rr.init();let t=rr.moov(e);return J(rr.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],r=new Uint8Array([1,t.general_profile_space<<6|32*!!t.general_tier_flag|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|64*!!t.frame_rate.fixed,i.length]),s=r.length;for(let e=0;e>8,255&i[e][t].length]),s),s+=2,a.set(i[e][t],s),s+=i[e][t].length}let l=rr.box(rr.types.hvcC,a),o=e.width,h=e.height,d=e.pixelRatio[0],u=e.pixelRatio[1];return rr.box(rr.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,rr.box(rr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rr.box(rr.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))}}function rs(e,t,i=1,r=!1){let s=e*t*i;return r?Math.round(s):s}function ra(e,t=!1){return rs(e,1e3,11111111111111112e-21,t)}function rn(e){let{baseTime:t,timescale:i,trackId:r}=e;return`${t/i} (${t}/${i}) trackId: ${r}`}rr.types=void 0,rr.HDLR_TYPES=void 0,rr.STTS=void 0,rr.STSC=void 0,rr.STCO=void 0,rr.STSZ=void 0,rr.VMHD=void 0,rr.SMHD=void 0,rr.STSD=void 0,rr.FTYP=void 0,rr.DINF=void 0;let rl=null,ro=null;function rh(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:+!e}}}class rd extends v{constructor(e,t,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=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===rl){let e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);rl=e?parseInt(e[1]):0}if(null===ro){let e=navigator.userAgent.match(/Safari\/(\d+)/i);ro=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?rn(t):t} > ${e?rn(e):e}`),this._initPTS=this._initDTS=e}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(e){let t=!1,i=e[0].pts,r=e.reduce((e,r)=>{let s=r.pts,a=s-e;return(a<-0x100000000&&(t=!0,a=(s=ru(s,i))-e),a>0)?e:s},i);return t&&this.debug("PTS rollover detected"),r}remux(e,t,i,r,s,a,n,l){let o,h,d,u,f,g,m=s,p=s,E=e.pid>-1,y=t.pid>-1,v=t.samples.length,T=e.samples.length>0,S=n&&v>0||v>1;if((!E||T)&&(!y||S)||this.ISGenerated||n){let i;if(this.ISGenerated){var A,L,R,I;let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(A=t.pixelRatio)?void 0:A[0])!==(null==(L=e.pixelRatio)?void 0:L[0])||(null==(R=t.pixelRatio)?void 0:R[1])!==(null==(I=e.pixelRatio)?void 0:I[1]))||!e&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,s,a));let r=this.isVideoContiguous,n=-1;if(S&&(n=function(e){for(let t=0;t0){this.warn(`Dropped ${n} out of ${v} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(n),t.dropped+=n,p+=(t.samples[0].pts-e)/t.inputTimeScale,i=p}else -1===n&&(this.warn(`No keyframe found out of ${v} video samples`),g=!1);if(this.ISGenerated){if(T&&S){let i=this.getVideoStartPts(t.samples),r=(ru(e.samples[0].pts,i)-i)/t.inputTimeScale;m+=Math.max(0,r),p+=Math.max(0,-r)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,a)),h=this.remuxAudio(e,m,this.isAudioContiguous,a,y||S||l===c.AUDIO?p:void 0),S){let i=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,a)),o=this.remuxVideo(t,p,r,i)}}else S&&(o=this.remuxVideo(t,p,r,0));o&&(o.firstKeyFrame=n,o.independent=-1!==n,o.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=rf(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=rc(r,s,this._initPTS))),{audio:h,video:o,initSegment:d,independent:g,text:u,id3:f}}computeInitPts(e,t,i,r){let s=Math.round(i*t),a=ru(e,s);if(aMath.abs(e-r-(E+m))?i=!0:E=e-r-m}let L=E+m;for(let e=0;e0?e-1:e].dts&&(A=!0)}A&&u.sort(function(e,t){let i=e.dts-t.dts,r=e.pts-t.pts;return i||r}),s=u[0].dts;let R=(a=u[u.length-1].dts)-s,I=R?Math.round(R/(c-1)):v||e.inputTimeScale/30;if(i){let i=s-L,r=i>I,a=i<-1;if((r||a)&&(r?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ra(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ra(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!a||L>=u[0].pts||rl)){s=L;let e=u[0].pts-i;if(r)u[0].dts=s,u[0].pts=e;else{let t=!0;for(let r=0;re)||!t);r++){let e=u[r].pts;if(u[r].dts-=i,u[r].pts-=i,r0?i.dts-u[e-1].dts:I;if(t=e>0?i.pts-u[e-1].pts:I,s.stretchShortVideoTrack&&null!==this.nextAudioTs){let e=Math.floor(s.maxBufferHole*d),t=(r?T+r*d:this.nextAudioTs+m)-i.pts;t>e?((v=t-a)<0?v=a:C=!0,this.log(`It is approximately ${t/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=a}else v=a}let l=Math.round(i.pts-i.dts);O=Math.min(O,v),w=Math.max(w,v),x=Math.min(x,t),M=Math.max(M,t),f.push(rh(i.key,v,a,l))}if(f.length){if(rl){if(rl<70){let e=f[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(ro&&M-x0&&(r&&9e3>Math.abs(L-(S+A))||Math.abs(ru(v[0].pts,L)-(S+A))<20*c),v.forEach(function(e){e.pts=ru(e.pts,L)}),!i||S<0){let e=v.length;if(e!==(v=v.filter(e=>e.pts>=0)).length&&this.warn(`Removed ${v.length-e} of ${e} samples (initPTS ${A} / ${n})`),!v.length)return;S=0===s?0:r&&!y?Math.max(0,L-A):v[0].pts-A}if("aac"===e.segmentCodec){let t=this.config.maxAudioFramesDrift;for(let i=0,r=S+A;i=t*c&&o<1e4&&y){let t=Math.round(l/c);for(r=a-t*c;r<0&&t&&c;)t--,r+=c;0===i&&(this.nextAudioTs=S=r-A),this.warn(`Injecting ${t} audio frames @ ${((r-A)/n).toFixed(3)}s due to ${Math.round(1e3*l/n)} ms gap.`);for(let a=0;a0))return;b+=T;try{a=new Uint8Array(b)}catch(e){this.observer.emit(h.ERROR,h.ERROR,{type:l.MUX_ERROR,details:o.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:b,reason:`fail allocating audio mdat ${b}`});return}m||(new DataView(a.buffer).setUint32(0,b),a.set(rr.types.mdat,4))}a.set(s,T);let d=s.byteLength;T+=d,E.push(rh(!0,f,d,0)),I=n}let k=E.length;if(!k)return;let _=E[E.length-1];S=I-A,this.nextAudioTs=S+u*_.duration;let P=m?new Uint8Array(0):rr.moof(e.sequenceNumber++,R/u,p({},e,{samples:E}));e.samples=[];let C=(R-A)/n,O=S/n,x={data1:P,data2:a,startPTS:C,endPTS:O,startDTS:C,endDTS:O,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,x}}function ru(e,t){let i;if(null===t)return e;for(i=t0x100000000;)e+=i;return e}function rf(e,t,i,r){let s=e.samples.length;if(!s)return;let a=e.inputTimeScale;for(let n=0;ne.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}class rg extends v{constructor(e,t,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}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:r}=this;if(!(null!=e&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:s,video:a}=this.initData=W(e);if(t)!function(e,t){if(!e||!t)return;let i=t.keyId;i&&t.isCommonEncryption&&z(e,(e,t)=>{let r=e.subarray(8,24);r.some(e=>0!==e)||(R.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${k(r)} -> ${k(i)}`),e.set(i,8))})}(e,t);else{let e=s||a;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}s&&(i=rp(s,x.AUDIO,this)),a&&(r=rp(a,x.VIDEO,this));let n={};s&&a?n.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:s?n.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:e,id:"audio"}:a?n.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,r,a,n){var l,o;let{initPTS:h,lastEndTime:d}=this,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};s(d)||(d=this.lastEndTime=a||0);let f=t.samples;if(!f.length)return u;let c={initPTS:void 0,timescale:void 0,trackId:void 0},g=this.initData;if(null!=(l=g)&&l.length||(this.generateInitSegment(f),g=this.initData),!(null!=(o=g)&&o.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);let m=function(e,t,i){let r={},a=Y(e,["moof","traf"]);for(let e=0;er[e].duration)){let t=1/0,i=0,a=Y(e,["sidx"]);for(let e=0;e>>31)return R.warn("SIDX has hierarchical references (not supported)"),null;let o=K(e,i);i+=4,t.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:t}}(a[e]);if(null!=r&&r.references){t=Math.min(t,r.earliestPresentationTime/r.timescale);let e=r.references.reduce((e,t)=>e+t.info.duration||0,0);i=Math.max(i,e+r.earliestPresentationTime/r.timescale)}}i&&s(i)&&Object.keys(r).forEach(e=>{r[e].duration||(r[e].duration=i*r[e].timescale-r[e].start)})}return r}(f,g,this),p=g.audio?m[g.audio.id]:null,E=g.video?m[g.video.id]:null,y=rm(E,1/0),v=rm(p,1/0),T=rm(E,0,!0),S=rm(p,0,!0),A=a,L=0,I=p&&(!E||!h&&vs}(h,A,a,L)||e!==h.timescale)&&(h&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${a} ${t/e} != initPTS: ${h.baseTime/h.timescale} (${h.baseTime}/${h.timescale}) trackId: ${h.trackId}`),this.log(`Found initPTS at playlist time: ${a} offset: ${A-a} (${t}/${e}) trackId: ${i}`),h=null,c.initPTS=t,c.timescale=e,c.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${a}`);h?(c.initPTS=h.baseTime,c.timescale=h.timescale,c.trackId=h.trackId):(c.timescale&&void 0!==c.trackId&&void 0!==c.initPTS||(this.warn("Could not set initPTS"),c.initPTS=A,c.timescale=1,c.trackId=-1),this.initPTS=h={baseTime:c.initPTS,timescale:c.timescale,trackId:c.trackId});let D=A-h.baseTime/h.timescale,k=D+L;L>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let _=!!g.audio,P=!!g.video,C="";_&&(C+="audio"),P&&(C+="video");let O={data1:f,startPTS:D,startDTS:D,endPTS:k,endDTS:k,type:C,hasAudio:_,hasVideo:P,nb:1,dropped:0,encrypted:!!g.audio&&g.audio.encrypted||!!g.video&&g.video.encrypted};u.audio=_&&!P?O:void 0,u.video=P?O:void 0;let x=null==E?void 0:E.sampleCount;if(x){let e=E.keyFrameIndex,t=-1!==e;O.nb=x,O.dropped=0===e||this.isVideoContiguous?0:t?e:x,O.independent=t,O.firstKeyFrame=e,t&&E.keyFrameStart&&(O.firstKeyFramePTS=(E.keyFrameStart-h.baseTime)/h.timescale),this.isVideoContiguous||(u.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),O.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${x} dropped: ${O.dropped} start: ${O.firstKeyFramePTS||"NA"}`)}return u.initSegment=c,u.id3=rf(i,a,h,h),r.samples.length&&(u.text=rc(r,a,h)),u}}function rm(e,t,i=!1){return(null==e?void 0:e.start)!==void 0?(e.start+(i?e.duration:0))/e.timescale:t}function rp(e,t,i){let r=e.codec;return r&&r.length>4?r:t===x.AUDIO?"ec-3"===r||"ac-3"===r||"alac"===r?r:"fLaC"===r||"Opus"===r?eg(r,!1):(i.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):(i.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}try{r=self.performance.now.bind(self.performance)}catch(e){r=Date.now}let rE=[{demux:i0,remux:rg},{demux:i6,remux:rd},{demux:iq,remux:rd},{demux:iZ,remux:rd}];rE.splice(2,0,{demux:iQ,remux:rd});class ry{constructor(e,t,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=e,this.typeSupported=t,this.config=i,this.id=s,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){var a,n;let d,u=i.transmuxing;u.executeStart=r();let f=new Uint8Array(e),{currentTransmuxState:c,transmuxConfig:g}=this;s&&(this.currentTransmuxState=s);let{contiguous:m,discontinuity:p,trackSwitch:E,accurateTimeOffset:y,timeOffset:v,initSegmentChange:T}=s||c,{audioCodec:S,videoCodec:A,defaultInitPts:L,duration:R,initSegmentData:I}=g,b=(a=f,n=t,d=null,a.byteLength>0&&(null==n?void 0:n.key)!=null&&null!==n.iv&&null!=n.method&&(d=n),d);if(b&&tA(b.method)){let e=this.getDecrypter(),t=tL(b.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(f,b.key.buffer,b.iv.buffer,t).then(e=>{let t=this.push(e,null,i);return this.decryptionPromise=null,t}),this.decryptionPromise;{let s=e.softwareDecrypt(f,b.key.buffer,b.iv.buffer,t);if(i.part>-1){let t=e.flush();s=t?t.buffer:t}if(!s)return u.executeEnd=r(),rv(i);f=new Uint8Array(s)}}let D=this.needsProbing(p,E);if(D){let e=this.configureTransmuxer(f);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(h.ERROR,h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),u.executeEnd=r(),rv(i)}(p||E||T||D)&&this.resetInitSegment(I,S,A,R,t),(p||T||D)&&this.resetInitialTimestamp(L),m||this.resetContiguity();let k=this.transmux(f,b,v,y,i);this.asyncResult=rT(k);let _=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,u.executeEnd=r(),k}flush(e){let t=e.transmuxing;t.executeStart=r();let{decrypter:i,currentTransmuxState:s,decryptionPromise:a}=this;if(a)return this.asyncResult=!0,a.then(()=>this.flush(e));let n=[],{timeOffset:l}=s;if(i){let t=i.flush();t&&n.push(this.push(t.buffer,null,e))}let{demuxer:o,remuxer:h}=this;if(!o||!h){t.executeEnd=r();let i=[rv(e)];return this.asyncResult?Promise.resolve(i):i}let d=o.flush(l);return rT(d)?(this.asyncResult=!0,d.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,d,e),this.asyncResult)?Promise.resolve(n):n}flushRemux(e,t,i){let{audioTrack:s,videoTrack:a,id3Track:n,textTrack:l}=t,{accurateTimeOffset:o,timeOffset:h}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===c.MAIN?"level":"track"} ${i.level}`);let d=this.remuxer.remux(s,a,n,l,h,o,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=r()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s){let{demuxer:a,remuxer:n}=this;a&&n&&(a.resetInitSegment(e,t,i,r),n.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s)}transmuxUnencrypted(e,t,i,r){let{audioTrack:s,videoTrack:a,id3Track:n,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,a,n,l,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){let t,{config:i,observer:r,typeSupported:s}=this;for(let i=0,r=rE.length;i({remuxResult:{},chunkMeta:e});function rT(e){return"then"in e&&e.then instanceof Function}class rS{constructor(e,t,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=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class rA{constructor(e,t,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=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=a}}let rL=0;class rR{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=rL++,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=e=>{let t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var r;let e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${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:t})};let s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let a=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===h.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new iE,this.observer.on(h.FRAG_DECRYPTED,a),this.observer.on(h.ERROR,a);let n=eE(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 ${s.workerPath} for "${t}"`),this.workerContext=function(e){let t=iv[e];if(t)return t.clientCount++,t;let i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return iv[e]=r,r}(s.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){let e=iv[iy];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return iv[iy]=r,r}());let{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:n,id:t,config:eC(s)})}catch(r){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new ry(this.observer,n,s,"",t,e.logger)}return}}this.transmuxer=new ry(this.observer,n,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=rL++;let t=this.hls.config,i=eE(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:eC(t)})}}terminateWorker(){if(this.workerContext){let{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError);var e=this.hls.config.workerPath;let i=iv[e||iy];if(i&&1==i.clientCount--){let{worker:t,objectURL:r}=i;delete iv[e||iy],r&&self.URL.revokeObjectURL(r),t.terminate()}}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,r,s,a,n,l,o,h){var d,u;o.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:g}=this,m=a?a.start:s.start,p=s.decryptdata,E=this.frag,y=!(E&&s.cc===E.cc),v=!(E&&o.level===E.level),T=E?o.sn-E.sn:-1,S=this.part?o.part-this.part.index:-1,A=0===T&&o.id>1&&o.id===(null==E?void 0:E.stats.chunkCount),L=!v&&(1===T||0===T&&(1===S||A&&S<=0)),R=self.performance.now();(v||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=R),a&&(S||!L)&&(a.stats.parsing.start=R);let I=!(E&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=E.initSegment)?void 0:u.url)),b=new rA(y,L,l,v,m,I);if(!L||y||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${o.sn}${o.part>-1?" part: "+o.part:""} ${this.id===c.MAIN?"level":"track"}: ${o.level} id: ${o.id} discontinuity: ${y} trackSwitch: ${v} contiguous: ${L} accurateTimeOffset: ${l} timeOffset: ${m} initSegmentChange: ${I}`);let e=new rS(i,r,t,n,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:o,state:b},e instanceof ArrayBuffer?[e]:[]);else if(g){let t=g.push(e,p,o,b);rT(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,o,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let t=i.flush(e);rT(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class rI extends ic{constructor(e,t,i){super(e,t,i,"audio-stream-controller",c.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()}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:e}=this;e.on(h.LEVEL_LOADED,this.onLevelLoaded,this),e.on(h.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(h.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(h.BUFFER_RESET,this.onBufferReset,this),e.on(h.BUFFER_CREATED,this.onBufferCreated,this),e.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(h.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(h.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(h.FRAG_LOADING,this.onFragLoading,this),e.on(h.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(h.LEVEL_LOADED,this.onLevelLoaded,this),e.off(h.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(h.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(h.BUFFER_RESET,this.onBufferReset,this),e.off(h.BUFFER_CREATED,this.onBufferCreated,this),e.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(h.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(h.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(h.FRAG_LOADING,this.onFragLoading,this),e.off(h.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s,trackId:a}){if(i===c.MAIN){let e=t.cc,i=this.fragCurrent;if(this.initPTS[e]={baseTime:r,timescale:s,trackId:a},this.log(`InitPTS for cc: ${e} found from main: ${r/s} (${r}/${s}) trackId: ${a}`),this.mainAnchor=t,this.state===iu.WAITING_INIT_PTS){let i=this.waitingData;(i||this.loadingParts)&&(!i||i.frag.cc===e)||this.syncWithAnchor(t,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==e?(i.abortRequests(),this.syncWithAnchor(t,i)):this.state===iu.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(t&&(null==r?void 0:r.cc)===t.cc)return;let s=(r||e).cc,a=eH(this.getLevelDetails(),s,this.getLoadPosition());a&&(this.log(`Syncing with main frag at ${a.start} cc ${a.cc}`),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===iu.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=iu.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=iu.IDLE):this.state=iu.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case iu.IDLE:this.doTickIdle();break;case iu.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=iu.WAITING_INIT_PTS}break}case iu.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case iu.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:s}=e,a=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=iu.FRAG_LOADING;let e={frag:t,part:i,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=iu.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;let{hls:t,levels:i,media:r,trackId:s}=this,a=t.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=iu.WAITING_TRACK,this.startFragRequested=!1;return}let o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,x.AUDIO,c.AUDIO));let d=this.getFwdBufferInfo(o,c.AUDIO);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,l)){t.trigger(h.BUFFER_EOS,{type:"audio"}),this.state=iu.ENDED;return}let u=d.len,f=t.maxBufferLength,g=l.fragments,m=g[0].start,p=this.getLoadPosition(),E=this.flushing?p:d.end;if(this.switchingTrack&&r&&l.PTSKnown&&pm||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05),u>=f&&!this.switchingTrack&&Ev.end){let e=this.fragmentTracker.getFragAtPos(E,c.MAIN);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(y.start>v.end)return}this.loadFragment(y,n,E)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new e_(e))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==iu.STOPPED&&(this.setInterval(100),this.state=iu.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(h.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i,r;let{levels:s}=this,{details:a,id:n,groupId:l,track:o}=t;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${l}"`);let d=this.mainDetails;if(!d||a.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==iu.STOPPED&&(this.state=iu.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${l}" loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`);let u=s[n],f=0;if(a.live||null!=(i=u.details)&&i.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u.details&&(f=this.alignPlaylists(a,u.details,null==(r=this.levelLastLoaded)?void 0:r.details)),a.alignedSliding||(ia(a,d),a.alignedSliding||il(a,d),f=a.fragmentStart)}u.details=a,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,f),this.hls.trigger(h.AUDIO_TRACK_UPDATED,{details:a,id:n,groupId:t.groupId}),this.state!==iu.WAITING_TRACK||this.waitForCdnTuneIn(a)||(this.state=iu.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:s}=e,{config:a,trackId:n,levels:l}=this;if(!l)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let o=l[n];if(!o)return void this.warn("Audio track is undefined on fragment load progress");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",u=this.transmuxer;u||(u=this.transmuxer=new rR(this.hls,c.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],g=null==(t=i.initSegment)?void 0:t.data;if(void 0!==f){let e=r?r.index:-1,t=new to(i.level,i.sn,i.stats.chunkCount,s.byteLength,e,-1!==e);u.push(s,g,d,"",i,r,h.totalduration,!1,t,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${n}`);let{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new im,complete:!1};e.push(new Uint8Array(s)),this.state!==iu.STOPPED&&(this.state=iu.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===c.MAIN&&M(t.frag)&&(this.mainFragLoading=t,this.state===iu.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==c.AUDIO){this.audioOnly||i.type!==c.MAIN||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i))return void this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);if(M(i)){this.fragPrevious=i;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(h.AUDIO_TRACK_SWITCHED,y({},e)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=iu.ERROR;return}switch(t.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(c.AUDIO,t);break;case o.AUDIO_TRACK_LOAD_ERROR:case o.AUDIO_TRACK_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==iu.WAITING_TRACK||(null==(i=t.context)?void 0:i.type)!==f.AUDIO_TRACK||(this.state=iu.IDLE);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,"audio"));break;case o.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==x.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==x.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===iu.ENDED&&(this.state=iu.IDLE);let e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,c.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:a}=e,n=this.getCurrentContext(a);if(!n)return void this.resetWhenMissingContext(a);let{frag:l,part:o,level:d}=n,{details:u}=d,{audio:f,text:c,id3:g,initSegment:m}=s;if(this.fragContextChanged(l)||!u)return void this.fragmentTracker.removeFragment(l);if(this.state=iu.PARSING,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){let e=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(d,m.tracks,e,a),r.trigger(h.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:m.tracks})}if(f){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=f;o&&(o.elementaryStreams[x.AUDIO]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(x.AUDIO,e,t,i,r),this.bufferFragmentData(f,l,o,a)}if(null!=g&&null!=(t=g.samples)&&t.length){let e=p({id:i,frag:l,details:u},g);r.trigger(h.FRAG_PARSING_METADATA,e)}if(c){let e=p({id:i,frag:l,details:u},c);r.trigger(h.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,i,r){if(this.state!==iu.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let s=t.audio;s.id=c.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${a}/${s.codec}]`),a&&1===a.split(",").length&&(s.levelCodec=a),this.hls.trigger(h.BUFFER_CODECS,t);let n=s.initSegment;if(null!=n&&n.byteLength){let e={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:n};this.hls.trigger(h.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===e3.NOT_LOADED||r===e3.PARTIAL){var s;if(M(e))if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=iu.WAITING_INIT_PTS;let i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&il(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:i,assocLang:r,characteristics:s,audioCodec:a,channels:n}=this.bufferedTrack;eF({name:t,lang:i,assocLang:r,characteristics:s,audioCodec:a,channels:n},e,eN)||(eB(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,1/0,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(h.AUDIO_TRACK_SWITCHED,y({},e))}}class rb extends v{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}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(e,t,i){let r=null==t?void 0:t.renditionReports;if(r){let s=-1;for(let i=0;i=0&&e>t.partTarget&&(n+=1)}return new ek(a,n>=0?n:void 0,i&&eD(i))}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){let{details:r,stats:a}=t,n=self.performance.now(),d=a.loading.first?Math.max(0,n-a.loading.first):0;r.advancedDateTime=Date.now()-d;let u=this.hls.config.timelineOffset;if(u!==r.appliedTimelineOffset){let e=Math.max(u||0,0);r.appliedTimelineOffset=e,r.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(r.live||null!=i&&i.live){let u,c,g,m="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){!function(e,t,i){let r;if(e===t)return;let a=null,n=e.fragments;for(let e=n.length-1;e>=0;e--){let t=n[e].initSegment;if(t){a=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){let r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,a=+!!e.fragmentHint+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,n=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let u=s;u<=a;u++){let s=o[n+u],a=l[u];if(r&&!a&&s&&(a=t.fragments[u]=s),s&&a){var h,d;i(s,a,u,l);let r=s.relurl,n=a.relurl;if(r&&(h=r)!==(d=n)&&d&&it(h)!==it(d)){t.playlistParsingError=t3(`media sequence mismatch ${a.sn}:`,e,t,s,a);return}if(s.cc!==a.cc){t.playlistParsingError=t3(`discontinuity sequence mismatch (${s.cc}!=${a.cc})`,e,t,s,a);return}}}}(e,t,(e,i,n,l)=>{if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){let r=e.cc-i.cc;for(let e=n;e{var t;e&&(!e.initSegment||e.initSegment.relurl===(null==(t=a)?void 0:t.relurl))&&(e.initSegment=a)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(e=>!e),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){let{dateRanges:r,recentlyRemovedDateranges:s}=t,a=p({},e);s&&s.forEach(e=>{delete a[e]});let n=Object.keys(a).length;return n?(Object.keys(r).forEach(e=>{let t=a[e],s=new ty(r[e].attr,t);s.isValid?(a[e]=s,t||(s.tagOrder+=n)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${eC(r[e].attr)}"`)}),a):r}(e.dateRanges,t,i));let r=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),r?t2(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,i):t4(e,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let d=t.advancedDateTime;if(t.advanced&&d){let e=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=e),t.driftEndTime=d,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}(i,r,this);let e=r.playlistParsingError;if(e){this.warn(e);let i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var f;let{networkDetails:s}=t;i.trigger(h.ERROR,{type:l.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(f=r.fragments[0])?void 0:f.type,networkDetails:s,stats:a});return}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=a.loading.start);let E=this.hls.mainForwardBufferInfo,y=E?E.end-E.len:0,v=(r.edge-y)*1e3,T=t8(r,v);if(r.requestScheduled+T0){if(d>3*r.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),c=void 0,g=void 0;else if(null!=i&&i.tuneInGoal&&d-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{let e=Math.floor(f/r.targetduration);c+=e,void 0!==g&&(g+=Math.round(f%r.targetduration/r.partTarget)),this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${f} skip sn ${e} to part ${g}`)}r.tuneInGoal=f}if(u=this.getDeliveryDirectives(r,t.deliveryDirectives,c,g),e||!o){r.requestScheduled=n,this.loadingPlaylist(m,u);return}}else(r.canBlockReload||r.canSkipUntil)&&(u=this.getDeliveryDirectives(r,t.deliveryDirectives,c,g));u&&void 0!==c&&r.canBlockReload&&(r.requestScheduled=a.loading.first+Math.max(T-2*d,T/2)),this.scheduleLoading(m,u,r)}else this.clearTimer()}scheduleLoading(e,t,i){let r=i||e.details;if(!r)return void this.loadingPlaylist(e,t);let s=self.performance.now(),a=r.requestScheduled;if(s>=a)return void this.loadingPlaylist(e,t);let n=a-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(n)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),n)}getDeliveryDirectives(e,t,i,r){let s=eD(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=eb.No),new ek(i,r,s)}checkRetry(e){let t=e.details,i=eY(e),r=e.errorAction,{action:s,retryCount:a=0,retryConfig:n}=r||{},l=!!r&&!!n&&(s===eJ.RetryRequest||!r.resolved&&s===eJ.SendAlternateToPenaltyBox);if(l){var o;if(a>=n.maxNumRetry)return!1;if(i&&null!=(o=e.context)&&o.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=eX(n,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return l}}function rD(e,t){if(e.length!==t.length)return!1;for(let i=0;ie[i]!==t[i])}function r_(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class rP extends rb{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.MANIFEST_PARSED,this.onManifestParsed,this),e.on(h.LEVEL_LOADING,this.onLevelLoading,this),e.on(h.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(h.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.MANIFEST_PARSED,this.onManifestParsed,this),e.off(h.LEVEL_LOADING,this.onLevelLoading,this),e.off(h.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(h.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.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(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==a?void 0:a.groupId}`);let n=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.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(e=>(null==r?void 0:r.indexOf(e))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!s&&t){let i=eM(t,e,eN);if(i>-1)s=e[i];else{let e=eM(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null)),this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(h.AUDIO_TRACKS_UPDATED,{audioTracks:e});let n=this.trackId;if(-1!==r&&-1===n)this.setAudioTrack(r);else if(e.length&&-1===n){var a;let t=Error(`No audio track selected for current audio group-ID(s): ${null==(a=this.groupIds)?void 0:a.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==f.AUDIO_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let r=this.currentTrack;if(r&&eF(e,r,eN))return r;let s=eM(e,this.tracksInGroup,eN);if(s>-1){let e=this.tracksInGroup[s];return this.setAudioTrack(s),e}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);let s=function(e,t,i,r,s){let a=t[r],n=t.reduce((e,t,i)=>{let r=t.uri;return(e[r]||(e[r]=[])).push(i),e},{})[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=eU(t,r,t=>{if(t.videoRange!==l||t.frameRate!==o||t.codecSet.substring(0,4)!==h)return!1;let r=t.audioGroups;return eM(e,i.filter(e=>!r||-1!==r.indexOf(e.groupId)),s)>-1});return d>-1?d:eU(t,r,t=>{let r=t.audioGroups;return eM(e,i.filter(e=>!r||-1!==r.indexOf(e.groupId)),s)>-1})}(e,t.levels,i,r,eN);if(-1===s)return null;t.nextLoadLevel=s}if(e.channels||e.audioCodec){let t=eM(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(e===this.trackId&&r===i&&s||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(h.AUDIO_TRACK_SWITCHING,y({},r)),s))return;let a=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i{this.append({label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}},e)})}prependBlocker(e){return new Promise(t=>{this.queues&&this.queues[e].unshift({label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}})})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=null==(t=e[0])?void 0:t.label;("async-blocker"===i||"async-blocker-prepend"===i)&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){null!==this.queues&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute()}catch(s){var i;if(r.onError(s),null===this.queues||null===this.tracks)return;let t=null==(i=this.tracks[e])?void 0:i.buffer;null!=t&&t.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return null===e||null===t?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}let rO=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rx="HlsJsTrackRemovedError";class rw extends Error{constructor(e){super(e),this.name=rx}}class rM extends v{constructor(e,t){var i;super("buffer-controller",e.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=e=>{var t;this.hls&&(null==(t=this.mediaSource)?void 0:t.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{let{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(h.MEDIA_ATTACHED,{media:t,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:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(i=I(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}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:e}=this;e.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.MANIFEST_PARSED,this.onManifestParsed,this),e.on(h.BUFFER_RESET,this.onBufferReset,this),e.on(h.BUFFER_APPENDING,this.onBufferAppending,this),e.on(h.BUFFER_CODECS,this.onBufferCodecs,this),e.on(h.BUFFER_EOS,this.onBufferEos,this),e.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(h.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(h.FRAG_PARSED,this.onFragParsed,this),e.on(h.FRAG_CHANGED,this.onFragChanged,this),e.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.MANIFEST_PARSED,this.onManifestParsed,this),e.off(h.BUFFER_RESET,this.onBufferReset,this),e.off(h.BUFFER_APPENDING,this.onBufferAppending,this),e.off(h.BUFFER_CODECS,this.onBufferCodecs,this),e.off(h.BUFFER_EOS,this.onBufferEos,this),e.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(h.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(h.FRAG_PARSED,this.onFragParsed,this),e.off(h.FRAG_CHANGED,this.onFragChanged,this),e.off(h.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let e=this.isUpdating();e||this.operationQueue.removeBlockers();let t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?p(i,r.tracks):this.sourceBuffers.forEach(e=>{let[t]=e;t&&(i[t]=p({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,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(e,t){var i;let r=2;(!t.audio||t.video)&&t.altAudio||(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let r=I(this.appendSource);if(r){let e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let s=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(s),e)this._objectUrl=i.src,this.attachTransferred();else{let e=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{i.removeAttribute("src");let t=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||t&&s instanceof t,rF(i),function(e,t){let i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,r=t.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 ${this.bufferCodecEventsTotal}) required tracks: ${eC(i,(e,t)=>"initSegment"===e?void 0:t)}; transfer tracks: ${eC(r,(e,t)=>"initSegment"===e?void 0:t)}}`),!b(r,i)){t.mediaSource=null,t.tracks=void 0;let s=e.currentTime,a=this.details,n=Math.max(s,(null==a?void 0:a.fragments[0].start)||0);return n-s>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${n}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${n} currentTime: ${s}`),this.onMediaDetaching(h.MEDIA_DETACHING,{}),this.onMediaAttaching(h.MEDIA_ATTACHING,t),void(e.currentTime=n))}this.transferData=void 0,s.forEach(e=>{let t=r[e];if(t){let i=t.buffer;if(i){let r=this.fragmentTracker,s=t.id;if(r.hasFragments(s)||r.hasParts(s)){let t=tu.getBuffered(i);r.detectEvictedFragments(e,t,s,null,!0)}let a=rN(e),n=[e,i];this.sourceBuffers[a]=n,i.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,t)}}}),n(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),n()}get mediaSourceOpenOrEnded(){var e;let t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:s,_objectUrl:a}=this;if(s){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e="open"===s.readyState;try{let t=s.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),s.removeSourceBuffer(t[i]);e&&s.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.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&&rF(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,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t,i;let r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[rN(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new rC(this.tracks)}onBufferCodecs(e,t){var i;let r=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),n=!a&&this.sourceBufferCount&&this.media&&s.some(e=>!r[e]);if(a||n)return void this.warn(`Unsupported transition between "${Object.keys(r)}" and "${s}" SourceBuffers`);s.forEach(e=>{var i,s;let{id:a,codec:n,levelCodec:l,container:o,metadata:h,supplemental:d}=t[e],u=r[e],f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[e],c=null!=f&&f.buffer?f:u,g=(null==c?void 0:c.pendingCodec)||(null==c?void 0:c.codec),m=null==c?void 0:c.levelCodec;u||(u=r[e]={buffer:void 0,listeners:[],codec:n,supplemental:d,container:o,levelCodec:l,metadata:h,id:a});let p=em(g,m),E=null==p?void 0:p.replace(rO,"$1"),y=em(n,l),v=null==(s=y)?void 0:s.replace(rO,"$1");y&&p&&E!==v&&("audio"===e.slice(0,5)&&(y=eg(y,this.appendSource)),this.log(`switching codec ${g} to ${y}`),y!==(u.pendingCodec||u.codec)&&(u.pendingCodec=y),u.container=o,this.appendChangeType(e,o,y))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(!(this.bufferCodecEventsTotal>1)||this.tracks.video||t.video||(null==(i=t.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((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let r=`${t};codecs=${i}`,s={label:`change-type=${r}`,execute:()=>{let s=this.tracks[e];if(s){let a=s.buffer;null!=a&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),s.codec=i,s.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,r=i+.05*e.duration;if((null==(t=this.fragmentTracker.getAppendedFrag(i,c.MAIN))?void 0:t.gap)===!0)return;let s={label:"block-audio",execute:()=>{var e;let t=this.tracks.video;(this.lastVideoAppendEnd>r||null!=t&&t.buffer&&tu.isBuffered(t.buffer,r)||(null==(e=this.fragmentTracker.getAppendedFrag(r,c.MAIN))?void 0:e.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:s,frag:e},this.append(s,"audio",!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:i}=this,{data:r,type:a,parent:n,frag:d,part:u,chunkMeta:f,offset:g}=t,m=f.buffering[a],{sn:p,cc:E}=d,y=self.performance.now();m.start=y;let v=d.stats.buffering,T=u?u.stats.buffering:null;0===v.start&&(v.start=y),T&&0===T.start&&(T.start=y);let S=i.audio,A=!1;"audio"===a&&(null==S?void 0:S.container)==="audio/mpeg"&&(A=!this.lastMpegAudioChunk||1===f.id||this.lastMpegAudioChunk.sn!==f.sn,this.lastMpegAudioChunk=f);let L=i.video,R=null==L?void 0:L.buffer;if(R&&"initSegment"!==p){let e=u||d,t=this.blockedAudioAppend;if("audio"!==a||"main"===n||this.blockedAudioAppend||L.ending||L.ended){if("video"===a){let i=e.end;if(t){let e=t.frag.start;(i>e||i{var e;m.executeStart=self.performance.now();let t=null==(e=this.tracks[a])?void 0:e.buffer;t&&(A?this.updateTimestampOffset(t,I,.1,a,p,E):void 0!==g&&s(g)&&this.updateTimestampOffset(t,g,1e-6,a,p,E)),this.appendExecutor(r,a)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();m.executeEnd=m.end=e,0===v.first&&(v.first=e),T&&0===T.first&&(T.first=e);let t={};this.sourceBuffers.forEach(([e,i])=>{e&&(t[e]=tu.getBuffered(i))}),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:u,chunkMeta:f,parent:d.type,timeRanges:t})},onError:e=>{var t;let i={type:l.MEDIA_ERROR,parent:d.type,details:o.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:d,part:u,chunkMeta:f,error:e,err:e,fatal:!1},r=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=o.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!r)i.errorAction=e2(!0);else if(e.name===rx&&0===this.sourceBufferCount)i.errorAction=e2(!0);else{let e=++this.appendErrors[a];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer (${r||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||r)&&(i.fatal=!0)}this.hls.trigger(h.ERROR,i)}};this.log(`queuing "${a}" append sn: ${p}${u?" p: "+u.index:""} of ${d.type===c.MAIN?"level":"track"} ${d.level} cc: ${E}`),this.append(b,a,this.isPending(this.tracks[a]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(h.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){let{type:i,startOffset:r,endOffset:s}=t;i?this.append(this.getFlushOp(i,r,s),i):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,r,s),e)})}onFragParsed(e,t){let{frag:i,part:r}=t,s=[],a=r?r.elementaryStreams:i.elementaryStreams;a[x.AUDIOVIDEO]?s.push("audiovideo"):(a[x.AUDIO]&&s.push("audio"),a[x.VIDEO]&&s.push("video"));let n=()=>{let e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:i.stats;this.hls.trigger(h.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type})};0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(n,s).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([e])=>{if(e){let i=this.tracks[e];(!t.type||t.type===e)&&(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}});let r=(null==(i=this.overrides)?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:e}=this;if(!e||"open"!==e.readyState){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(h.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(h.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===o.BUFFER_APPEND_ERROR&&t.frag){var i;let e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;s(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||null===t||!this.sourceBufferCount)return;let r=e.config,a=i.currentTime,n=t.levelTargetDuration,l=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(s(l)&&l>=0){let e=Math.max(l,n),t=Math.floor(a/n)*n-e;this.flushBackBuffer(a,n,t)}let o=r.frontBufferFlushThreshold;if(s(o)&&o>0){let e=Math.max(Math.max(r.maxBufferLength,o),n),t=Math.floor(a/n)*n+e;this.flushFrontBuffer(a,n,t)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([e,t])=>{if(t){let s=tu.getBuffered(t);if(s.length>0&&i>s.start(0)){var r;this.hls.trigger(h.BACK_BUFFER_REACHED,{bufferEnd:i});let t=this.tracks[e];if(null!=(r=this.details)&&r.live)this.hls.trigger(h.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(h.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([t,r])=>{if(r){let s=tu.getBuffered(r),a=s.length;if(a<2)return;let n=s.start(a-1),l=s.end(a-1);i>n||e>=n&&e<=l||this.hls.trigger(h.BUFFER_FLUSHING,{startOffset:n,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||(null==i?void 0:i.readyState)!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let e=Math.max(0,t.fragmentStart),i=Math.max(e,r);return{duration:1/0,start:e,end:i}}return{duration:1/0}}let a=null==(e=this.overrides)?void 0:e.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({duration:e,start:t,end:i}){let r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==e&&(s(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),void 0!==t&&void 0!==i&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${eC(i)}`),this.tracksReady){var r;let e=null==(r=this.transferData)?void 0:r.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(h.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=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:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let s in e){let a=e[s];if(this.isPending(a)){let e=this.getTrackCodec(a,s),n=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${n})${this.currentOp(s)?" Queued":""} ${eC(a)}`);try{let e=i.addSourceBuffer(n),r=rN(s),l=[s,e];t[r]=l,a.buffer=e}catch(e){var r;this.error(`error while trying to add sourceBuffer: ${e.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:e,sourceBufferName:s,mimeType:n,parent:a.id});return}this.trackSourceBuffer(s,a)}}this.bufferCreated()}getTrackCodec(e,t){let i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&el(i,"video")&&(r=function(e,t){let i=[];if(e){let t=e.split(",");for(let e=0;e{let i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(h.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;let i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if((null==(t=this.mediaSource)?void 0:t.readyState)==="closed")return void this.resetBuffer(e);let i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;let r=Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let s=this.currentOp(e);s&&s.onError(r)}updateTimestampOffset(e,t,i,r,s,a){Math.abs(t-e.timestampOffset)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${s} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:r,mediaSource:a}=this,n=this.tracks[e],l=null==n?void 0:n.buffer;if(!r||!a||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let o=s(r.duration)?r.duration:1/0,h=s(a.duration)?a.duration:1/0,d=Math.max(0,t),u=Math.min(i,o,h);u>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${u}] from the ${e} SourceBuffer`),l.remove(d,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new rw(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,r=t.map(e=>this.appendBlocker(e));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;let i=null==(t=this.tracks[e])?void 0:t.buffer;i&&!i.updating&&this.shiftAndExecuteNext(e)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+ +!!this.isPending(this.tracks[t]),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+ +!!t,0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let r=this.tracks[e];if(!r)return;let s=r.buffer;if(!s)return;let a=i.bind(this,e);r.listeners.push({event:t,listener:a}),s.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(e=>{i.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}function rF(e){let t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function rN(e){return+("audio"===e)}class rU{constructor(e){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=e,this.autoLevelCapping=1/0,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(h.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(h.MANIFEST_PARSED,this.onManifestParsed,this),e.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(h.BUFFER_CODECS,this.onBufferCodecs,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(h.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(h.MANIFEST_PARSED,this.onManifestParsed,this),e.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(h.BUFFER_CODECS,this.onBufferCodecs,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&s(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.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 e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((t,i)=>this.isLevelAllowed(t)&&i<=e);return this.clientRect=null,rU.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=1/0,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=1/0,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,i){if(!(null!=e&&e.length))return -1;let r=(e,t)=>!t||e.width!==t.width||e.height!==t.height,s=e.length-1,a=Math.max(t,i);for(let t=0;t=a||i.height>=a)&&r(i,e[t+1])){s=t;break}}return s}}let rB={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",TIMED_TEXT:"tt"},r$={HLS:"h"};class rG{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof rG?e:new rG(e))),this.value=e,this.params=t}}function rK(e,t,i){return Error(`failed to serialize "${Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}" as ${t}`,{cause:i})}class rV{constructor(e){this.description=e}}let rH="Bare Item";function rY(e){if(e<-0x38d7ea4c67fff||0x38d7ea4c67fff12)throw rK(e,"Decimal");let i=t.toString();return i.includes(".")?i:`${i}.0`;case"string":if(rW.test(e))throw rK(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;case"symbol":return rj(e);case"boolean":if("boolean"!=typeof e)throw rK(e,"Boolean");return e?"?1":"?0";case"object":if(e instanceof Date)return`@${rY(e.getTime()/1e3)}`;if(e instanceof Uint8Array){if(!1===ArrayBuffer.isView(e))throw rK(e,"Byte Sequence");return`:${btoa(String.fromCharCode(...e))}:`}if(e instanceof rV)return rj(e);default:throw rK(e,rH)}}function rX(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw rK(e,"Key");return e}function rQ(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${rX(e)}`:`;${rX(e)}=${rq(t)}`).join("")}function rz(e){return e instanceof rG?`${rq(e.value)}${rQ(e.params)}`:rq(e)}function rZ(e,t){return function(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw rK(e,"Dict");let i=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map(([e,t])=>{t instanceof rG==!1&&(t=new rG(t));let i=rX(e);if(!0===t.value)i+=rQ(t.params);else if(i+="=",Array.isArray(t.value)){var r;i+=(r=t,`(${r.value.map(rz).join(" ")})${rQ(r.params)}`)}else i+=rz(t);return i}).join(`,${r}`)}(e,t)}let rJ="CMCD-Object",r0="CMCD-Request",r1="CMCD-Session",r2="CMCD-Status",r3={br:rJ,ab:rJ,d:rJ,ot:rJ,tb:rJ,tpb:rJ,lb:rJ,tab:rJ,lab:rJ,url:rJ,pb:r0,bl:r0,tbl:r0,dl:r0,ltc:r0,mtp:r0,nor:r0,nrr:r0,rc:r0,sn:r0,sta:r0,su:r0,ttfb:r0,ttfbb:r0,ttlb:r0,cmsdd:r0,cmsds:r0,smrt:r0,df:r0,cs:r0,ts:r0,cid:r1,pr:r1,sf:r1,sid:r1,st:r1,v:r1,msd:r1,bs:r2,bsd:r2,cdn:r2,rtp:r2,bg:r2,pt:r2,ec:r2,e:r2},r4={REQUEST:r0},r5="event",r8=e=>Math.round(e),r6=(e,t)=>Array.isArray(e)?e.map(e=>r6(e,t)):e instanceof rG&&"string"==typeof e.value?new rG(r6(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){let i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;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}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),r9=e=>100*r8(e/100),r7={br:r8,d:r8,bl:r9,dl:r9,mtp:r9,nor:(e,t)=>{let i=e;return t.version>=2&&(e instanceof rG&&"string"==typeof e.value?i=new rG([e]):"string"==typeof e&&(i=[e])),r6(i,t)},rtp:r9,tb:r8},se="request",st="response",si=["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"],sr=["e"],ss=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function sa(e){return ss.test(e)}let sn=["d","dl","nor","ot","rtp","su"],sl=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],so=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function sh(e){return so.includes(e)||sa(e)}let sd={[st]:function(e){return si.includes(e)||sn.includes(e)||sl.includes(e)||sa(e)},[r5]:function(e){return si.includes(e)||sr.includes(e)||sa(e)},[se]:function(e){return si.includes(e)||sn.includes(e)||sa(e)}};function su(e,t={}){let i={};if(null==e||"object"!=typeof e)return i;let r=t.version||e.v||1,a=t.reportingMode||se,n=1===r?sh:sd[a],l=Object.keys(e).filter(n),o=t.filter;"function"==typeof o&&(l=l.filter(o));let h=a===st||a===r5;h&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");let d=p({},r7,t.formatters),u={version:r,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(t=>{var a;let n=e[t],l=d[t];if("function"==typeof l&&(n=l(n,u)),"v"===t)if(1===r)return;else n=r;("pr"!=t||1!==n)&&(h&&"ts"===t&&!s(n)&&(n=Date.now()),("number"==typeof(a=n)?s(a):null!=a&&""!==a&&!1!==a)&&(["ot","sf","st","e","sta"].includes(t)&&"string"==typeof n&&(n=new rV(n)),i[t]=n))}),i}let sf=/CMCD=[^&#]+/;class sc{constructor(e){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=e=>{try{this.apply(e,{ot:rB.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{let{frag:t,part:i}=e,r=this.hls.levels[t.level],s=this.getObjectType(t),a={d:1e3*(i||t).duration,ot:s};(s===rB.VIDEO||s===rB.AUDIO||s==rB.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(t);null!=n&&n.url&&n.url!==t.url&&(a.nor=n.url),this.apply(e,a)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(h.MEDIA_DETACHED,this.onMediaDetached,this),e.on(h.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(h.MEDIA_DETACHED,this.onMediaDetached,this),e.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(e,t){this.media=t.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(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:r$.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){p(t,this.createData());let i=t.ot===rB.INIT||t.ot===rB.VIDEO||t.ot===rB.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((e,i)=>(r.includes(i)&&(e[i]=t[i]),e),{}));let s={baseUrl:e.url};if(this.useHeaders){var a;e.headers||(e.headers={}),a=e.headers,p(a,function(e,t={}){let i={};return e?Object.entries(function(e,t){let i={};if(!e)return i;let r=Object.keys(e),s=t?Object.keys(t).reduce((e,i)=>{var r;return null==(r=t[i])||r.forEach(t=>e[t]=i),e},{}):{};return r.reduce((t,i)=>{var r;let a=r3[i]||s[i]||r4.REQUEST;return(null!=(r=t[a])?r:t[a]={})[i]=e[i],t},i)}(su(e,t),null==t?void 0:t.customHeaderMap)).reduce((e,[t,i])=>{let r=rZ(i,{whitespace:!1});return r&&(e[t]=r),e},i):i}(t,s))}else e.url=function(e,t,i){let r=function(e,t={}){if(!e)return"";let i=function(e,t={}){return e?encodeURIComponent(function(e,t={}){return e?rZ(su(e,t),{whitespace:!1}):""}(e,t)):""}(e,t);return`CMCD=${i}`}(t,i);if(!r)return e;if(sf.test(e))return e.replace(sf,r);let s=e.includes("?")?"&":"?";return`${e}${s}${r}`}(e.url,t,s)}getNextFrag(e){var t;let i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){let t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t;let{index:i,fragment:r}=e,s=null==(t=this.hls.levels[r.level])||null==(t=t.details)?void 0:t.partList;if(s){let{sn:e}=r;for(let t=s.length-1;t>=0;t--){let r=s[t];if(r.index===i&&r.fragment.sn===e)return s[t+1]}}}getObjectType(e){let{type:t}=e;return"subtitle"===t?rB.TIMED_TEXT:"initSegment"===e.sn?rB.INIT:"audio"===t?rB.AUDIO:"main"===t?this.hls.audioTracks.length?rB.VIDEO:rB.MUXED:void 0}getTopBandwidth(e){let t,i=0,r=this.hls;if(e===rB.AUDIO)t=r.audioTracks;else{let e=r.maxAutoLevel,i=e>-1?e+1:r.levels.length;t=r.levels.slice(0,i)}return t.forEach(e=>{e.bitrate>i&&(i=e.bitrate)}),i>0?i:NaN}getBufferLength(e){let t=this.media,i=e===rB.AUDIO?this.audioBuffer:this.videoBuffer;return i&&t?1e3*tu.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}}class sg extends v{constructor(e){super("content-steering",e.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=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(h.MANIFEST_PARSED,this.onManifestParsed,this),e.on(h.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(h.MANIFEST_PARSED,this.onManifestParsed,this),e.off(h.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}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(e){let t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}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(e,t){let{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((null==i?void 0:i.action)===eJ.SendAlternateToPenaltyBox&&i.flags===e0.MoveAllAlternatesMatchingHost){let e=this.levels,r=this._pathwayPriority,s=this.pathwayId;if(t.context){let{groupId:i,pathwayId:r,type:a}=t.context;i&&e?s=this.getPathwayForGroupId(i,a,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),t.details!==o.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e?e.length:e} priorities: ${eC(r)} penalized: ${eC(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;let i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(e=>{r-i[e]>3e5&&delete i[e]});for(let r=0;r0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,ie(t),this.hls.trigger(h.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];n&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==n.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==n.bitrate&&this.log(`Unstable Pathways change from bitrate ${n.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i{let{ID:s,"BASE-ID":a,"URI-REPLACEMENT":n}=e;if(t.some(e=>e.pathwayId===s))return;let l=this.getLevelsForPathway(a).map(e=>{let t=new tE(e.attrs);t["PATHWAY-ID"]=s;let a=t.AUDIO&&`${t.AUDIO}_clone_${s}`,l=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;a&&(i[t.AUDIO]=a,t.AUDIO=a),l&&(r[t.SUBTITLES]=l,t.SUBTITLES=l);let o=sp(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",n),h=new e_({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:o,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t{this.log(`Loaded steering manifest: "${t}"`);let a=e.data;if((null==a?void 0:a.VERSION)!==1)return void this.log(`Steering VERSION ${a.VERSION} not supported!`);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,t).href}catch(e){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${n}`);return}this.scheduleRefresh(this.uri||r.url),l&&this.clonePathways(l);let d={steeringManifest:a,url:t.toString()};this.hls.trigger(h.STEERING_MANIFEST_LOADED,d),o&&this.updatePathwayPriority(o)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let s=1e3*this.timeToLoad;if(429===e.code){let e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){let t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,s)},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;let i=null==(t=this.hls)?void 0:t.media;if(i&&!i.ended)return void this.loadSteeringManifest(e);this.scheduleRefresh(e,1e3*this.timeToLoad)},t)}}function sm(e,t,i,r){e&&Object.keys(t).forEach(s=>{let a=e.filter(e=>e.groupId===s).map(e=>{let a=p({},e);return a.details=void 0,a.attrs=new tE(a.attrs),a.url=a.attrs.URI=sp(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=r,a});e.push(...a)})}function sp(e,t,i,r){let s,{HOST:a,PARAMS:n,[i]:l}=r;t&&(s=null==l?void 0:l[t])&&(e=s);let o=new self.URL(e);return a&&!s&&(o.host=a),n&&Object.keys(n).sort().forEach(e=>{e&&o.searchParams.set(e,n[e])}),o.href}class sE extends v{constructor(e){super("eme",e.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=sE.CDMCleanupPromise?[sE.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{let{initDataType:t,initData:i}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=tx(this.config));let t=e.map(tO).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(s=>{let a,n=tC(s);if("sinf"!==t||n!==t_.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);try{let e=$(new Uint8Array(i)),t=tR(JSON.parse(e).sinf),r=Z(t);if(!r)throw Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(r.subarray(8,24))}catch(e){this.warn(`${r} Failed to parse sinf: ${e}`);return}let l=k(a),{keyIdToKeySessionPromise:o,mediaKeySessions:h}=this,d=o[l];for(let e=0;ethis.generateRequestWithPreferredKeySession(r,t,i,"encrypted-event-key-match"))).catch(e=>this.handleError(e));break}}d||this.handleError(Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.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(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=null==t?void 0:t[e];return r?r.licenseUrl:e===t_.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(void 0===t)throw Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(i),s=t.map(e=>e.videoCodec).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise((t,i)=>{let a=e=>{let n=e.shift();this.getMediaKeysPromise(n,r,s).then(e=>t({keySystem:n,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof sv?i(t):i(new sv({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===tw&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){var r;let s=function(e,t,i,r){var s,a,n,l;let o;switch(e){case t_.FAIRPLAY:o=["cenc","sinf"];break;case t_.WIDEVINE:case t_.PLAYREADY:o=["cenc"];break;case t_.CLEARKEY:o=["cenc","keyids"];break;default:throw Error(`Unknown key-system: ${e}`)}return s=o,a=t,n=i,[{initDataTypes:s,persistentState:(l=r).persistentState||"optional",distinctiveIdentifier:l.distinctiveIdentifier||"optional",sessionTypes:l.sessionTypes||[l.sessionType||"temporary"],audioCapabilities:a.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:l.audioRobustness||"",encryptionScheme:l.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:l.videoRobustness||"",encryptionScheme:l.videoEncryptionScheme||null}))}]}(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],n=null==(r=a)?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${eC(s)}`),n=this.requestMediaKeySystemAccess(e,s);let t=a=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),n.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);let r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let s=t.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,r.then(t=>t?this.setMediaKeysServerCertificate(i,e,t):i)));return s.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),s})}return n.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${k(e.keyId||[])} keyUri: ${e.uri}`);let r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=sy(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${k(e.decryptdata.keyId||[])} } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>tO(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let r=tO(e);r?t(r):i(Error(`Unable to find format for key-system "${e}"`))}).catch(i)})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=tx(this.config),i=e.map(tC).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(i)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(i,r).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:r,decryptdata:t}))))).then(e=>{let i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return r.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[i]=r,r}return a.catch(i=>{if(i instanceof sv){let r=y({},i.data);"internal-error"===this.getKeyStatus(t)&&(r.decryptdata=t);let s=new sv(r,i.message);this.handleError(s,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof sv){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${k(i.keyId||[])})`:""}`),this.hls.trigger(h.ERROR,e.data)}else this.error(e.message),this.hls.trigger(h.ERROR,{type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=sy(e),i=this.keyIdToKeySessionPromise[t];if(!i){let t=tC(e.keyFormat),i=t?[t]:tx(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=tx(this.config)),0===e.length)throw new sv({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${eC({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);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(t)});return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===i.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,i,r){var s;let a=null==(s=this.config.drmSystems)||null==(s=s[e.keySystem])?void 0:s.generateRequest;if(a)try{let r=a.call(this.hls,t,i,e);if(!r)throw Error("Invalid response from configured generateRequest filter");t=r.initDataType,i=r.initData?r.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let n=sy(e.decryptdata),h=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${n} URI: ${h} (init data type: ${t} length: ${i.byteLength})`);let d=new iE,u=e._onmessage=t=>{let i=e.mediaKeysSession;if(!i)return void d.emit("error",Error("invalid state"));let{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch(e=>{d.eventNames().length?d.emit("error",e):this.handleError(e)}):"license-release"===r?e.keySystem===t_.FAIRPLAY&&this.updateKeySession(e,tI("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${r}"`)},f=(e,t)=>{let i;t.keyStatus=e,e.startsWith("usable")?d.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=sT(e,t.decryptdata):"expired"===e?i=Error(`key expired (keyId: ${n})`):"released"===e?i=Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${n})`),i&&(d.eventNames().length?d.emit("error",i):this.handleError(i))},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void d.emit("error",Error("invalid state"));let i=this.getKeyStatuses(e);if(!Object.keys(i).some(e=>"status-pending"!==i[e]))return;if("expired"===i[n]){this.log(`Expired key ${eC(i)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let r=i[n];if(r)f(r,e);else{var s;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(s=e.keyStatusTimeouts)[n]||(s[n]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let t=this.getKeyStatus(e.decryptdata);if(t&&"status-pending"!==t)return this.log(`No status for keyId ${n} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${t} from other session.`),f(t,e);this.log(`key status for ${n} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),f(r="internal-error",e)},1e3)),this.log(`No status for keyId ${n} (${eC(i)}).`)}};io(e.mediaKeysSession,"message",u),io(e.mediaKeysSession,"keystatuseschange",c);let g=new Promise((e,t)=>{d.on("error",t),d.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${n} URI: ${h}`)}).catch(t=>{throw new sv({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>g).catch(t=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if("string"==typeof r&&"object"==typeof i){let e=r;r=i,i=e}let s="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);e.keySystem===t_.PLAYREADY&&16===s.length&&tb(s);let a=k(s);"internal-error"===i&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i}),t}fetchServerCertificate(e){let t=this.config,i=new t.loader(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((s,a)=>{let n={responseType:"arraybuffer",url:r},h=t.certLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(n,d,{onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,h)=>{a(new sv({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:y({url:n.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{a(new sv({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:n.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{a(Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,s)=>{e.setServerCertificate(i).then(s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),r(e)}).catch(e=>{s(new sv({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new sv({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let i=0,r=s.length;i in key message");return tI(atob(o))}setupLicenseXHR(e,t,i,r){let s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!i.decryptdata)throw Error("Key removed");return s.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)}).then(i=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,s)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let n=new XMLHttpRequest;n.responseType="arraybuffer",n.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(Error("invalid state"));if(4===n.readyState)if(200===n.status){this._requestLicenseFailureCount=0;let t=n.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,n,a,e)}catch(e){this.error(e)}r(t)}else{let h=i.errorRetry,d=h?h.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||n.status>=400&&n.status<500)s(new sv({type:l.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:n,response:{url:a,data:void 0,code:n.status,text:n.statusText}},`License Request XHR failed (${a}). Status: ${n.status} (${n.statusText})`));else{let i=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=n,this.setupLicenseXHR(n,a,e,t).then(({xhr:t,licenseChallenge:i})=>{e.keySystem==t_.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}).catch(s)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,io(i,"encrypted",this.onMediaEncrypted),io(i,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){let e=this.media;e&&(ih(e,"encrypted",this.onMediaEncrypted),ih(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;let t=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,tN.clearKeyUriToKeyIdMap();let r=i.length;sE.CDMCleanupPromise=Promise.all(i.map(e=>this.removeSession(e)).concat((null==t||null==(e=t.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),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: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),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: ${e}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={}}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i,decryptdata:r}=e;if(t){var s;this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${k((null==r?void 0:r.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);let{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(e=>self.clearTimeout(n[e]));let{drmSystemOptions:d}=this.config;return(d&&("persistent-license"===d.sessionType||null!=(s=d.sessionTypes)&&s.some(e=>"persistent-license"===e))?new Promise((e,i)=>{self.setTimeout(()=>i(Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(i)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),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: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),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: ${e}`)})})}return Promise.resolve()}}function sy(e){if(!e)throw Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw Error("keyId is null");return k(e.keyId)}sE.CDMCleanupPromise=void 0;class sv extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=Error(t)),this.data=e,e.err=e.error}}function sT(e,t){let i="output-restricted"===e,r=i?o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:o.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new sv({type:l.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}class sS{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}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(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,s=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,n=1e3*s/e,l=this.hls;if(l.trigger(h.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:i}),n>0&&s>l.config.fpsDroppedMonitoringThreshold*a){let e=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=e)&&(e-=1,l.trigger(h.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:l.currentLevel}),l.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function sA(e,t){let i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function sL(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(i){R.debug(`[texttrack-utils]: ${i}`);try{let i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){R.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function sR(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function sI(e,t,i,r){let s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){let s=function(e,t,i){let r=[],s=function(e,t){let i;if(t<=e[0].startTime)return 0;let r=e.length-1;if(t>e[r].endTime)return -1;let s=0,a=r;for(;s<=a;)if(te[i].startTime)||!(s-1)for(let a=s,n=e.length;a=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)break}return r}(e.cues,t,i);for(let t=0;tthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null,t=sb(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.MANIFEST_PARSED,this.onManifestParsed,this),e.on(h.LEVEL_LOADING,this.onLevelLoading,this),e.on(h.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(h.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(h.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.MANIFEST_PARSED,this.onManifestParsed,this),e.off(h.LEVEL_LOADING,this.onLevelLoading,this),e.off(h.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(h.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(h.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let i=this.media;if(!i)return;let r=!!t.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||sb(i.textTracks).forEach(e=>{sR(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==a?void 0:a.groupId}`);let n=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.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(e=>(null==r?void 0:r.indexOf(e))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;let i=eM(t,e);if(i>-1)s=e[i];else{let e=eM(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null)),this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(h.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:e}),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}{if(i)return null;let r=eM(e,t);if(r>-1)return t[r]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),a=e.details,n=null==a?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${(null==t?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""} ${s}`),this.hls.trigger(h.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let e,{media:t}=this;if(!t)return;let i=sb(t.textTracks),r=this.currentTrack;if(r&&((e=i.filter(e=>r_(r,e))[0])||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(i).forEach(t=>{"disabled"!==t.mode&&t!==e&&(t.mode="disabled")}),e){let t=this.subtitleDisplay?"showing":"hidden";e.mode!==t&&(e.mode=t)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!s(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(h.SUBTITLE_TRACK_SWITCH,{id:e});let a=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&a)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:n,groupId:l="",name:o,type:d,url:u}=r;this.hls.trigger(h.SUBTITLE_TRACK_SWITCH,{id:n,groupId:l,name:o,type:d,url:u});let f=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(f)}}function sk(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}let s_=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});class sP{constructor(e,t){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=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return!(e<=0||isNaN(i))&&(0===i||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i)}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return sC(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=sC(t,e);return t-i<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=s(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return sC(e,t)}return e}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(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t0||null!==this.assetListResponse}toString(){var e;return e=this,`["${e.identifier}" ${e.cue.pre?"
":e.cue.post?"":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}}function sC(e,t){return e-t.startMath.abs(e-(t.start+t.duration)))?t.start:t.start+t.duration}function sO(e,t,i){let r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function sx(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function sw(e){let t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class sM{constructor(e,t,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 e(t);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,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(h.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,s.trigger(h.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=sO(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;let i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,s=tu.bufferInfo(e,r,0);return this.getAssetTime(s.end)>=i-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=tu.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i1/9e4&&this.hls){if(this.hasDetails)throw Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}getAssetTime(e){return Math.min(Math.max(0,e-this.timelineOffset),this.duration)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var r;null==(r=this.hls)||r.on(e,t)}once(e,t,i){var r;null==(r=this.hls)||r.once(e,t)}off(e,t,i){var r;null==(r=this.hls)||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${sw(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class sF extends v{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let r=0;rs.start&&e1)for(let e=0;ei&&(t!n.includes(e.identifier)):[];a.length&&a.sort((e,t)=>{let i=e.cue.pre,r=e.cue.post,s=t.cue.pre,a=t.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=e.startTime,r=t.startTime;if(i!==r)return i-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=a,l.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],i=!1){let r=this.events||[];if(r.length||t.length||this.length<2){let s=this.items,a=this.parseSchedule(r,e);(i||t.length||(null==s?void 0:s.length)!==a.length||a.some((e,t)=>Math.abs(e.playout.start-s[t].playout.start)>.005||Math.abs(e.playout.end-s[t].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,s))}}parseDateRanges(e,t,i){let r=[],s=Object.keys(e);for(let a=0;a!e.error&&!(e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let r=0,l=0;if(e.forEach((t,n)=>{let o=t.cue.pre,h=t.cue.post,d=e[n-1]||null,u=t.appendInPlace,f=h?s:t.startOffset,c=t.duration,g=t.timelineOccupancy===s_.Range?c:0,m=t.resumptionOffset,p=(null==d?void 0:d.startTime)===f,E=f+t.cumulativeDuration,y=u?E+c:f+m;if(o||!h&&f<=0){let e=l;l+=g,t.timelineStart=E;let r=a;a+=c,i.push({event:t,start:E,end:y,playout:{start:r,end:a},integrated:{start:e,end:l}})}else{if(!(f<=s))return;if(!p){let s=f-r;if(s>.033){let o=r,h=l;l+=s;let d=a;a+=s;let u={previousEvent:e[n-1]||null,nextEvent:t,start:o,end:o+s,playout:{start:d,end:a},integrated:{start:h,end:l}};i.push(u)}else s>0&&d&&(d.cumulativeDuration+=s,i[i.length-1].end=f)}h&&(y=E),t.timelineStart=E;let o=l;l+=g;let u=a;a+=c,i.push({event:t,start:E,end:y,playout:{start:u,end:a},integrated:{start:o,end:l}})}let v=t.resumeTime;r=h||v>s?s:v}),r{let h=l.cue.pre,d=l.cue.post,u=h?0:d?r:l.startTime;this.updateAssetDurations(l),n===u?l.cumulativeDuration=a:(a=0,n=u),!d&&l.snapOptions.in&&(l.resumeAnchor=eK(null,i.fragments,l.startOffset+l.resumptionOffset,0,0)||void 0),l.appendInPlace&&!l.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(l,t)||(l.appendInPlace=!1)),!l.appendInPlace&&o+1.025?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let s=t[r].details,a=s.edge;if(i>=a)return this.log(`"${e.identifier}" resumption ${i} past ${r} playlist end ${a}`),!1;let n=eK(null,s.fragments,i);if(!n)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${s.fragStart}-${s.fragmentEnd})`),!0;let l=.175*("audio"===r);return!(Math.abs(n.start-i)<.025+l||Math.abs(n.end-i)<.025+l)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${n.start}-${n.end} sn: ${n.sn} cc: ${n.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,r=!1,s=!1;for(let a=0;a{let a=t.data;if(!Array.isArray(null==a?void 0:a.ASSETS)){let t=this.assignAssetListError(e,o.ASSET_LIST_PARSING_ERROR,Error("Invalid interstitial asset list"),r.url,i,s);this.hls.trigger(h.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(h.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:s})},onError:(t,i,r,s)=>{let a=this.assignAssetListError(e,o.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,s,r);this.hls.trigger(h.ERROR,a)},onTimeout:(t,i,r)=>{let s=this.assignAssetListError(e,o.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,r);this.hls.trigger(h.ERROR,s)}}),this.hls.trigger(h.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,r,s,a){return e.error=i,{type:l.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:a,stats:s}}}function sB(e){null==e||e.play().catch(()=>{})}function s$(e,t){return`[${e}] Advancing timeline position to ${t}`}class sG extends v{constructor(e,t){super("interstitials",e.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},this.onSeeking=()=>{var e,t;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)return void this.checkBuffer();if(s&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(!0),this.checkBuffer(),s&&i=a.end){let t=this.findItemIndex(a),r=this.schedule.findItemIndexAtTime(i);if(-1===r&&(r=t+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${i} (resolving from ${t} to ${r})`)),!this.isInterstitial(a)&&null!=(e=this.media)&&e.paused&&(this.shouldPlay=!1),!s&&r>t){let e=this.schedule.findJumpRestrictedIndex(t+1,r);if(e>t)return void this.setSchedulePosition(e)}this.setSchedulePosition(r);return}let n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(a)){let e=a.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,e))}return}let l=n.timelineStart,o=n.duration||0;(s&&i=l+o)&&(null!=(t=a.event)&&t.appendInPlace&&(this.clearInterstitial(a.event,a),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,n))},this.onTimeupdate=()=>{let e=this.currentTime;if(void 0===e||this.playbackDisabled||!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let i=this.playingAsset;i&&e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{let i=this.schedule;if(!i)return;let r=this.playingItem,s=i.events||[],a=i.items||[],n=i.durations,l=e.map(e=>e.identifier),o=!!(s.length||l.length);(o||t)&&this.log(`INTERSTITIALS_UPDATED (${s.length}): ${s}
Schedule: ${a.map(e=>sN(e))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let d=null,u=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 f=this.bufferingItem;if(f&&(u=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,u)?this.bufferingItem=u:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(r){Math.abs(i)>.025&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),o||t){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 "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(d,r),f&&u!==d&&this.trimInPlace(u,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new sU(e),this.schedule=new sF(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(h.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(h.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(h.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(h.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(h.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(h.BUFFER_APPENDED,this.onBufferAppended,this),e.on(h.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(h.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(h.MEDIA_ENDED,this.onMediaEnded,this),e.on(h.ERROR,this.onError,this),e.on(h.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(h.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(h.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(h.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(h.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(h.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(h.BUFFER_CODECS,this.onBufferCodecs,this),e.off(h.BUFFER_APPENDED,this.onBufferAppended,this),e.off(h.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(h.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(h.MEDIA_ENDED,this.onMediaEnded,this),e.off(h.ERROR,this.onError,this),e.off(h.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.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 e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){ih(e,"play",this.onPlay),ih(e,"pause",this.onPause),ih(e,"seeking",this.onSeeking),ih(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;io(i,"seeking",this.onSeeking),io(i,"timeupdate",this.onTimeupdate),io(i,"play",this.onPlay),io(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(i);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=t=>t?e.getAssetPlayer(t.identifier):t,i=(i,s,a,n,l)=>{if(i){let o=i[s].start,h=i.event;if(h){if("playout"===s||h.timelineOccupancy!==s_.Point){let e=t(a);(null==e?void 0:e.interstitial)===h&&(o+=e.assetItem.startOffset+e[l])}}else o+=("bufferedPos"===n?r():e[n])-i.start;return o}return 0},r=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?s("primary"):Math.max(t,0)},s=t=>{var i,r;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(r=e.schedule)?void 0:r.durations[t])||0},a=(r,s)=>{var a,n;let l=e.effectivePlayingItem;if(null!=l&&null!=(a=l.event)&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${r} "${s}"`);let o=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(r,s),d=null==(n=e.schedule.items)?void 0:n[h],u=e.getBufferingPlayer(),f=null==u?void 0:u.interstitial,c=null==f?void 0:f.appendInPlace,g=o&&e.itemsMatch(o,d);if(o&&(c||g)){let a=t(e.playingAsset),n=(null==a?void 0:a.media)||e.primaryMedia;if(n){let t="primary"===s?n.currentTime:i(o,s,e.playingAsset,"timelinePos","currentTime"),l=r-t,h=(c?t:n.currentTime)+l;if(h>=0&&(!a||c||h<=a.duration)){n.currentTime=h;return}}}if(d){let t=r;if("primary"!==s){let e=r-d[s].start;t=d.start+e}let i=!e.isInterstitial(d);if((!e.isInterstitial(o)||o.event.appendInPlace)&&(i||d.event.appendInPlace)){let i=e.media||(c?null==u?void 0:u.media:null);i&&(i.currentTime=t)}else if(o){let a=e.findItemIndex(o);if(h>a){let t=e.schedule.findJumpRestrictedIndex(a+1,h);if(t>a)return void e.setSchedulePosition(t)}let n=0;if(i)e.timelinePos=t,e.checkBuffer();else{let e=d.event.assetList,t=r-(d[s]||d).start;for(let i=e.length;i--;){let r=e[i];if(r.duration&&t>=r.startOffset&&t{let t=e.effectivePlayingItem;if(e.isInterstitial(t))return t;let i=e.bufferingItem||e.waitingItem;return e.isInterstitial(i)?i:null},l={get bufferedEnd(){let t=e.bufferingItem||e.waitingItem,r=e.bufferingItem;if(r&&r===t){var o;return i(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(o=e.bufferingAsset)?void 0:o.startOffset)||0}return 0},get currentTime(){let t=n(),r=e.effectivePlayingItem;if(r&&r===t)return i(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start;return 0},set currentTime(time){let t=n(),i=e.effectivePlayingItem;i&&i===t&&a(time+i.playout.start,"playout")},get duration(){let e=n();if(e)return e.playout.end-e.playout.start;return 0},get assetPlayers(){var h;let t=null==(h=n())?void 0:h.event.assetList;if(t)return t.map(t=>e.getAssetPlayer(t.identifier));return[]},get playingIndex(){var d;let t=null==(d=n())?void 0:d.event;if(t&&e.effectivePlayingAsset)return t.findAssetIndex(e.effectivePlayingAsset);return -1},get scheduleItem(){return n()}};return this.manager={get events(){var u;return(null==(u=e.schedule)||null==(u=u.events)?void 0:u.slice(0))||[]},get schedule(){var f;return(null==(f=e.schedule)||null==(f=f.items)?void 0:f.slice(0))||[]},get interstitialPlayer(){if(n())return l;return null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return e.bufferingItem||e.waitingItem},get bufferingIndex(){let t=e.bufferingItem||e.waitingItem;return e.findItemIndex(t)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(time){a(time,"primary")},get duration(){return s("primary")},get seekableStart(){var c;return(null==(c=e.primaryDetails)?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(e.bufferingItem||e.waitingItem,"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(time){a(time,"integrated")},get duration(){return s("integrated")},get seekableStart(){var g;return((t,i)=>{var r,s;if(0!==t&&"primary"!==i&&null!=(r=e.schedule)&&r.length){let r=e.schedule.findItemIndexAtTime(t),a=null==(s=e.schedule.items)?void 0:s[r];if(a)return t+(a[i].start-a.start)}return t})((null==(g=e.primaryDetails)?void 0:g.fragmentStart)||0,"integrated")}},skip:()=>{let t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){let r=e.findItemIndex(t);i.appendInPlace?a(t.playout.start+t.event.duration+.001,"playout"):e.advanceAfterAssetEnded(i,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!this.playbackStarted&&!!t&&!!i&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;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!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(r=this.primaryMedia);let a=null==(t=r)?void 0:t.currentTime;if(void 0!==a&&s(a))return a}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!!(null!=e&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${eC(i)}`),this.detachedData=i}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var i,r;let s;if(e.media===t)return;let a=null,n=this.hls,l=e!==n,o=l&&e.interstitial.appendInPlace,h=null==(i=this.detachedData)?void 0:i.mediaSource;if(n.media)o&&(a=n.transferMedia(),this.detachedData=a),s="Primary";else if(h){let e=this.getBufferingPlayer();e?(a=e.transferMedia(),s=`${e}`):s="detached MediaSource"}else s="detached media";if(!a){if(h)a=this.detachedData,this.log(`using detachedData: MediaSource ${eC(a)}`);else if(!this.detachedData||n.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(l&&e.interstitial.appendInPlace!==o){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let d=a&&"mediaSource"in a&&(null==(r=a.mediaSource)?void 0:r.readyState)!=="closed",u=d&&a?a:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${l?e:"Primary"} from ${s} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(u===a&&f){let t=l&&e.assetId===f.assetIdAtEnd;u.overrides={duration:f.duration,endOfStream:!l||t,cueRemoval:!l}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=null==e?void 0:e.events;if(!t||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(s$("checkStart",i)),this.timelinePos=i,t.length&&t[0].cue.pre){let i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){let t=this.timelinePos=i>0?i:0,r=e.findItemIndexAtTime(t);this.setSchedulePosition(r)}}else if(r&&!this.playingItem){let t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let i=e.event,r=i.findAssetIndex(t),s=sx(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var a;let t=null==(a=this.schedule.items)?void 0:a[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,s)}advanceAfterAssetEnded(e,t,i){let r=sx(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let i=this.schedule.items;if(i){let r=t+1;if(r>=i.length)return void this.setSchedulePosition(-1);let s=e.resumeTime;this.timelinePos=0?a[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n?sN(n):n}) pos: ${this.timelinePos}`);let l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){let i=l.event,d=this.playingAsset,u=null==d?void 0:d.identifier,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(l,n)||void 0!==t&&u!==i.assetList[t].identifier)){let t=i.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${i.assetList.length} ${sw(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(h.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:i,schedule:a.slice(0),scheduleIndex:e,player:f}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(u,n),f.media&&!(null!=(r=this.detachedData)&&r.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(l,n)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${sN(l)}`),i.hasPlayed=!0,this.hls.trigger(h.INTERSTITIAL_ENDED,{event:i,schedule:a.slice(0),scheduleIndex:e}),i.cue.once)){this.updateSchedule();let e=null==(s=this.schedule)?void 0:s.items;if(n&&e){let i=this.findItemIndex(n);this.advanceSchedule(i,e,t,l,o)}return}}this.advanceSchedule(e,a,t,l,o)}advanceSchedule(e,t,i,r,s){let a=this.schedule;if(!a)return;let n=t[e]||null,l=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach(t=>{let i=t.interstitial,r=a.findEventIndex(i.identifier);(re+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 t=sx(s,i-1);if(s.isAssetPastPlayoutLimit(t)||s.appendInPlace&&this.timelinePos===n.end)return void this.advanceAfterAssetEnded(s,e,i);i=t}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 ${sN(n)} ${s.appendInPlace?"append in place":""}`),this.hls.trigger(h.INTERSTITIAL_STARTED,{event:s,schedule:t.slice(0),scheduleIndex:e})),!s.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${s}`);if(s.assetListLoader&&(s.assetListLoader.destroy(),s.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${s}`);this.waitingItem=this.endedItem=null,this.playingItem=n;let u=s.assetList[i];if(!u)return void this.advanceAfterAssetEnded(s,e,i||0);if(d||(d=this.getAssetPlayer(u.identifier)),null===d||d.destroyed){let e=s.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${s}`),(d=this.createAssetPlayer(s,u,i)).loadSource()}if(!this.eventItemsMatch(n,this.bufferingItem)&&s.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(d,i,t,e,l),this.shouldPlay&&sB(d.media)}else n?(this.resumePrimary(n,e,r),this.shouldPlay&&sB(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 e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!!(null!=(e=this.primaryDetails)&&e.live)}resumePrimary(e,t,i){var r,s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${sN(e)}`),!(null!=(r=this.detachedData)&&r.mediaSource)){let i=this.timelinePos;(i=e.end)&&(i=this.getPrimaryResumption(e,t),this.log(s$("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;let a=null==(s=this.schedule)?void 0:s.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${sN(e)}`),this.hls.trigger(h.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let i=e.start;if(this.primaryLive){let e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(ie.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:tu.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):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(e,i)),i||(this.log(s$("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.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(e,t){if(-1===t.level||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let r=y(y({},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(e,t){let i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=y(y({},this.altSelection),{},{audio:i});return}let s=y(y({},r),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=y(y({},this.altSelection),{},{subtitles:i});return}let s=y(y({},r),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(e,t){let i=ew(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=ew(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((t,i)=>{e.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(t.identifier,null)});let i=e.end+.25,r=tu.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${sN(e)} (was ${sN(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))}checkBuffer(e){var t;let i=null==(t=this.schedule)?void 0:t.items;if(!i)return;let r=tu.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}updateBufferedPos(e,t,i){let r=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(1===t.length&&this.itemsMatch(t[0],s)){this.bufferedPos=e;return}let a=this.playingItem,n=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos=s.end||null!=(o=a.event)&&o.appendInPlace&&e+.01>=a.start)&&(l=r),this.isInterstitial(s)){let e=s.event;if(r-n>1&&!1===e.appendInPlace||0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,l>i&&l>n)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start{let i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:r,events:s}=i;if(!r||!s)return t;let a=this.isInterstitial(e),n=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=n?n.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${sN(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let t=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,i)=>{let r=this.getAssetPlayer(e.identifier);r&&(i===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(h.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;let t=this.detachedData;t&&t.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){let i=e.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){let e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let i=e.assetUrl,r=e.assetList.length,s=0===r&&!e.assetListLoader,a=e.cue.once;if(s){let s,a=e.timelineStart;if(e.appendInPlace){var n;let t=this.playingItem;this.isInterstitial(t)||(null==t||null==(n=t.nextEvent)?void 0:n.identifier)!==e.identifier||this.flushFrontBuffer(a+.25)}let l=0;if(!this.playingItem&&this.primaryLive&&-1===(l=this.hls.startPosition)&&(l=this.hls.liveSyncPosition||0),l&&!(e.cue.pre||e.cue.post)){let e=l-a;e>0&&(s=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${s?` live-start: ${l} start-offset: ${s}`:""}`),i)return this.createAsset(e,0,0,a,e.duration,i);let o=this.assetListLoader.loadAssetList(e,s);o&&(e.assetListLoader=o)}else if(!a&&r){for(let i=t;i{this.hls.trigger(h.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i1){let i=t.duration;i&&e{if(r.live){var s;let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:l.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},a=(null==(s=this.schedule)?void 0:s.findEventIndex(e.identifier))||-1;this.handleAssetItemError(r,e,a,i,t.message);return}let a=r.edge-r.fragmentStart,n=t.duration;(v||null===n||a>n)&&(v=!1,this.log(`Interstitial asset "${c}" duration change ${n} > ${a}`),t.duration=a,this.updateSchedule())};E.on(h.LEVEL_UPDATED,(e,{details:t})=>T(t)),E.on(h.LEVEL_PTS_UPDATED,(e,{details:t})=>T(t)),E.on(h.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let S=(e,t)=>{let i=this.getAssetPlayer(c);if(i&&t.tracks){i.off(h.BUFFER_CODECS,S),i.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};E.on(h.BUFFER_CODECS,S);let A=()=>{var i;let r=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${r}`),!r||!this.schedule)return;let s=this.schedule.findEventIndex(e.identifier),a=null==(i=this.schedule.items)?void 0:i[s];this.isInterstitial(a)&&this.advanceAssetBuffering(a,t)};E.on(h.BUFFERED_TO_END,A);let L=t=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;let i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return E.once(h.MEDIA_ENDED,L(i)),E.once(h.PLAYOUT_LIMIT_REACHED,L(1/0)),E.on(h.ERROR,(t,r)=>{if(!this.schedule)return;let s=this.getAssetPlayer(c);if(r.details===o.BUFFER_STALLED_ERROR)return null!=s&&s.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${r.error} ${e}`)}),E.on(h.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${c}`),r={fatal:!0,type:l.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),i,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${sw(t)}`),this.hls.trigger(h.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:E}),E}clearInterstitial(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)}),e.reset()}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(-1!==i){let e=this.playerQueue[i];this.log(`clear ${e} toSegment: ${t?sN(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(i,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,r,s){let{interstitial:a,assetItem:n,assetId:l}=e,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 ${t+1}/${o} ${sw(n)}`),this.hls.trigger(h.INTERSTITIAL_ASSET_STARTED,{asset:n,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var i,r;if(!this.schedule)return;let{interstitial:s,assetItem:a}=e,n=this.schedule.findEventIndex(s.identifier),h=null==(i=this.schedule.items)?void 0:i[n];if(!h)return;e.loadSource(),this.setBufferingItem(h),this.bufferingAsset=a;let d=this.getBufferingPlayer();if(d===e)return;let u=s.appendInPlace;if(u&&(null==d?void 0:d.interstitial.appendInPlace)===!1)return;let f=(null==d?void 0:d.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(f&&!b(f,e.tracks)){let t=Error(`Asset ${sw(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(f)}')`),i={fatal:!0,type:l.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},r=s.findAssetIndex(a);this.handleAssetItemError(i,s,n,r,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let r=i.currentTime,s=t.findAssetIndex(e,r),a=e.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 ${l} of ${l+o} in ${n} ${e} (media.currentTime: ${r})`),l&&(o/i.playbackRate<.5||n.bufferedInPlaceToEnd(i))&&n.hls){let i=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,s)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime!e.error))for(let e=r;e{let i=parseFloat(e.DURATION);this.createAsset(a,t,d,o+d,i,e.URI),d+=i}),a.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${h}) ${a}`);let u=this.waitingItem,f=(null==u?void 0:u.event.identifier)===n;this.updateSchedule();let c=null==(r=this.bufferingItem)?void 0:r.event;if(f){let e=this.schedule.findEventIndex(n),t=null==(s=this.schedule.items)?void 0:s[e];if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){a.error=Error(`Interstitial no longer within playback range ${this.timelinePos} ${a}`),this.updateSchedule(!0),this.primaryFallback(a);return}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==c?void 0:c.identifier)===n){let e=a.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(c.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case o.ASSET_LIST_PARSING_ERROR:case o.ASSET_LIST_LOAD_ERROR:case o.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case o.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0)}}}}class sK extends ic{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",c.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(h.LEVEL_LOADED,this.onLevelLoaded,this),e.on(h.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(h.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(h.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(h.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(h.LEVEL_LOADED,this.onLevelLoaded,this),e.off(h.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(h.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(h.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(h.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=iu.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let i,{frag:r,success:s}=t;if(this.fragContextChanged(r)||(M(r)&&(this.fragPrevious=r),this.state=iu.IDLE),!s)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let n=r.start;for(let e=0;e=a[e].start&&n<=a[e].end){i=a[e];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(e,t){let{startOffset:i,endOffset:r}=t;if(0===i&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let i=0;inew e_(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new e_(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,c.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!(null!=(i=this.levels)&&i.length)||-1===this.currentTrackId)return void this.clearInterval();let r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==iu.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i,r;let{currentTrackId:s,levels:a}=this,{details:n,id:l}=t;if(!a)return void this.warn(`Subtitle tracks were reset while loading level ${l}`);let o=a[l];if(l>=a.length||!o)return;this.log(`Subtitle track ${l} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;let e=this.mainDetails;if(!e){this.startFragRequested=!1;return}let t=e.fragments[0];o.details?0===(d=this.alignPlaylists(n,o.details,null==(r=this.levelLastLoaded)?void 0:r.details))&&t&&t5(n,d=t.start):n.hasProgramDateTime&&e.hasProgramDateTime?(il(n,e),d=n.fragmentStart):t&&t5(n,d=t.start),e&&!this.startFragRequested&&this.setStartPosition(e,d)}o.details=n,this.levelLastLoaded=o,l===s&&(this.hls.trigger(h.SUBTITLE_TRACK_UPDATED,{details:n,id:l,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===iu.IDLE&&(eK(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&tA(r.method)){let e=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,tL(r.method)).catch(e=>{throw s.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(i=>{let r=performance.now();s.trigger(h.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=iu.IDLE})}}doTick(){if(!this.media){this.state=iu.IDLE;return}if(this.state===iu.IDLE){let{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;let{config:r}=this,s=this.getLoadPosition(),{end:a,len:n}=tu.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,u=null,f=this.fragPrevious;if(ad-e?0:e))||!f||!(f.start{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}let sH={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},sY=e=>String.fromCharCode(sH[e]||e),sW={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},sj={17:2,18:4,21:6,22:8,23:10,19:13,20:15},sq={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},sX={25:2,26:4,29:6,30:8,31:10,27:13,28:15},sQ=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class sz{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i="function"==typeof t?t():t;R.log(`${this.time} [${e}] ${i}`)}}}let sZ=function(e){let t=[];for(let i=0;i100&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)}moveCursor(e){let t=this.pos+e;if(e>1)for(let e=this.pos+1;e=144&&this.backSpace();let t=sY(e);if(this.pos>=100)return void this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<100;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<100;i++){let r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class s2{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<15;t++)this.rows.push(new s1(e));this.logger=e}reset(){for(let e=0;e<15;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<15;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<15;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+eC(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+eC(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],i="",r=-1;for(let i=0;i<15;i++){let s=this.rows[i].getTextString();s&&(r=i+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class s3{constructor(e,t,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=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new s2(i),this.nonDisplayedMemory=new s2(i),this.lastOutputScreen=new s2(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}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(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;tt+": "+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(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){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 e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};(t.underline=e%2==1,t.italics=e>=46,t.italics)?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+eC(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&!this.displayedMemory.isEmpty()&&(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e)}}class s4{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;let r=this.logger=new sz;this.channels=[null,new s3(e,t,r),new s3(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e"["+sZ([t[e],t[e+1]])+"] -> ("+sZ([d,u])+")");let g=this.cmdHistory;if(d>=16&&d<=31){if(i=d,r=u,(s=g).a===i&&s.b===r){(a=g).a=null,a.b=null,this.logger.log(3,()=>"Repeated command ("+sZ([d,u])+") is dropped");continue}n=d,l=u,(o=this.cmdHistory).a=n,o.b=l,(f=this.parseCmd(d,u))||(f=this.parseMidrow(d,u)),f||(f=this.parsePAC(d,u)),f||(f=this.parseBackgroundAttributes(d,u))}else{(h=g).a=null,h.b=null}if(!f&&(c=this.parseChars(d,u))){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(c):this.logger.log(2,"No channel found yet. TEXT-MODE?")}f||c||this.logger.log(2,()=>"Couldn't parse cleaned data "+sZ([d,u])+" orig: "+sZ([t[e],t[e+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;let i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+sZ([e,t])+")"),!0)}return!1}parsePAC(e,t){let i,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,s=(16===e||24===e)&&t>=64&&t<=95;if(!(r||s))return!1;let a=e<=23?1:2;i=t>=64&&t<=95?1===a?sW[e]:sq[e]:1===a?sj[e]:sX[e];let n=this.channels[a];return!!n&&(n.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0)}interpretPAC(e,t){let i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return r.underline=(1&(i=t>95?t-96:t-64))==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(e,t){let i,r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,()=>"Special char '"+sY(e)+"' in channel "+i),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes =  "+sZ(r).join(",")),r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let i={};return 16===e||24===e?(i.background=sQ[Math.floor((t-32)/2)],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0)),this.channels[e<=23?1:2].setBkgData(i),!0}reset(){var e;for(let e=0;e100)throw Error("Position must be between 0 and 100.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"positionAlign",r({},l,{get:function(){return v},set:function(e){let r=i(t,e);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(e){if(e<0||e>100)throw Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"align",r({},l,{get:function(){return S},set:function(e){let r=i(t,e);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 s8{decode(e,t){if(!e)return"";if("string"!=typeof e)throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function s6(e){function t(e,t,i,r){return(0|e)*3600+(0|t)*60+(0|i)+parseFloat(r||0)}let i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class s9{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r=0&&i<=100)return this.set(e,i),!0}return!1}}function s7(e,t,i,r){let s=r?e.split(r):[e];for(let e in s){if("string"!=typeof s[e])continue;let r=s[e].split(i);if(2===r.length)t(r[0],r[1])}}let ae=new s5(0,0,""),at="middle"===ae.align?"middle":"center";function ai(e){return e.replace(//gi,"\n")}class ar{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new s8,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;function i(){let e=t.buffer,i=0;for(e=ai(e);i=0;r--)if(i[r].id===t){l.set(e,i[r].region);break}break;case"vertical":l.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),l.integer(e,r[0]),l.percent(e,r[0])&&l.set("snapToLines",!1),l.alt(e,r[0],["auto"]),2===r.length&&l.alt("lineAlign",r[1],["start",at,"end"]);break;case"position":r=t.split(","),l.percent(e,r[0]),2===r.length&&l.alt("positionAlign",r[1],["start",at,"end","line-left","line-right","auto"]);break;case"size":l.percent(e,t);break;case"align":l.alt(e,t,["start",at,"end","left","right"])}},/:/,/\s/),t.region=l.get("region",null),t.vertical=l.get("vertical","");let o=l.get("line","auto");"auto"===o&&-1===ae.line&&(o=-1),t.line=o,t.lineAlign=l.get("lineAlign","start"),t.snapToLines=l.get("snapToLines",!0),t.size=l.get("size",100),t.align=l.get("align",at);let h=l.get("position","auto");"auto"===h&&50===ae.position&&(h="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=h}(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let i=-1!==e.indexOf("--\x3e");if(!e||i&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}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(e){this.onparsingerror&&this.onparsingerror(e)}return this.onflush&&this.onflush(),this}}let as=/\r\n|\n\r|\n|\r/g,aa=function(e,t,i=0){return e.slice(i,i+t.length)===t},an=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),a=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!s(t)||!s(i)||!s(r)||!s(a))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*r,t+=36e5*a};function al(e,t,i){return sk(e.toString())+sk(t.toString())+sk(i)}let ao=function(e,t,i){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;null!=(a=s)&&a.new;){var a;e.ccOffset+=r.start-s.start,r.new=!1,s=e[(r=s).prevCC]}e.presentationOffset=i},ah="stpp.ttml.im1t",ad=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,au=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,af={left:"start",center:"center",right:"end",start:"start",end:"end"};function ac(e,t,i,r){let s=Y(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(Error("Could not parse IMSC1 mdat"));let a=s.map(e=>D(e)),n=function(e,t,i=1,r=!1){return rs(e,1,1/i,r)}(t.baseTime,0,t.timescale);try{a.forEach(e=>i(function(e,t){let i=new DOMParser().parseFromString(e,"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((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==i.getAttribute("xml:space"),n=am(ag(i,"styling","style")),l=am(ag(i,"layout","region")),o=ag(i,"body","[begin]");return[].map.call(o,e=>{let i=function e(t,i){return[].slice.call(t.childNodes).reduce((t,r,s)=>{var a;return"br"===r.nodeName&&s?t+"\n":null!=(a=r.childNodes)&&a.length?e(r,i):i?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}(e,a);if(!i||!e.hasAttribute("begin"))return null;let r=ay(e.getAttribute("begin"),s),o=ay(e.getAttribute("dur"),s),h=ay(e.getAttribute("end"),s);if(null===r)throw aE(e);if(null===h){if(null===o)throw aE(e);h=r+o}let d=new s5(r-t,h-t,i);d.id=al(d.startTime,d.endTime,d.text);let u=l[e.getAttribute("region")],f=function(e,t,i){let r="http://www.w3.org/ns/ttml#styling",s=null,a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(s=i[a]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((i,a)=>{let n=ap(t,r,a)||ap(e,r,a)||ap(s,r,a);return n&&(i[a]=n),i},{})}(u,n[e.getAttribute("style")],n),{textAlign:c}=f;if(c){let e=af[c];e&&(d.lineAlign=e),d.align=c}return p(d,f),d}).filter(e=>null!==e)}(e,n)))}catch(e){r(e)}}function ag(e,t,i){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function am(e){return e.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function ap(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function aE(e){return Error(`Could not parse ttml timestamp ${e}`)}function ay(e,t){if(!e)return null;let i=s6(e);return null===i&&(ad.test(e)?i=function(e,t){let i=ad.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return(0|i[1])*3600+(0|i[2])*60+(0|i[3])+r/t.frameRate}(e,t):au.test(e)&&(i=function(e,t){let i=au.exec(e),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/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}class av{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class aT{constructor(e){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=aL(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(h.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(h.FRAG_LOADING,this.onFragLoading,this),e.on(h.FRAG_LOADED,this.onFragLoaded,this),e.on(h.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(h.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(h.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(h.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(h.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(h.FRAG_LOADING,this.onFragLoading,this),e.off(h.FRAG_LOADED,this.onFragLoaded,this),e.off(h.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(h.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(h.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(h.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new av(this,"textTrack1"),t=new av(this,"textTrack2"),i=new av(this,"textTrack3"),r=new av(this,"textTrack4");this.cea608Parser1=new s4(1,e,t),this.cea608Parser2=new s4(3,i,r)}addCues(e,t,i,r,s){let a=!1;for(let e=s.length;e--;){var n,l;let r=s[e],o=(n=r[0],l=r[1],Math.min(l,i)-Math.max(n,t));if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),a=!0,o/(i-t)>.5))return}if(a||s.push([t,i]),this.config.renderTextTracksNatively){let s=this.captionsTracks[e];this.Cues.newCue(s,t,i,r)}else{let s=this.Cues.newCue(null,t,i,r);this.hls.trigger(h.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s,trackId:a}){let{unparsedVttFrags:n}=this;i===c.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:s,trackId:a}),n.length&&(this.unparsedVttFrags=[],n.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(h.FRAG_LOADED,e):this.hls.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r{sR(r[e]),delete r[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=aL(),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:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let e=0;ee.textCodec===ah);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(rD(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let e=this.media,t=e?sb(e.textTracks):null;if(this.tracks.forEach((e,i)=>{let r;if(t){let i=null;for(let r=0;rnull!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(h.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===c.MAIN){var i,r;let{cea608Parser1:e,cea608Parser2:s,lastSn:a}=this,{cc:n,sn:l}=t.frag,o=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;e&&s&&(l!==a+1||l===a&&o!==this.lastPartIndex+1||n!==this.lastCc)&&(e.reset(),s.reset()),this.lastCc=n,this.lastSn=l,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===c.SUBTITLE)if(r.byteLength){let e=i.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){let e=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),e&&e.textCodec===ah?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;ac(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),i.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:s,unparsedVttFrags:a}=this,n=s.length-1;if(!s[i.cc]&&-1===n)return void a.push(e);let l=this.hls;!function(e,t,i,r,s,a,n){let l,o=new ar,h=D(new Uint8Array(e)).trim().replace(as,"\n").split("\n"),d=[],u=t?function(e,t=1){return rs(e,9e4,1/t)}(t.baseTime,t.timescale):0,f="00:00.000",c=0,g=0,m=!0;o.oncue=function(e){let a=i[r],n=i.ccOffset,o=(c-u)/9e4;if(null!=a&&a.new&&(void 0!==g?n=i.ccOffset=a.start:ao(i,r,o)),o){if(!t){l=Error("Missing initPTS for VTT MPEGTS");return}n=o-i.presentationOffset}let h=e.endTime-e.startTime,f=ru((e.startTime+n-g)*9e4,9e4*s)/9e4;e.startTime=Math.max(f,0),e.endTime=Math.max(f+h,0);let m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=al(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){l=e},o.onflush=function(){if(l)return void n(l);a(d)},h.forEach(e=>{if(m)if(aa(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach(e=>{aa(e,"LOCAL:")?f=e.slice(6):aa(e,"MPEGTS:")&&(c=parseInt(e.slice(7)))});try{g=an(f)/1e3}catch(e){l=e}return}else""===e&&(m=!1);o.parse(e+"\n")}),o.flush()}(null!=(t=i.initSegment)&&t.data?J(i.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,e=>{this._appendCues(e,i.level),l.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},t=>{let s="Missing initPTS for VTT MPEGTS"===t.message;s?a.push(e):this._fallbackToIMSC1(i,r),l.logger.log(`Failed to parse VTT cue: ${t}`),s&&n>i.cc||l.trigger(h.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||ac(t,this.initPTS[e.cc],()=>{i.textCodec=ah,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(e=>sL(i,e))}else{let r=this.tracks[t];if(!r)return;let s=r.default?"default":"subtitles"+t;i.trigger(h.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===c.SUBTITLE&&this.onFragLoaded(h.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=t;if(i.type!==c.MAIN||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;esI(e[r],t,i))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){let{textTracks:e}=this;Object.keys(e).forEach(i=>sI(e[i],t,r))}}}extractCea608Data(e){let t=[[],[]],i=31&e[0],r=2;for(let s=0;s=16?l--:l++;let r=ai(o.trim()),c=al(t,i,r);null!=e&&null!=(u=e.cues)&&u.getCueById(c)||((a=new d(t,i,r)).id=c,a.line=f+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),h.push(a))}return e&&h.length&&(h.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),h.forEach(t=>sL(e,t))),h}},ab=/(\d+)-(\d+)\/(\d+)/;class aD{constructor(e){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=e.fetchSetup||ak,this.controller=new self.AbortController,this.stats=new O}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 e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,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(e,t){let i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(p({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(e,this.controller.signal),n="arraybuffer"===e.responseType,l=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=o&&s(o)?o:h,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(rT(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),t.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},h-(l-r.loading.start)),!i.ok){let{status:e,statusText:t}=i;throw new a_(t||"fetch, bad network response",e,i)}r.loading.first=l,r.total=function(e){let t=e.get("Content-Range");if(t){let e=function(e){let t=ab.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(s(e))return e}let i=e.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(t.highWaterMark)?this.loadProgressively(i,r,e,t.highWaterMark,o):n?i.arrayBuffer():"json"===e.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},u=null==(a=this.callbacks)?void 0:a.onProgress;u&&!s(t.highWaterMark)&&u(r,e,i,o),null==(n=this.callbacks)||n.onSuccess(d,r,e,o)}).catch(t=>{var i;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let s=t&&t.code||0,a=t?t.message:null;null==(i=this.callbacks)||i.onError({code:s,text:a},e,t?t.details:null,r)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){let a=new im,n=e.body.getReader(),l=()=>n.read().then(n=>{if(n.done)return a.dataLength&&s(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let o=n.value,h=o.length;return t.loaded+=h,h=r&&s(t,i,a.flush().buffer,e)):s(t,i,o.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function ak(e,t){return new self.Request(e.url,t)}class a_ extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}let aP=/^age:\s*[\d.]+\s*$/im;class aC{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new O,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)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,t.url)}).catch(e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(e=>{var s;null==(s=this.callbacks)||s.onError({code:i.status,text:e.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:a,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=a&&s(a)?a:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.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),t.onreadystatechange=null,t.onprogress=null;let r=t.status,o="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){let s=null!=o?o:t.response;if(null!=s){i.loading.end=Math.max(self.performance.now(),i.loading.first),i.loaded=i.total="arraybuffer"===t.responseType?s.byteLength:s.length,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);let l=null==(a=this.callbacks)?void 0:a.onProgress;l&&l(i,e,s,t);let o={url:t.responseURL,data:s,code:r};null==(n=this.callbacks)||n.onSuccess(o,i,e,t);return}}let h=s.loadPolicy.errorRetry;ez(h,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(h):(R.error(`${r} while loading ${e.url}`),null==(l=this.callbacks)||l.onError({code:r,text:t.statusText},e,t,i))}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry;if(ez(e,this.stats.retry,!0))this.retry(e);else{var t;R.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=eX(e,i.retry),i.retry++,R.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&aP.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}let aO=y(y({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,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,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:aC,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:e$,bufferController:rM,capLevelController:rU,errorController:e1,fpsController:sS,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:tw,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:aI,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:sK,subtitleTrackController:sD,timelineController:aT,audioStreamController:rI,audioTrackController:rP,emeController:sE,cmcdController:sc,contentSteeringController:sg,interstitialsController:sG});class ax extends tl{constructor(e,t){super("gap-controller",e.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 e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var e;this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(h.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(h.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(h.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;let i=this.media=t.media;io(i,"playing",this.onMediaPlaying),io(i,"waiting",this.onMediaWaiting),io(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(ih(i,"playing",this.onMediaPlaying),ih(i,"waiting",this.onMediaWaiting),ih(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!(null!=(e=this.media)&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){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,u=n.paused&&!l||n.ended||0===n.playbackRate;if(this.seeking=l,e!==t){t&&(this.ended=0),this.moved=!0,!l&&(this.nudgeRetry=0,a.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),0===this.waiting&&this.stallResolved(e);return}if(d||o){o&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(h.MEDIA_ENDED,{stalled:!1}));return}if(!tu.getBuffered(n).length){this.nudgeRetry=0;return}let f=tu.bufferInfo(n,e,0),c=f.nextStart||0,g=this.fragmentTracker;if(l&&g&&this.hls){let t=aw(this.hls.inFlightFragments,e),i=f.len>2,r=!c||t||c-e>2&&!g.getPartialFragment(e);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(!(f.len>0)&&!c)return;let t=Math.max(c,f.start||0)-e,i=null!=m&&m.live?2*m.targetduration:2,r=aF(e,g);if(t>0&&(t<=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||y)&&this.hls){if((null==(s=this.mediaSource)?void 0:s.readyState)==="ended"&&!(null!=m&&m.live)&&1>Math.abs(e-((null==m?void 0:m.edge)||0))){if(this.ended)return;this.ended=e||1,this.hls.trigger(h.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(f),!this.media||!this.hls)return}let S=tu.bufferInfo(n,e,a.maxBufferHole);this._tryFixBufferStall(S,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(h.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){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&&e>r.end(0)){let i=tu.bufferedInfo(tu.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){let i=tu.timeRangesToArray(r),s=tu.bufferedInfo(i,t,0).bufferedIndex;if(s>-1&&ss)&&a-r<1&&e-r<2){let i=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;let s=aF(e,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);let n=tu.bufferInfo(this.media,e,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(e,t,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=aF(i,a);if((h||null!=o&&o.live&&i1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i1e3*l.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,r=e.nextStart;if(i&&r){let e=i.getFragAtPos(t,c.MAIN),s=i.getFragAtPos(r,c.MAIN);if(e&&s)return s.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:r,stalled:s}=this;if(!r&&null!==s&&i&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${i.currentTime} due to low buffer (${eC(e)})`);this.warn(r.message),t.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t,i;let{fragmentTracker:r,media:s}=this,a=null==(t=this.hls)?void 0:t.config;if(!s||!r||!a)return 0;let n=s.currentTime,d=tu.bufferInfo(s,n,0),u=n0&&d.len<1&&s.readyState<3,g=u-n;if(g>0&&(t||f)){if(g>a.maxBufferHole){let t=!1;if(0===n){let e=r.getAppendedFrag(0,c.MAIN);e&&u{let e=aN();try{e&&new e(0,1/0,"")}catch(e){return Number.MAX_VALUE}return 1/0})();class a${constructor(e){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=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(h.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(h.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(h.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(h.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(h.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(h.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(h.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,(null==(i=t.overrides)?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;let t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&sR(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;taB&&(o=aB),o-l<=0&&(o=l+.25);for(let e=0;ee.type===iw.audioId3&&l:"video"===r?e=>e.type===iw.emsg&&n:e=>e.type===iw.audioId3&&l||e.type===iw.emsg&&n)}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){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=aN();if(a&&n&&!o){let{fragmentStart:t,fragmentEnd:i}=e,r=this.assetCue;r?(r.startTime=t,r.endTime=i):h&&(r=this.assetCue=aU(h,t,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(!e.hasProgramDateTime)return;let{id3Track:d}=this,{dateRanges:u}=e,f=Object.keys(u),c=this.dateRangeCuesAppended;if(d&&t)if(null!=(i=d.cues)&&i.length){let e=Object.keys(c).filter(e=>!f.includes(e));for(let t=e.length;t--;){let i=e[t],s=null==(r=c[i])?void 0:r.cues;delete c[i],s&&Object.keys(s).forEach(e=>{let t=s[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{d.removeCue(t)}catch(e){}}})}}else c=this.dateRangeCuesAppended={};let g=e.fragments[e.fragments.length-1];if(0!==f.length&&s(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e{if(t!==i.id){let r=u[t];if(r.class===i.class&&r.startDate>i.startDate&&(!e||i.startDate.01&&(u.startTime=r,u.endTime=l);else if(h){let e=i.attr[d];("SCTE35-OUT"===d||"SCTE35-IN"===d||"SCTE35-CMD"===d)&&(e=_(e));let s=aU(h,r,l,{key:d,data:e},iw.dateRange);s&&(s.id=t,this.id3Track.addCue(s),a[d]=s,o&&("X-ASSET-LIST"===d||"X-ASSET-URL"===d)&&s.addEventListener("enter",this.onEventCueEnter))}}c[t]={cues:a,dateRange:i,durationKnown:n}}}}}class aG{constructor(e){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:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;let i=this.computeLatency();if(null===i)return;this._latency=i;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!t.live)return;let a=this.targetLatency;if(null===a)return;let n=i-a;if(n.05&&this.forwardBufferLength>1){let t=Math.min(Math.min(2,Math.max(1,s)),Math.max(1,Math.round(2/(1+Math.exp(-.75*n-this.edgeStalled))*20)/20));this.changeMediaPlaybackRate(e,t)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(null===e||null===this.hls)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:n}=this.config,l=this.hls.userConfig,o=n&&i||t;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(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;let i=this.levelDetails;if(null===i)return null;let r=i.edge,s=e-t-this.edgeStalled;return Math.min(Math.max(r-i.totalduration,s),r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration))}get drift(){let e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(null===e)return 0;let t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(h.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(h.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(h.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(h.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.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(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.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(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(r=this.targetLatency)?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class aK extends rb{constructor(e,t){super(e,"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=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(h.LEVEL_LOADED,this.onLevelLoaded,this),e.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(h.FRAG_BUFFERED,this.onFragBuffered,this),e.on(h.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(h.LEVEL_LOADED,this.onLevelLoaded,this),e.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(h.FRAG_BUFFERED,this.onFragBuffered,this),e.off(h.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],s={},a={},n=!1,l=!1,o=!1;t.levels.forEach(e=>{let t=e.attrs,{audioCodec:h,videoCodec:d}=e;h&&(e.audioCodec=h=eg(h,i)||void 0),d&&(d=e.videoCodec=function(e){let t=e.split(",");for(let e=0;e2&&"avc1"===i[0]&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}(d));let{width:u,height:f,unknownCodecs:c}=e,g=(null==c?void 0:c.length)||0;if(n||(n=!!(u&&f)),l||(l=!!d),o||(o=!!h),g||h&&!this.isAudioSupported(h)||d&&!this.isVideoSupported(d))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);let{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":E,"PATHWAY-ID":y,RESOLUTION:v,"VIDEO-RANGE":T}=t,S=`${y||"."}-`,A=`${S}${e.bitrate}-${v}-${p}-${m}-${T}-${E}`;if(s[A])if(s[A].uri===e.url||e.attrs["PATHWAY-ID"])s[A].addGroupId("audio",t.AUDIO),s[A].addGroupId("text",t.SUBTITLES);else{let t=a[A]+=1;e.attrs["PATHWAY-ID"]=Array(t+1).join(".");let i=this.createLevel(e);s[A]=i,r.push(i)}else{let t=this.createLevel(e);s[A]=t,a[A]=1,r.push(t)}}),this.filterAndSortMediaOptions(r,t,n,l,o)}createLevel(e){let t=new e_(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=eS(e,[])}return t}isAudioSupported(e){return el(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return el(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,r,s){var a,n;let d=[],u=[],f=e,c=(null==(a=t.stats)?void 0:a.parsing)||{};if((i||r)&&s&&(f=f.filter(({videoCodec:e,videoRange:t,width:i,height:r})=>{var s;return(!!e||!!(i&&r))&&!!(s=t)&&eI.indexOf(s)>-1})),0===f.length){Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${eC(t.levels.map(e=>e.attrs.CODECS).filter((e,t,i)=>i.indexOf(e)===t))}`,this.warn(i),e+=` (${i})`);let r=Error(e);this.hls.trigger(h.ERROR,{type:l.MEDIA_ERROR,details:o.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}),c.end=performance.now();return}t.audioTracks&&aV(d=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),t.subtitles&&aV(u=t.subtitles);let g=f.slice(0);f.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return eI.indexOf(e.videoRange)-eI.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let i=ed(e.videoCodec),r=ed(t.videoCodec);if(i!==r)return r-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let i=eu(e.codecSet),r=eu(t.codecSet);if(i!==r)return r-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let m=g[0];if(this.steering&&(f=this.steering.filterParsedLevels(f)).length!==g.length){for(let e=0;ei&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let p=s&&!r,E=this.hls.config,y=!!(E.audioStreamController&&E.audioTrackController),v={levels:f,audioTracks:d,subtitleTracks:u,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:y&&!p&&d.some(e=>!!e.url)};c.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(e){let t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){let i=Error("invalid level idx"),r=e<0;if(this.hls.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],n=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&r&&s===n)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${n?" with Pathway "+n:""} from level ${i}${s?" with Pathway "+s:""}`);let d={level:e,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 u=a.details;if(!u||u.live){let e=this.switchParams(a.uri,null==r?void 0:r.details,u);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){let e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===f.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===c.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i,r;let{level:s,details:a}=t,n=t.levelInfo;if(!n){this.warn(`Invalid level index ${s}`),null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(s,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],a=e.details,n=null==a?void 0:a.age;this.log(`Loading level index ${r}${(null==t?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""} ${i}`),this.hls.trigger(h.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return -1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;let i=this._levels.filter((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));ie(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.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(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(h.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function aV(e){let t={};e.forEach(e=>{let i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function aH(){return self.SourceBuffer||self.WebKitSourceBuffer}function aY(){if(!I())return!1;let e=aH();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class aW extends ic{constructor(e,t,i){super(e,t,i,"stream-controller",c.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 e=this.media,t=e?e.currentTime:null;if(null===t||!s(t)||(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t)))return;let i=this.getFwdBufferInfoAtPos(e,t,c.MAIN,0);if(null===i||0===i.len)return void this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`);this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(h.MANIFEST_PARSED,this.onManifestParsed,this),e.on(h.LEVEL_LOADING,this.onLevelLoading,this),e.on(h.LEVEL_LOADED,this.onLevelLoaded,this),e.on(h.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(h.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(h.BUFFER_CREATED,this.onBufferCreated,this),e.on(h.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(h.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(h.MANIFEST_PARSED,this.onManifestParsed,this),e.off(h.LEVEL_LOADED,this.onLevelLoaded,this),e.off(h.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(h.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(h.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(h.BUFFER_CREATED,this.onBufferCreated,this),e.off(h.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(h.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=iu.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=iu.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case iu.WAITING_LEVEL:{let{levels:e,level:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(!r||r.live&&(this.levelLastLoaded!==i||this.waitForLive(i)))this.hls.nextLoadLevel!==this.level&&(this.state=iu.IDLE);else{if(this.waitForCdnTuneIn(r))break;this.state=iu.IDLE}break}case iu.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===iu.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(null===t||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let s=this.buffering?e.nextLoadLevel:e.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 e={};2===this.altAudio&&(e.type="video"),this.hls.trigger(h.BUFFER_EOS,e),this.state=iu.ENDED;return}if(!this.buffering)return;e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;let o=a.details;if(!o||this.state===iu.WAITING_LEVEL||this.waitForLive(a)){this.level=s,this.state=iu.WAITING_LEVEL,this.startFragRequested=!1;return}let d=n.len,u=this.getMaxBufferLength(a.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>n.end&&(this.backtrackFragment=null);let f=this.backtrackFragment?this.backtrackFragment.start:n.end,g=this.getNextFragment(f,o);if(this.couldBacktrack&&!this.fragPrevious&&g&&M(g)&&this.fragmentTracker.getState(g)!==e3.OK){var m;let e=(null!=(m=this.backtrackFragment)?m:g).sn-o.startSN,t=o.fragments[e-1];t&&g.cc===t.cc&&(g=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&n.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){let e=this.audioOnly&&!this.altAudio?x.AUDIO:x.VIDEO,t=(e===x.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,c.MAIN)}g=this.getNextFragmentLoopLoading(g,o,n,c.MAIN,u)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,a,f))}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);r===e3.NOT_LOADED||r===e3.PARTIAL?M(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,c.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0)}nextLevelSwitch(){let{levels:e,media:t}=this;if(null!=t&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let s=this.getLevelDetails();if(null!=s&&s.live){let e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){let t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(a.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,1/0)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case iu.KEY_LOADING:case iu.FRAG_LOADING:case iu.FRAG_LOADING_WAITING_RETRY:case iu.PARSING:case iu.PARSED:this.state=iu.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;io(i,"playing",this.onMediaPlaying),io(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(ih(i,"playing",this.onMediaPlaying),ih(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),t.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(e,t){let i=!1,r=!1;for(let e=0;e=a-t.maxFragLookUpTolerance&&s<=n;if(null!==r&&i.duration>r&&(s{this.hls&&this.hls.trigger(h.AUDIO_TRACK_SWITCHED,t)}),i.trigger(h.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}i.trigger(h.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=eB(t.url,this.hls);if(i){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=2*!!i,this.tick()}onBufferCreated(e,t){let i,r,s=t.tracks,a=!1;for(let e in s){let t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){let t=s[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t,s=i.type===c.MAIN;if(s){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===iu.PARSED&&(this.state=iu.IDLE);return}let e=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),M(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}let a=this.media;a&&(!this._hasEnoughToStart&&tu.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=iu.ERROR;return}switch(t.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(c.MAIN,t);break;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==iu.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==f.LEVEL||(this.state=iu.IDLE);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case o.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=iu.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==x.AUDIO||!this.altAudio){let e=(t===x.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,c.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t0&&(l{let{hls:i}=this,r=null==e?void 0:e.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=iu.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,e),r.bitrateTest=!1}).catch(t=>{this.state!==iu.STOPPED&&this.state!==iu.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,n=this.getCurrentContext(a);if(!n)return void this.resetWhenMissingContext(a);let{frag:l,part:o,level:d}=n,{video:u,text:f,id3:c,initSegment:g}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l))return void this.fragmentTracker.removeFragment(l);if(this.state=iu.PARSING,g){let e=g.tracks;if(e){let r=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(d,e,r,a),i.trigger(h.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=g.initPTS,n=g.timescale,o=this.initPTS[l.cc];if(s(r)&&(!o||o.baseTime!==r||o.timescale!==n)){let e=g.trackId;this.initPTS[l.cc]={baseTime:r,timescale:n,trackId:e},i.trigger(h.INIT_PTS_FOUND,{frag:l,id:t,initPTS:r,timescale:n,trackId:e})}}if(u&&m){p&&"audiovideo"===u.type&&this.logMuxedErr(l);let e=m.fragments[l.sn-1-m.startSN],t=l.sn===m.startSN,i=!e||l.cc>e.cc;if(!1!==r.independent){let{startPTS:e,endPTS:r,startDTS:s,endDTS:n}=u;if(o)o.elementaryStreams[u.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:n};else if(u.firstKeyFrame&&u.independent&&1===a.id&&!i&&(this.couldBacktrack=!0),u.dropped&&u.independent){let s=this.getMainFwdBufferInfo(),a=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,o=u.firstKeyFramePTS?u.firstKeyFramePTS:e;if(!t&&a2&&(l.gap=!0);l.setElementaryStreamInfo(u.type,e,r,s,n),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,o,a,t||i)}else{if(!t&&!i)return void this.backtrack(l);l.gap=!0}}if(p){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=p;o&&(o.elementaryStreams[x.AUDIO]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(x.AUDIO,e,t,i,r),this.bufferFragmentData(p,l,o,a)}if(m&&null!=c&&c.samples.length){let e={id:t,frag:l,details:m,samples:c.samples};i.trigger(h.FRAG_PARSING_METADATA,e)}if(m&&f){let e={id:t,frag:l,details:m,samples:f.samples};i.trigger(h.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${M(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,r){if(this.state!==iu.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:s,video:a,audiovideo:n}=t;if(s){let i=e.audioCodec,r=em(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 e=s.metadata;e&&"channelCount"in e&&1!==(e.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 ${r}`)),i&&i!==r&&this.log(`Swapping manifest audio codec "${i}" for "${r}"`),s.levelCodec=r,s.id=c.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${r||""}/${i||""}/${s.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=c.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:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${a.codec!==i?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}n&&(this.log(`Init audiovideo buffer, container:${n.container}, codecs[level/parsed]=[${e.codecs}/${n.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(h.BUFFER_CODECS,t),!this.hls)return;l.forEach(e=>{let s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(h.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,c.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=iu.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){let i=e.currentTime;if(tu.isBuffered(e,i)?t=this.getAppendedFrag(i):tu.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,i=t.level;(!e||t.sn!==e.sn||e.level!==i)&&(this.fragPlaying=t,this.hls.trigger(h.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(h.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return s(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(s(t)){let e=this.getLevelDetails(),i=this.currentFrag||(e?eK(null,e.fragments,t):null);if(i){let e=i.programDateTime;if(null!==e)return new Date(e+(t-i.start)*1e3)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class aj extends v{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[i].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){for(let e in this.detach(),this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=o.KEY_LOAD_ERROR,i,r,s){return new tn({type:l.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,s=t.length;r{if(!this.emeController)return;a.setKeyFormat(e);let t=tC(e);if(t)return this.emeController.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=tx(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let s=e.decryptdata;if(!s){let i=Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,o.KEY_LOAD_ERROR,i))}let a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,o.KEY_LOAD_ERROR,Error(`Invalid key URI: "${a}"`)));let n=aq(s),l=this.keyIdToKeyInfo[n];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,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(t=>{let{keyInfo:i}=t;return s.key=i.decryptdata.key,{frag:e,keyInfo:i}})}switch(this.log(`${this.keyIdToKeyInfo[n]?"Rel":"L"}oading${s.keyId?" keyId: "+k(s.keyId):""} URI: ${s.uri} from ${e.type} ${e.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,e);return this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,o.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&null!=(r=t.initSegment)&&r.data){let i=function(e){let t=[];return z(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(i.length){let t=i[0];t.some(e=>0!==e)&&(this.log(`Using keyId found in init segment ${k(t)}`),e.decryptdata.keyId=t,tN.setKeyIdForUri(e.decryptdata.uri,t))}}return(e.keyLoadPromise=this.emeController.loadKey(i).then(t=>(e.mediaKeySessionContext=t,i))).catch(i=>{throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=new i.loader(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((s,a)=>{let n={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(n,h,{onSuccess:(e,t,i,r)=>{let{frag:n,keyInfo:l}=i,h=aq(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(e.data),n.keyLoader=null,l.loader=null,s({frag:n,keyInfo:l})},onError:(e,i,r,s)=>{this.resetLoader(i),a(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,Error(`HTTP Error ${e.code} loading key ${e.text}`),r,y({url:n.url,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),a(this.createKeyLoadError(t,o.KEY_LOAD_TIMEOUT,Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),a(this.createKeyLoadError(t,o.INTERNAL_ABORTED,Error("key loading aborted"),r))}})})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null);let a=aq(i.decryptdata)||r;delete this.keyIdToKeyInfo[a],s&&s.destroy()}}function aq(e){if(e.keyFormat!==tP.FAIRPLAY){let t=e.keyId;if(t)return k(t)}return e.uri}function aX(e){let{type:t}=e;switch(t){case f.AUDIO_TRACK:return c.AUDIO;case f.SUBTITLE_TRACK:return c.SUBTITLE;default:return c.MAIN}}function aQ(e,t){let i=e.url;return(void 0===i||0===i.indexOf("data:"))&&(i=t.url),i}class az{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(h.MANIFEST_LOADING,this.onManifestLoading,this),e.on(h.LEVEL_LOADING,this.onLevelLoading,this),e.on(h.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(h.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(h.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(h.MANIFEST_LOADING,this.onManifestLoading,this),e.off(h.LEVEL_LOADING,this.onLevelLoading,this),e.off(h.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(h.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(h.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:f.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:r,pathwayId:s,url:a,deliveryDirectives:n,levelInfo:l}=t;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:f.LEVEL,url:a,deliveryDirectives:n,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:a,track:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:f.AUDIO_TRACK,url:s,deliveryDirectives:a,levelOrTrack:n})}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:a,track:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:f.SUBTITLE_TRACK,url:s,deliveryDirectives:a,levelOrTrack:n})}onLevelsUpdated(e,t){let i=this.loaders[f.LEVEL];if(i){let e=i.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(i.abort(),delete this.loaders[f.LEVEL])}}load(e){var t;let i,r=this.hls.config,a=this.getInternalLoader(e);if(a){let t=this.hls.logger,i=a.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),a.abort()}if(i=e.type===f.MANIFEST?r.manifestLoadPolicy.default:p({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(e),s(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===f.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===f.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===f.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,r=t.targetduration;if(e&&r){let t=1e3*Math.max(3*e,.8*r);i=p({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,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(e,l,{onSuccess:(e,t,i,r)=>{let s=this.getInternalLoader(i);this.resetInternalLoader(i.type);let a=e.data;t.parsing.start=performance.now(),tH.isMediaPlaylist(a)||i.type!==f.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r)},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}})}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,r){let s=this.hls,a=e.data,n=aQ(e,i),l=tH.parseMasterPlaylist(a,n);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:o,levels:d,sessionData:u,sessionKeys:f,startTimeOffset:c,variableList:g}=l;this.variableList=g,d.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:i}=this.hls.config,{audioCodec:r,videoCodec:s}=e;for(let a=t.length;a--;){let n=t[a];el(n,"audio",i)?(e.audioCodec=r=r?`${r},${n}`:n,ea.audio[r.substring(0,4)]=2,t.splice(a,1)):el(n,"video",i)&&(e.videoCodec=s=s?`${s},${n}`:n,ea.video[s.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":E}=tH.parseMasterPlaylistMedia(a,n,l);m.length&&(m.some(e=>!e.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 tE({}),bitrate:0,url:""}))),s.trigger(h.MANIFEST_LOADED,{levels:d,audioTracks:m,subtitles:p,captions:E,contentSteering:o,url:n,stats:t,networkDetails:r,sessionData:u,sessionKeys:f,startTimeOffset:c,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,r,a){let n=this.hls,{id:l,level:o,type:d}=i,u=aQ(e,i),c=s(o)?o:s(l)?l:0,g=aX(i),m=tH.parseLevelPlaylist(e.data,u,c,g,0,this.variableList);if(d===f.MANIFEST){let e={attrs:new tE({}),bitrate:0,details:m,name:"",url:u};m.requestScheduled=t.loading.start+t8(m,0),n.trigger(h.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,e,t,i,r,a)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(h.ERROR,{type:l.NETWORK_ERROR,details:o.MANIFEST_PARSING_ERROR,fatal:t.type===f.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===f.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===f.AUDIO_TRACK||e.type===f.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let n=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let d=o.UNKNOWN,u=!1,c=this.getInternalLoader(e);switch(e.type){case f.MANIFEST:d=i?o.MANIFEST_LOAD_TIMEOUT:o.MANIFEST_LOAD_ERROR,u=!0;break;case f.LEVEL:d=i?o.LEVEL_LOAD_TIMEOUT:o.LEVEL_LOAD_ERROR,u=!1;break;case f.AUDIO_TRACK:d=i?o.AUDIO_TRACK_LOAD_TIMEOUT:o.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case f.SUBTITLE_TRACK:d=i?o.SUBTITLE_TRACK_LOAD_TIMEOUT:o.SUBTITLE_LOAD_ERROR,u=!1}c&&this.resetInternalLoader(e.type);let g={type:l.NETWORK_ERROR,details:d,fatal:u,url:e.url,loader:c,context:e,error:n,networkDetails:t,stats:s};r&&(g.response=y({url:(null==t?void 0:t.url)||e.url,data:void 0},r)),this.hls.trigger(h.ERROR,g)}handlePlaylistLoaded(e,t,i,r,s,a){let n=this.hls,{type:d,level:u,levelOrTrack:g,id:m,groupId:p,deliveryDirectives:E}=r,y=aQ(t,r),v=aX(r),T="number"==typeof r.level&&v===c.MAIN?u:void 0,S=e.playlistParsingError;if(S){if(this.hls.logger.warn(`${S} ${e.url}`),!n.config.ignorePlaylistParsingErrors)return void n.trigger(h.ERROR,{type:l.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:y,error:S,reason:S.message,response:t,context:r,level:T,parent:v,networkDetails:s,stats:i});e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error("No Segments found in Playlist");n.trigger(h.ERROR,{type:l.NETWORK_ERROR,details:o.LEVEL_EMPTY_ERROR,fatal:!1,url:y,error:a,reason:a.message,response:t,context:r,level:T,parent:v,networkDetails:s,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),d){case f.MANIFEST:case f.LEVEL:if(T)if(g){if(g!==n.levels[T]){let e=n.levels.indexOf(g);e>-1&&(T=e)}}else T=0;n.trigger(h.LEVEL_LOADED,{details:e,levelInfo:g||n.levels[0],level:T||0,id:m||0,stats:i,networkDetails:s,deliveryDirectives:E,withoutMultiVariant:d===f.MANIFEST});break;case f.AUDIO_TRACK:n.trigger(h.AUDIO_TRACK_LOADED,{details:e,track:g,id:m||0,groupId:p||"",stats:i,networkDetails:s,deliveryDirectives:E});break;case f.SUBTITLE_TRACK:n.trigger(h.SUBTITLE_TRACK_LOADED,{details:e,track:g,id:m||0,groupId:p||"",stats:i,networkDetails:s,deliveryDirectives:E})}}}class aZ{static get version(){return iy}static isMSESupported(){return aY()}static isSupported(){if(!aY())return!1;let e=I();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(eh(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(eh(t,"audio"))))}static getMediaSource(){return I()}static get Events(){return h}static get MetadataSchema(){return iw}static get ErrorTypes(){return l}static get ErrorDetails(){return o}static get DefaultConfig(){return aZ.defaultConfig?aZ.defaultConfig:aO}static set DefaultConfig(e){aZ.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new iE,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 t=this.logger=function(e,t,i){let r=A();if("object"==typeof console&&!0===e||"object"==typeof e){let s=["debug","log","info","warn","error"];s.forEach(t=>{r[t]=L(t,e,i)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.13`)}catch(e){return A()}s.forEach(t=>{R[t]=L(t,e)})}else p(R,r);return r}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let r=function e(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(e):Object.keys(t).reduce((i,r)=>(i[r]=e(t[r]),i),{}):t}(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{let a=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[a],l=[];s.forEach(i=>{let s=`${e}Loading${i}`,o=t[s];if(void 0!==o&&n){l.push(s);let e=r[a].default;switch(t[a]={default:e},i){case"TimeOut":e.maxLoadTimeMs=o,e.maxTimeToFirstByteMs=o;break;case"MaxRetry":e.errorRetry.maxNumRetry=o,e.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":e.errorRetry.retryDelayMs=o,e.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=o,e.timeoutRetry.maxRetryDelayMs=o}}}),l.length&&i.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${eC(t[a])}`)}),y(y({},r),t)}(aZ.DefaultConfig,e,t);this.userConfig=e,i.progressive&&function(e,t){let i=e.loader;i!==aD&&i!==aC?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=aD,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,t);let{abrController:r,bufferController:s,capLevelController:a,errorController:n,fpsController:l}=i,o=new n(this),d=this.abrController=new r(this),u=new e4(this),f=i.interstitialsController,c=f?this.interstitialsController=new f(this,aZ):null,g=this.bufferController=new s(this,u),m=this.capLevelController=new a(this),E=new l(this),v=new az(this),T=i.contentSteeringController,S=T?new T(this):null,I=this.levelController=new aK(this,S),b=new a$(this),D=new aj(this.config,this.logger),k=this.streamController=new aW(this,u,D),_=this.gapController=new ax(this,u);m.setStreamController(k),E.setStreamController(k);let P=[v,I,k];c&&P.splice(1,0,c),S&&P.splice(1,0,S),this.networkControllers=P;let C=[d,g,_,m,E,b,u];this.audioTrackController=this.createController(i.audioTrackController,P);let O=i.audioStreamController;O&&P.push(this.audioStreamController=new O(this,u,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,P);let x=i.subtitleStreamController;x&&P.push(this.subtititleStreamController=new x(this,u,D)),this.createController(i.timelineController,C),D.emeController=this.emeController=this.createController(i.emeController,C),this.cmcdController=this.createController(i.cmcdController,C),this.latencyController=this.createController(aG,C),this.coreComponents=C,P.push(o);let w=o.onErrorOut;"function"==typeof w&&this.on(h.ERROR,w,o),this.on(h.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;let i=e===h.ERROR;this.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(h.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(h.ERROR,{type:l.OTHER_ERROR,details:o.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,r=t?e:{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 e=this.bufferController.transferMedia();return this.trigger(h.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,r=this._url=C.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(h.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", ":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[c.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[c.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[c.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(t){let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)})}}}()),e}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(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return -1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){eR.indexOf(e)>-1&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return -1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r=t)return r;return 0}get maxAutoLevel(){let e,{levels:t,autoLevelCapping:i,maxHdcpLevel:r}=this;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(let i=e;i--;){let e=t[i].attrs["HDCP-LEVEL"];if(e&&e<=r)return i}return e}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}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(e){this.latencyController.targetLatency=e}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(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!(null!=(e=this.bufferController)&&e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return eA(e,ex(t),navigator.mediaCapabilities)}}aZ.defaultConfig=void 0}}]);
//# sourceMappingURL=a4634e51-30cbf5dc8026422c.js.map