"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[65157],{65157:function(t,e,s){s.d(e,{ZP:function(){return Po}});const i=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},r=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=n},n=Number.MAX_SAFE_INTEGER||9007199254740991;let a=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),o=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),l=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var h="manifest",d="level",c="audioTrack",u="subtitleTrack",f="main",g="audio",m="subtitle";class p{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class v{constructor(t,e,s,i=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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new p(t),this.fast_=new p(e),this.defaultTTFB_=i,this.ttfb_=new p(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new p(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new p(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new p(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function y(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function E(){return E=Object.assign?Object.assign.bind():function(t){for(var e=1;e`):A}(t,s)}const k=b();const D=k;function _(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function P(t,e){const s=Object.keys(t),i=Object.keys(e),r=s.length,n=i.length;return!r||!n||r===n&&!s.some((t=>-1===i.indexOf(t)))}function C(t,e=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(t);if(e){const t=s.indexOf("\0");return-1!==t?s.substring(0,t):s}return s.replace(/\0/g,"")}const s=t.length;let i,r,n,a="",o=0;for(;o>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:r=t[o++],a+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=t[o++],n=t[o++],a+=String.fromCharCode((15&i)<<12|(63&r)<<6|(63&n)<<0)}}return a}const w=function(t){let e="";for(let s=0;s1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){i(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return j(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}}class X extends W{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function z(t,e){const s=Object.getPrototypeOf(t);if(s){const t=Object.getOwnPropertyDescriptor(s,e);return t||z(s,e)}}const Q=Math.pow(2,32)-1,Z=[].push,J={video:1,audio:2,id3:3,text:4};function tt(t){return String.fromCharCode.apply(null,t)}function et(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function st(t,e){const s=rt(t,e);return s<0?4294967296+s:s}function it(t,e){let s=st(t,e);return s*=Math.pow(2,32),s+=st(t,e+4),s}function rt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function nt(t,e,s){t[e]=s>>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=255&s}function at(t,e){const s=[];if(!e.length)return s;const i=t.byteLength;for(let r=0;r1?r+n:i;if(tt(t.subarray(r+4,r+8))===e[0])if(1===e.length)s.push(t.subarray(r+8,a));else{const i=at(t.subarray(r+8,a),e.slice(1));i.length&&Z.apply(s,i)}r=a}return s}function ot(t){const e=[],s=t[0];let i=8;const r=st(t,i);i+=4;let n=0,a=0;0===s?(n=st(t,i),a=st(t,i+4),i+=8):(n=it(t,i),a=it(t,i+8),i+=16),i+=2;let o=t.length+a;const l=et(t,i);i+=2;for(let s=0;s>>31)return D.warn("SIDX has hierarchical references (not supported)"),null;const l=st(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function lt(t){const e=[],s=at(t,["moov","trak"]);for(let t=0;t{const s=st(t,4),i=e[s];i&&(i.default={duration:st(t,12),flags:st(t,20)})})),e}function ht(t){const e=t.subarray(8),s=e.subarray(86),i=tt(e.subarray(4,8));let r,n=i;const a="enca"===i||"encv"===i;if(a){const t=at(e,[i])[0];at(t.subarray("enca"===i?28:78),["sinf"]).forEach((t=>{const e=at(t,["schm"])[0];if(e){const s=tt(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=at(t,["frma"])[0];e&&(n=tt(e))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=at(s,["avcC"])[0];n+="."+ut(t[1])+ut(t[2])+ut(t[3]),r=dt("avc1"===o?"dva1":"dvav",s);break}case"mp4a":{const t=at(e,[i])[0],s=at(t.subarray(28),["esds"])[0];if(s&&s.length>7){let t=4;if(3!==s[t++])break;t=ct(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=ct(s,t);const i=s[t++];if(64!==i)break;if(n+="."+ut(i),t+=12,5!==s[t++])break;t=ct(s,t);const r=s[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&s[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=at(s,["hvcC"]);if(t){const e=t[0],s=e[1],i=["","A","B","C"][s>>6],r=31&s,a=st(e,2),o=(32&s)>>5?"H":"L",l=e[12],h=e.subarray(6,12);n+="."+i+r,n+="."+a.toString(16).toUpperCase(),n+="."+o+l;let d="";for(let t=h.length;t--;){const e=h[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}r=dt("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=dt(n,s)||n;break;case"vp09":{const t=at(s,["vpcC"])[0],e=t[4],i=t[5],r=t[6]>>4&15;n+="."+ft(e)+"."+ft(i)+"."+ft(r);break}case"av01":{const t=at(s,["av1C"])[0],e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,h=2===e&&o?l?12:10:o?10:8,d=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+ft(i)+a+"."+ft(h)+"."+d+"."+c+u+f+"."+ft(g)+"."+ft(m)+"."+ft(p)+"."+v,r=dt("dav1",s);break}}return{codec:n,encrypted:a,supplemental:r}}function dt(t,e){const s=at(e,["dvvC"]),i=s.length?s[0]:at(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,s=i[2]<<5&32|i[3]>>3&31;return t+"."+ft(e)+"."+ft(s)}}function ct(t,e){const s=e+5;for(;128&t[e++]&&e{const l=o.byteOffset-8;at(o,["traf"]).map((o=>{const h=at(o,["tfdt"]).map((t=>{const e=t[0];let s=st(t,4);return 1===e&&(s*=Math.pow(2,32),s+=st(t,8)),s/r}))[0];return void 0!==h&&(t=h),at(o,["tfhd"]).map((h=>{const d=st(h,4),c=16777215&st(h,0);let u=0;const f=0!=(16&c);let g=0;const m=0!=(32&c);let p=8;d===n&&(0!=(1&c)&&(p+=8),0!=(2&c)&&(p+=4),0!=(8&c)&&(u=st(h,p),p+=4),f&&(g=st(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=yt(e.codec)),at(o,["trun"]).map((n=>{const o=n[0],h=16777215&st(n,0),d=0!=(1&h);let c=0;const f=0!=(4&h),m=0!=(256&h);let p=0;const v=0!=(512&h);let y=0;const E=0!=(1024&h),T=0!=(2048&h);let S=0;const L=st(n,4);let A=8;d&&(c=st(n,A),A+=4),f&&(A+=4);let R=c+l;for(let l=0;l>1&63;return 39===t||40===t}return 6===(31&e)}function Tt(t,e,s,i){const r=St(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(ot){D.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=et(r,e);if(e+=2,49===t){const t=st(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r>>24;if(0!==r&&1!==r)return{offset:s,size:e};const n=t.buffer,a=w(new Uint8Array(n,s+12,16)),o=t.getUint32(28);let l=null,h=null;if(0===r){if(e-32/\(Windows.+Firefox\//i.test(navigator.userAgent),bt={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 It(t,e){const s=bt[e];return!!s&&!!s[t.slice(0,4)]}function kt(t,e,s=!0){return!t.split(",").some((t=>!Dt(t,e,s)))}function Dt(t,e,s=!0){var i;const r=_(s);return null!=(i=null==r?void 0:r.isTypeSupported(_t(t,e)))&&i}function _t(t,e){return`${e}/mp4;codecs=${t}`}function Pt(t){if(t){const e=t.substring(0,4);return bt.video[e]}return 2}function Ct(t){const e=Rt();return t.split(",").reduce(((t,s)=>{const i=e&&yt(s)?9:bt.video[s];return i?(2*i+t)/(t?3:2):(bt.audio[s]+t)/(t?2:1)}),0)}const wt={};const xt=/flac|opus|mp4a\.40\.34/i;function Ot(t,e=!0){return t.replace(xt,(t=>function(t,e=!0){if(wt[t])return wt[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t)))return t;if(e){const s=e.split(",");if(s.length>1){if(t)for(let e=s.length;e--;)if(s[e].substring(0,4)===t.substring(0,4))return s[e];return s[0]}}return e||t}function Ft(t){if(t.startsWith("av01.")){const e=t.split("."),s=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=s[t-4];return e.join(".")}return t}function Nt(t){const e=_(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ut(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Bt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function $t(t,e){return{supported:!1,configurations:e,decodingInfoResults:[{supported:!1,smooth:!1,powerEfficient:!1}],error:t}}const Gt={};function Kt(t,e,s,r,n,a){const o=t.audioCodec?t.audioGroups:null,l=null==a?void 0:a.audioCodec,h=null==a?void 0:a.channels,d=h?parseInt(h):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce(((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach((e=>{t[e]=(t[e]||0)+i.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(n,8e6))||!!c&&i(d)&&Object.keys(c).some((t=>parseInt(t)>d))}function Ht(t,e,s){const r=t.videoCodec,n=t.audioCodec;if(!r&&!n||!s)return Promise.resolve(Bt);const a=[];if(r){const e={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},s=t.videoRange;"SDR"!==s&&(e.transferFunction=s.toLowerCase());const i=r.split(","),n=navigator.userAgent;if(i.some((t=>yt(t)))&&Rt())return Promise.resolve($t(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${n})`),a));a.push.apply(a,i.map((t=>({type:"media-source",video:S(S({},e),{},{contentType:_t(Ft(t),"video")})}))))}return n&&t.audioGroups&&t.audioGroups.forEach((t=>{var s;t&&(null==(s=e.groups[t])||s.tracks.forEach((e=>{if(e.groupId===t){const t=e.channels||"",s=parseFloat(t);i(s)&&s>2&&a.push.apply(a,n.split(",").map((t=>({type:"media-source",audio:{contentType:_t(t,"audio"),channels:""+s}}))))}})))})),Promise.all(a.map((t=>{const e=function(t){const{audio:e,video:s}=t,i=s||e;if(i){const t=Ut(i.contentType);if(s)return`r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${t}_${Math.ceil(s.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return Gt[e]||(Gt[e]=s.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:a,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:a,decodingInfoResults:[],error:t})))}const Vt=["NONE","TYPE-0","TYPE-1",null];const Yt=["SDR","PQ","HLG"];var Wt="",jt="YES",qt="v2";function Xt(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i!!t)).map((t=>t.substring(0,4))).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const s=null==(e=t.supplemental)?void 0:e.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.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(t){return Zt(this._audioGroups,t)}hasSubtitleGroup(t){return Zt(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function Zt(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Jt(t,e){let s=!1,i=[];if(t&&(s="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||Yt.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;s=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}const te=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(s,i)=>{if(t&&(i=t(s,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})(e));function ee(t,e){D.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function se(t){return t.reduce(((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ie(t){if(!t)return t;const{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}=t;return{lang:e,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function re(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i-1===i.indexOf(t)))}(t.characteristics||"",e.characteristics))&&(void 0===s||s(t,e))}function ae(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function oe(t,e,s){for(let i=e;i>-1;i--)if(s(t[i]))return i;for(let i=e+1;i0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function de(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===ce(s,i,n)||function(t,e,s){if(e&&0===e.start&&e.level0){const i=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=he(e,ce.bind(null,s,i));return!a||a===t&&n?n:a}function ce(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function ue(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}function fe(t,e){return he(t,(t=>t.cce?-1:0))}function ge(t){switch(t.details){case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_TIMEOUT:case o.LEVEL_LOAD_TIMEOUT:case o.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function me(t,e){const s=ge(e);return t.default[(s?"timeout":"error")+"Retry"]}function pe(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function ve(t){return S(S({},t),{errorRetry:null,timeoutRetry:null})}function ye(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}var Ee=0,Te=2,Se=3,Le=5,Ae=0,Re=1,be=2;function Ie(t){const e={action:Ee,flags:Ae};return t&&(e.resolved=!0),e}var ke="NOT_LOADED",De="APPENDING",_e="PARTIAL",Pe="OK";class Ce{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.BUFFER_APPENDED,this.onBufferAppended,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.BUFFER_APPENDED,this.onBufferAppended,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const i=s[e];if(!i)break;const r=i.end;if(i.start<=t&&null!==r&&t<=r)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if((null==a?void 0:a.body.type)===e&&(!s||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i,r){this.timeRanges&&(this.timeRanges[t]=e);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(a.body),s})):this.removeFragment(a.body))}))}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const s=t.frag,i=xe(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;if(Object.keys(e).forEach((i=>{const a=s.elementaryStreams[i];if(!a)return;const o=e[i],l=n||!0===a.partial;r.range[i]=this.getBufferedTimes(s,t.part,l,o)})),r.loaded=null,Object.keys(r.range).length){r.buffered=!0;(r.body.endList=s.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),we(r)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(r.body)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=s.filter((e=>e.fragment.sn>=t)))}fragBuffered(t,e){const s=xe(t);let i=this.fragments[s];!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t=e&&o<=s){r.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(ne){const e=Math.max(n,i.start(t)),s=Math.min(a,i.end(t));s>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&we(h)&&(s=h.body.start-a,i=h.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=h.body,n=e)))})),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||we(e))}getState(t){const e=xe(t),s=this.fragments[e];return s?s.buffered?we(s)?_e:Pe:De:ke}isTimeBuffered(t,e,s){let i,r;for(let n=0;n=i&&e<=r)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const s=e.frag,i=e.part?null:e,r=xe(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r,type:n}=e;if("initSegment"===s.sn)return;const a=s.type;if(i){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=xe(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,s=Object.keys(e);if(!t)return s.length>0;for(let i=s.length;i--;){const r=e[s[i]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.startt&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(t){const e=xe(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=s.filter((t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t,e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const s=null==(t=this.hls)||null==(e=t.latestLevelDetails)?void 0:e.partList;s&&s.forEach((t=>t.clearElementaryStreamInfo()))}}function we(t){var e,s,i;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(i=t.range.audiovideo)?void 0:i.partial))}function xe(t){return`${t.type}_${t.level}_${t.sn}`}var Oe=0,Me=1;class Fe{constructor(t,e,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=s}decrypt(t,e){switch(this.aesMode){case Oe:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Me:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Ne{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_(t){const e=new DataView(t),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=e.getUint32(4*t);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[s]^16843008*s;i[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[s]=v<<24|v>>>8,h[s]=v<<16|v>>>16,d[s]=v<<8|v>>>24,c[s]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,s,i)}softwareDecrypt(t,e,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==Oe||16!==e.byteLength)return D.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=pt(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ne),l.expandKey(e);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(t,e,s,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s,i));this.key=e,this.fastAesKey=new Ue(this.subtle,e,i)}return this.fastAesKey.expandKey().then((e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Fe(this.subtle,new Uint8Array(s),i).decrypt(t.buffer,e)})).catch((r=>(D.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s,i))))}onWebCryptoError(t,e,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s,i);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=t.slice(0,s),this.remainderData=t.slice(s)),e}logOnce(t){this.logEnabled&&(D.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const $e=Math.pow(2,17);class Ge{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const s=t.url;if(!s)return Promise.reject(new Ve({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((l,h)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void h(He(t));t.gap=!1}const d=this.loader=r?new r(i):new n(i),c=Ke(t);t.loader=d;const u=ve(i.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:$e};t.stats=d.stats;const g={onSuccess:(e,s,i,r)=>{this.resetLoader(t,d);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,r,n)=>{this.resetLoader(t,d),h(new Ve({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:S({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,d),h(new Ve({type:a.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,d),h(new Ve({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:i,stats:e}))}};e&&(g.onProgress=(s,i,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})),d.load(c,f,g)}))}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((l,h)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void h(He(t,e));const d=this.loader=r?new r(i):new n(i),c=Ke(t,e);t.loader=d;const u=ve(i.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:$e};e.stats=d.stats,d.load(c,f,{onSuccess:(i,r,n,a)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:i.data,networkDetails:a};s(o),l(o)},onError:(s,i,r,n)=>{this.resetLoader(t,d),h(new Ve({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:S({url:c.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,d),h(new Ve({type:a.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,d),h(new Ve({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:r,stats:s}))}})}))}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Ke(t,e=null){const s=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=s.byteRangeStartOffset,a=s.byteRangeEndOffset;if(i(n)&&i(a)){var o;let e=n,s=a;if("initSegment"===t.sn&&("AES-128"===(l=null==(o=t.decryptdata)?void 0:o.method)||"AES-256"===l)){const t=a-n;t%16&&(s=a+(16-t%16)),0!==n&&(r.resetIV=!0,e=n-16)}r.rangeStart=e,r.rangeEnd=s}var l;return r}function He(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:a.MEDIA_ERROR,details:o.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new Ve(i)}class Ve extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Ye extends L{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class We{constructor(t,e,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=s,this.size=i,this.part=r,this.partial=n}}const je={length:0,start:()=>0,end:()=>0};class qe{static isBuffered(t,e){if(t){const s=qe.getBuffered(t);for(let t=s.length;t--;)if(e>=s.start(t)&&e<=s.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=qe.getBuffered(t);return qe.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let s=0;s1&&t.sort(((t,e)=>t.start-e.start||e.end-t.end));let i=-1,r=[];if(s)for(let n=0;n=t[n].start&&e<=t[n].end&&(i=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-ee&&(r[a-1].end=t[n].end):r.push(t[n])}else r.push(t[n])}else r=t;let n,a=0,o=e,l=e;for(let t=0;t=h&&e<=d&&(i=t),e+s>=h&&e{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r}))}return e}function Ze(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function Je(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}const ts=/^(\d+)x(\d+)$/,es=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ss{constructor(t,e){"string"==typeof t&&(t=ss.parseAttrList(t,e)),E(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const s=new Uint8Array(e.length/2);for(let t=0;tNumber.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce(((t,e)=>(t[e.toLowerCase()]=!0,t)),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=ts.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let s;const i={};for(es.lastIndex=0;null!==(s=es.exec(t));){const r=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=Qe(e,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)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":D.warn(`${t}: attribute ${r} is missing quotes`)}i[r]=n}return i}}function is(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class rs{constructor(t,e,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(r=null==e?void 0:e.tagOrder)?r:s,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){D.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=E(new ss({}),s,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);i(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(D.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(i(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&i(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 ns{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}get hasProgramDateTime(){return!!this.fragments.length&&i(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let s=t.length;s--;)if(t[s].index>e)return t[s].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function as(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function os(t){switch(t){case"AES-128":case"AES-256":return Oe;case"AES-256-CTR":return Me;default:throw new Error(`invalid full segment method ${t}`)}}function ls(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function hs(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}function ds(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=ls(r)):s=function(t){const e=hs(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}const cs="undefined"!=typeof self?self:void 0;var us={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},fs="org.w3.clearkey",gs="com.apple.streamingkeydelivery",ms="com.microsoft.playready",ps="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function vs(t){switch(t){case gs:return us.FAIRPLAY;case ms:return us.PLAYREADY;case ps:return us.WIDEVINE;case fs:return us.CLEARKEY}}var ys="1077efecc0b24d02ace33c1e52e2fb4b",Es="e2719d58a985b3c9781ab030af78d30e",Ts="9a04f07998404286ab92e65be0885f95",Ss="edef8ba979d64acea3c827dcd51d21ed";function Ls(t){return t===Ss?us.WIDEVINE:t===Ts?us.PLAYREADY:t===ys||t===Es?us.CLEARKEY:void 0}function As(t){switch(t){case us.FAIRPLAY:return gs;case us.PLAYREADY:return ms;case us.WIDEVINE:return ps;case us.CLEARKEY:return fs}}function Rs(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[us.FAIRPLAY,us.WIDEVINE,us.PLAYREADY,us.CLEARKEY].filter((t=>!!e[t])):[];return!i[us.WIDEVINE]&&s&&i.push(us.WIDEVINE),i}const bs=null!=cs&&null!=(Is=cs.navigator)&&Is.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Is;function ks(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),s=String.fromCharCode.apply(null,Array.from(e)),i=s.substring(s.indexOf("<"),s.length),r=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){const t=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(t){const e=ls(t).subarray(0,16);return function(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),e}}return null}let Ds={};class _s{static clearKeyUriToKeyIdMap(){Ds={}}constructor(t,e,s,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!as(t)}isSupported(){if(this.method){if(as(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case gs:case ps:case ms:case fs:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if(as(this.method)&&this.uri&&!this.iv){"number"!=typeof t&&(D.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const e=function(t){const e=new Uint8Array(16);for(let s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}(t);return new _s(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=ds(this.uri);if(e)switch(this.keyFormat){case ps:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case ms:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Lt(t,0,e),this.keyId=ks(e);break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=Ds[this.uri];if(!t){const e=Object.keys(Ds).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),Ds[this.uri]=t}this.keyId=t}return this}}const Ps=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Cs=/#EXT-X-MEDIA:(.*)/g,ws=/^#EXT(?:INF|-X-TARGETDURATION):/m,xs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Os=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ms{static findGroup(t,e){for(let s=0;s0&&i.length({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Cs.lastIndex=0;null!==(i=Cs.exec(t));){const t=new ss(i[1],s),n=t.TYPE;if(n){const s=a[n],i=r[n]||[];r[n]=i;const l=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],d=t.CHANNELS,c=t.CHARACTERISTICS,u=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Ms.resolve(t.URI,e):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=s&&s.length){const t=Ms.findGroup(s,f.groupId)||s[0];Gs(f,t,"audioCodec"),Gs(f,t,"textCodec")}i.push(f)}}return r}static parseLevelPlaylist(t,e,s,r,n,a){var o;const l={url:e},h=new ns(e),d=h.fragments,c=[];let u,f,g,m,p=null,v=0,y=0,T=0,S=0,L=0,A=null,R=new q(r,l),b=-1,I=!1,k=null;if(xs.lastIndex=0,h.m3u8=t,h.hasVariableRefs=ze(t),"#EXTM3U"!==(null==(o=xs.exec(t))?void 0:o[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(u=xs.exec(t));){I&&(I=!1,R=new q(r,l),R.playlistOffset=T,R.start=T,R.sn=v,R.cc=S,L&&(R.bitrate=L),R.level=s,p&&(R.initSegment=p,p.rawProgramDateTime&&(R.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),k&&(R.setByteRange(k),k=null)));const t=u[1];if(t){R.duration=parseFloat(t);const e=(" "+u[2]).slice(1);R.title=e||null,R.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(i(R.duration)){R.playlistOffset=T,R.start=T,g&&Vs(R,g,h),R.sn=v,R.level=s,R.cc=S,d.push(R);const t=(" "+u[3]).slice(1);R.relurl=Qe(h,t),Ks(R,A,c),A=R,T+=R.duration,v++,y=0,I=!0}}else{if(u=u[0].match(Os),!u){D.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f0&&Ws(h,t,u),v=h.startSN=parseInt(n);break;case"SKIP":{h.skippedSegments&&Ys(h,t,u);const e=new ss(n,h),s=e.decimalInteger("SKIPPED-SEGMENTS");if(i(s)){h.skippedSegments+=s;for(let t=s;t--;)d.push(null);v+=s}const r=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(r.split("\t")));break}case"TARGETDURATION":0!==h.targetduration&&Ys(h,t,u),h.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==h.version&&Ys(h,t,u),h.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Ys(h,t,u),h.live=!1;break;case"#":(n||o)&&R.tagList.push(o?[n,o]:[n]);break;case"DISCONTINUITY":S++,R.tagList.push(["DIS"]);break;case"GAP":R.gap=!0,R.tagList.push([t]);break;case"BITRATE":R.tagList.push([t,n]),L=1e3*parseInt(n),i(L)?R.bitrate=L:L=0;break;case"DATERANGE":{const t=new ss(n,h),e=new rs(t,h.dateRanges[t.ID],h.dateRangeTagCount);h.dateRangeTagCount++,e.isValid||h.skippedSegments?h.dateRanges[e.id]=e:D.warn(`Ignoring invalid DATERANGE tag: "${n}"`),R.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new ss(n,h);"IMPORT"in t?Je(h,t,a):Ze(h,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC?Ys(h,t,u):d.length>0&&Ws(h,t,u),h.startCC=S=parseInt(n);break;case"KEY":{const t=Us(n,e,h);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={}),g[t.keyFormat]&&(g=E({},g)),g[t.keyFormat]=t}else D.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${n}"`);break}case"START":h.startTimeOffset=Bs(n);break;case"MAP":{const t=new ss(n,h);if(R.duration){const e=new q(r,l);Hs(e,t,s,g),p=e,R.initSegment=p,p.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=p.rawProgramDateTime)}else{const e=R.byteRangeEndOffset;if(e){const t=R.byteRangeStartOffset;k=`${e-t}@${t}`}else k=null;Hs(R,t,s,g),p=R,I=!0}p.cc=S;break}case"SERVER-CONTROL":m&&Ys(h,t,u),m=new ss(n),h.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),h.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{h.partTarget&&Ys(h,t,u);const e=new ss(n);h.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=h.partList;t||(t=h.partList=[]);const e=y>0?t[t.length-1]:void 0,s=y++,i=new ss(n,h),r=new X(i,R,l,s,e);t.push(r),R.duration+=r.duration;break}case"PRELOAD-HINT":{const t=new ss(n,h);h.preloadHint=t;break}case"RENDITION-REPORT":{const t=new ss(n,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(t);break}default:D.warn(`line parsed but not handled: ${u}`)}}}A&&!A.relurl?(d.pop(),T-=A.duration,h.partList&&(h.fragmentHint=A)):h.partList&&(Ks(R,A,c),R.cc=S,h.fragmentHint=R,g&&Vs(R,g,h)),h.targetduration||(h.playlistParsingError=new Error("#EXT-X-TARGETDURATION is required"));const _=d.length,P=d[0],C=d[_-1];if(T+=h.skippedSegments*h.targetduration,T>0&&_&&C){h.averagetargetduration=T/_;const t=C.sn;h.endSN="initSegment"!==t?t:0,h.live||(C.endList=!0),P&&void 0===h.startCC&&(h.startCC=P.cc),b>0&&(!function(t,e){let s=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(d,b),P&&c.unshift(P))}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(T+=h.fragmentHint.duration),h.totalduration=T,c.length&&h.dateRangeTagCount&&P&&Fs(c,h),h.endCC=S,h}}function Fs(t,e){const s=t.length,i=t[s-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let a=n.length;a--;){const o=e.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=i.ref;for(let i=s;i--;){const s=Ns(e,l,t,i,r);if(-1!==s){o.tagAnchor=e.fragments[s].ref;break}}}}function Ns(t,e,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(e>=o||0===i){var a;if(e<=o+1e3*(((null==(a=s[i+1])?void 0:a.start)||r)-n.start)){const r=s[i].sn-t.startSN,n=t.fragments;if(n.length>s.length){for(let a=(s[i+1]||n[n.length-1]).sn-t.startSN;a>r;a--){const t=n[a].programDateTime;if(e>=t&&et));["video","audio","text"].forEach((t=>{const i=s.filter((e=>It(e,t)));i.length&&(e[`${t}Codec`]=i.map((t=>t.split("/")[0])).join(","),s=s.filter((t=>-1===i.indexOf(t))))})),e.unknownCodecs=s}function Gs(t,e,s){const i=e[s];i&&(t[s]=i)}function Ks(t,e,s){t.rawProgramDateTime?s.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Hs(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function Vs(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||i.push(t)}function Ys(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${s[0]})`)}function Ws(t,e,s){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${s[0]})`)}function js(t,e){const s=e.startPTS;if(i(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&i.setDuration(r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function qs(t,e,s,r,n,a){r-s<=0&&(D.warn("Fragment should have a positive duration",e),r=s+e.duration,a=n+e.duration);let o=s,l=r;const h=e.startPTS,d=e.endPTS;if(i(h)){const t=Math.abs(h-s);i(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,o=Math.max(s,h),s=Math.min(s,h),n=Math.min(n,e.startDTS),l=Math.min(r,d),r=Math.max(r,d),a=Math.max(a,e.endDTS)}const c=s-e.start;0!==e.start&&e.setStart(s),e.setDuration(r-e.start),e.startPTS=s,e.maxStartPTS=o,e.startDTS=n,e.endPTS=r,e.minEndPTS=l,e.endDTS=a;const u=e.sn;if(!t||ut.endSN)return 0;let f;const g=u-t.startSN,m=t.fragments;for(m[g]=e,f=g;f>0;f--)js(m[f],m[f-1]);for(f=g;f=0;t--){const e=r[t].initSegment;if(e){s=e;break}}let n;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,s){const i=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let h=r;h<=n;h++){const r=l[a+h];let n=o[h];if(i&&!n&&r&&(n=e.fragments[h]=r),r&&n){if(s(r,n,h,o),r.url&&r.url!==n.url)return void(e.playlistParsingError=zs(`media sequence mismatch ${n.sn}:`,t,e,r,n));if(r.cc!==n.cc)return void(e.playlistParsingError=zs(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,t,e,r,n))}}}(t,e,((t,r,a,o)=>{if(e.skippedSegments&&r.cc!==t.cc){const e=t.cc-r.cc;for(let t=a;t{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)})),e.skippedSegments)if(e.deltaUpdateFailed=a.some((t=>!t)),e.deltaUpdateFailed){D.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.endCC=a[a.length-1].cc,e.canSkipDateRanges&&(e.dateRanges=function(t,e){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=E({},t);i&&i.forEach((t=>{delete r[t]}));const n=Object.keys(r).length;n&&Object.keys(s).forEach((t=>{const e=r[t],i=new rs(s[t].attr,e);i.isValid?(r[t]=i,e||(i.tagOrder+=n)):D.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${te(s[t].attr)}"`)}));return r}(t.dateRanges,e));const s=t.fragments.filter((t=>t.rawProgramDateTime));if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),n?qs(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Qs(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const t=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=t),e.driftEndTime=l,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function zs(t,e,s,i,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function Qs(t,e,s=!0){const i=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,n=i>=0;let a=0;if(n&&ie){const t=1e3*i[i.length-1].duration;t{var s;null==(s=t.details)||s.fragments.forEach((t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)}))}))}function ii(t,e){for(let i=0,r=t.length;it.startCC)}(e,t))return;const s=Math.min(e.endCC,t.endCC),i=ii(e.fragments,s),r=ii(t.fragments,s);if(!i||!r)return;D.log(`Aligning playlist at start of dicontinuity sequence ${s}`);ni(i.start-r.start,t)}function oi(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,i=e.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(e.endCC,t.endCC);e.startCC{const{config:t,fragCurrent:e,media:s,mediaBuffer:r,state:n}=this,a=s?s.currentTime:0,o=qe.bufferInfo(r||s,a,t.maxBufferHole);if(this.log(`media seeking to ${i(a)?a.toFixed(3):a}, state: ${n}`),this.state===vi)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,i=e.start-s,r=e.start+e.duration+s;if(!o.len||ro.end){const t=a>r;(athis.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts){const t=Math.max(o.end,a),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}this.hls.hasEnoughToStart||o.len||(this.log(`setting startPosition to ${a} because of seek before start`),this.nextLoadPosition=this.startPosition=a),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new Ge(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Be(t.config)}registerListeners(){const{hls:t}=this;t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===hi)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=hi}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const s=t.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=t.nextStart;if(r&&r>i&&r{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const e=this.state,s=t.frag;this.fragContextChanged(s)?(e===ui||!this.fragCurrent&&e===mi)&&(this.fragmentTracker.removeFragment(s),this.state=di):("payload"in t&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(l.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((e=>{this.state!==hi&&this.state!==yi&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===De){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===_e&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(l.BUFFER_FLUSHING,i)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:e}=this,{frag:s,payload:i}=t,r=s.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&as(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,os(r.method)).catch((t=>{throw e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:s}),t})).then((i=>{const r=self.performance.now();return e.trigger(l.FRAG_DECRYPTED,{frag:s,payload:i,stats:{tstart:n,tdecrypt:r}}),t.payload=i,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((e=>{this.state!==hi&&this.state!==yi&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state!==hi&&(this.state=di),t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${s?li(qe.getBuffered(s)):"(detached)"})`),j(t)){var i;if(t.type!==m){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=di)}const e=null==(i=this.levels)?void 0:i[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=di}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some((t=>!t)),a=new We(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,r){var n;this.fragCurrent=t;const a=null==e?void 0:e.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;!t.encrypted||null!=(n=t.decryptdata)&&n.key?!t.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(t,a.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=ci,this.fragCurrent=t,o=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(l.KEY_LOADED,t),this.state===ci&&(this.state=di),t})),this.hls.trigger(l.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const h=this.fragPrevious;if(j(t)&&(!h||t.sn!==h.sn)){const s=this.shouldLoadParts(e.details,t.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==h?void 0:h.sn}->${t.sn}`),this.loadingParts=s)}if(s=Math.max(t.start,s||0),this.loadingParts&&j(t)){const i=a.partList;if(i&&r){s>t.end&&a.fragmentHint&&(t=a.fragmentHint);const n=this.getNextPart(i,t,s);if(n>-1){const h=i[n];let d;return t=this.fragCurrent=h.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${h.index} (${n}/${i.length-1}) of ${this.fragInfo(t,!1,h)}) cc: ${t.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=h.start+h.duration,this.state=ui,d=o?o.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,h,e,r))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,h,e,r).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(l.FRAG_LOADING,{frag:t,part:h,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(i,s))return Promise.resolve(null)}}if(j(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${a?"["+a.startSN+"-"+a.endSN+"]":""}, target: ${parseFloat(s.toFixed(3))}`),i(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ui;const d=this.config.progressive;let c;return c=d&&o?o.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,r))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,d?r:void 0),o]).then((([t])=>(!d&&t&&r&&r(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(l.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(t,e,s,i){return new Promise(((r,n)=>{var a;const o=[],h=null==(a=s.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,i).then((i=>{o[e.index]=i;const n=i.part;this.hls.trigger(l.FRAG_LOADED,i);const a=ti(s.details,t.sn,e.index+1)||ei(h,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});d(a)})).catch(n)};d(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===o.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(l.ERROR,e)}else this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==mi)return void(this.fragCurrent||this.state===hi||this.state===yi||(this.state=di));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(null!=t&&t.partList){var s;const r=t.partList[0];if(e>=r.end+((null==(s=t.fragmentHint)?void 0:s.duration)||0)){var i;if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=a.details,l=n>-1?ti(o,r,n):null,h=l?l.fragment:function(t,e,s){if(!t)return null;let i=t.fragments[e-t.startSN];return i||(i=t.fragmentHint,i&&i.sn===e?i:en&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var s;const r=this.getLoadPosition();if(!i(r))return null;const n=this.lastCurrentTime>r||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,r,e,n)}getFwdBufferInfoAtPos(t,e,s,i){const r=qe.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&(r.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(r.nextStart,n.end)-e,i);return qe.bufferInfo(t,e,s)}}return r}getMaxBufferLength(t){const{config:e}=this;let s;return s=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e),r=Math.max(t-3*e,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=f){var s;const i=null==(s=this.fragmentTracker)?void 0:s.getAppendedFrag(t,e);return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const h=r.initialLiveManifestSize;if(i=n?i:r)||o.start:t;this.log(`Setting startPosition to ${h} to match start frag at live edge. mainStart: ${i} liveSyncPosition: ${r} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=h}}else t<=n&&(o=s[0]);if(!o){const s=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,s,e)}let h=this.filterReplacedPrimary(o,e);if(!h&&o){const t=o.sn-e.startSN;h=this.filterReplacedPrimary(s[t+1]||null,e)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return(s===Pe||s===_e&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,i,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&s.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(null!==t&&s.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Li(this.hls.config)){var t,e;if(null==(t=this.hls.interstitialsManager)||null==(e=t.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(Li(this.hls.config)&&t.type!==m){const s=this.hls.interstitialsManager,i=null==s?void 0:s.bufferingItem;if(i){const s=i.event;if(s){if(s.appendInPlace||Math.abs(t.start-i.start)>1||0===i.start)return null}else{if(t.end<=i.start&&!1===(null==e?void 0:e.live))return null;if(t.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||t.start-i.end>1))return null}}const r=null==s?void 0:s.playerQueue;if(r)for(let e=r.length;e--;){const s=r[e].interstitial;if(s.appendInPlace&&t.start>=s.startTime&&t.end<=s.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a-1&&ss.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let r=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!i(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let i=0;i=t.startSN&&i<=t.endSN){const n=e[i-t.startSN];s.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=fe(e,s.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(d&&o&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),te-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===Pe||e===_e&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn||!s.live&&!d)){if(r&&c.level===r.level){const e=n[t+1];c=c.sn${t.startSN} fragments: ${r}`),i}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let s=this.startPosition;s=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&j(t)&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===fi)||(this.state=di)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const s=e.frag;if(!s||s.type!==t||!this.levels)return;var i;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);const r=e.details===o.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,flags:l,retryCount:h=0,retryConfig:d}=n||{},c=!!n&&!!d,u=c&&a===Le,f=c&&!n.resolved&&l===Re;if(!u&&f&&j(s)&&!s.endList)this.resetFragmentErrors(t),this.treatAsGap(s),n.resolved=!0;else if((u||f)&&h.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===g&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==hi&&(this.state=di)}afterBufferFlushed(t,e,s){if(!t)return;const i=qe.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,s),this.state===vi&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==hi&&(this.state=di)}resetStartWhenNotLoaded(t){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of ${this.playlistLabel()} ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){const r=s.details;if(!r)return void this.warn("level.details undefined");var n;if(!Object.keys(t.elementaryStreams).reduce(((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const h=i?0:qs(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(l.LEVEL_PTS_UPDATED,{details:r,level:s,drift:h,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&(0===s.fragmentError&&this.treatAsGap(t,s),null===(null==(n=this.transmuxer)?void 0:n.error))){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=pi,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(l.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===f?"level":"track"}fragInfo(t,e=!0,s){var i,r;return`${this.playlistLabel()} ${t.level} (${s?"part":"frag"}:[${(null!=(i=e&&!s?t.startPTS:(s||t).start)?i:NaN).toFixed(3)}-${(null!=(r=e&&!s?t.endPTS:(s||t).end)?r:NaN).toFixed(3)}]${s&&"main"===t.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function Li(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Ai{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let i=0;for(let e=0;e0)return t.subarray(s,s+i)}function Oi(t,e){return 255===t[e]&&240==(246&t[e+1])}function Mi(t,e){return 1&t[e+1]?7:9}function Fi(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Ni(t,e){return e+1=t.length)return!1;const i=Fi(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||Ni(t,r)}return!1}function Bi(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){const r=e[s+2],n=r>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const h=1+(r>>6&3),d=e[s+3]>>6&3|(1&r)<<2,c="mp4a.40."+h,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let f=n;5!==h&&29!==h||(f-=3);const g=[h<<3|(14&f)>>1,(1&f)<<7|d<<3];return D.log(`manifest codec:${i}, parsed codec:${c}, channels:${d}, rate:${u} (ADTS object type:${h} sampling index:${n})`),{config:g,samplerate:u,channelCount:d,codec:c,parsedCodec:c,manifestCodec:i}}(e,s,i,r);if(!n)return;E(t,n)}}function $i(t){return 9216e4/t}function Gi(t,e,s,i,r){const n=i+r*$i(t.samplerate),a=function(t,e){const s=Mi(t,e);if(e+s<=t.length){const i=Fi(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,s+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-s;o=new Uint8Array(l),o.set(e.subarray(s,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Ki(t,e){return Ci(t,e)&&wi(t,e+6)+10<=t.length-e}function Hi(t,e){if(t<0)return-Hi(-t,e);const s=Math.pow(10,e);if(Math.abs(t*s%1-.5)>6&1&&(e+=10),e+=10;const r=e+i;for(;e+100&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Zi.audioId3,duration:Number.POSITIVE_INFINITY});n{if(i(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};let sr=null;const ir=[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],rr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],nr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ar=[0,1,1,4];function or(t,e,s,i,r){if(s+24>e.length)return;const n=lr(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function lr(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*ir[14*(3===s?3-i:3===i?3:4)+r-1],h=rr[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=nr[s][i],u=ar[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===sr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);sr=t?parseInt(t[1]):0}return!!sr&&sr<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function hr(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function dr(t,e){return e+1{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<>l,s=s?s<e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=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*o+n];if(s+l>e.length)return-1;const h=e[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[s+6]<<8|e[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),v=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const mr=/\/emsg[-/]ID3/i;function pr(t,e){return i(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class vr{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Be(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Oe)}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}))}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let i=0;for(let e=32;e{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}))}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}}class yr{constructor(){this.VideoSample=null}createVideoSample(t,e,s){return{key:t,frame:!1,pts:e,dts:s,units:[],length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,s){const i=e.byteLength;let r=t.naluState||0;const n=r,a=[];let o,l,h,d=0,c=-1,u=0;for(-1===r&&(c=0,u=this.getNALuType(e,0),r=0,d=1);d=0){const t={data:e.subarray(c,l),type:u};a.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(n&&d<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=pt(s.data,e.subarray(0,l)),s.state=0))}d=0&&r>=0){const t={data:e.subarray(c,i),type:u,state:r};a.push(t)}if(0===a.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=pt(s.data,e))}return t.naluState=r,a}}class Er{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&D.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?s<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Tr extends yr{parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let n,a=this.VideoSample,o=!1;s.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach((i=>{var r,l;switch(i.type){case 1:{let e=!1;n=!0;const r=i.data;if(o&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Tt(i.data,1,s.pts,e.samples);break;case 7:{var d,c;n=!0,o=!0;const e=i.data,s=this.readSPS(e);if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(d=t.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:n=!0,t.pps=[i.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(i)}})),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new Er(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let s,i=8,r=8;for(let n=0;n{var r,l;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var h;if(n=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,Tt(i.data,2,s.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=E(t.params,this.readVPS(i.data)),this.initVPS=i.data),t.vps=[i.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],i.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(i.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const s in e.params)t.params[s]=e.params[s]}this.pushParameterSet(t.sps,i.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(i.data);for(const s in e)t.params[s]=e[s]}this.pushParameterSet(t.pps,i.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:n=!1}if(a&&n){a.units.push(i)}})),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let s=0;for(let i=0;i=2&&3===t[i]&&0===t[i-1]&&0===t[i-2]||(e[s]=t[i],s++);return new Uint8Array(e.buffer,0,s)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new Er(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new Er(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const s=e.readBits(3);e.readBoolean();const i=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),d=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let t=0;t0)for(let t=s;t<8;t++)e.readBits(2);for(let t=0;t1&&e.readEG();for(let t=0;t0&&t<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],O=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=e.readBits(16),O=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),U=e.readBoolean(),U&&(A+=e.readUEG(),R+=e.readUEG(),b+=e.readUEG(),I+=e.readUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),i=e.readBoolean();let r=!1;(t||i)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=s;n++){M=e.readBoolean();let s=!1;M||e.readBoolean()?e.readEG():s=e.readBoolean();const n=s?1:e.readUEG()+1;if(t)for(let t=0;t>t&1)<<31-t)>>>0;let V=H.toString(16);1===n&&"2"===V&&(V="6");return{codecString:`hvc1.${G}${n}.${V}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:w,chroma_format_idc:E,frame_rate:{fixed:M,fps:N/F}},width:B,height:$,pixelRatio:[x,O]}}readPPS(t){const e=new Er(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const s=e.readBoolean(),i=e.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const Lr=188;class Ar{constructor(t,e,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(t,e){const s=Ar.syncOffset(t);return s>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(t){const e=t.length;let s=Math.min(940,e-Lr)+1,i=0;for(;i1&&(0===n&&a>2||o+Lr>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:J[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ar.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Ar.createTrack("audio",i),this._id3Track=Ar.createTrack("id3"),this._txtTrack=Ar.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=pt(this.remainderData,t)).length,this.remainderData=null),y>4>1){if(T=e+5+t[e+4],T===e+Lr)continue}else T=e+4;switch(y){case h:if(i){if(d&&(r=_r(d,this.logger))){if(null===this.videoParser)switch(n.segmentCodec){case"avc":this.videoParser=new Tr;break;case"hevc":this.videoParser=new Sr}null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)}d={data:[],size:0}}d&&(d.data.push(t.subarray(T,e+Lr)),d.size+=e+Lr-T);break;case c:if(i){if(f&&(r=_r(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+Lr)),f.size+=e+Lr-T);break;case u:i&&(g&&(r=_r(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+Lr)),g.size+=e+Lr-T);break;case 0:i&&(T+=t[T]+1),v=this._pmtId=br(t,T);break;case v:{i&&(T+=t[T]+1);const r=Ir(t,T,this.typeSupported,s,this.observer,this.logger);h=r.videoPid,h>0&&(n.pid=h,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&kr(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;let e;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(t){const{audioTrack:e,videoTrack:s,id3Track:i,textTrack:r}=t,n=s.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=_r(n,this.logger))){if(null===this.videoParser)switch(s.segmentCodec){case"avc":this.videoParser=new Tr;break;case"hevc":this.videoParser=new Sr}null!==this.videoParser&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)}else s.pesData=n;if(a&&(l=_r(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=_r(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,s){const i=this.demux(t,s,!0,!this.config.progressive),r=this.sampleAes=new vr(this.observer,this.config,e);return this.decrypt(i,r)}decrypt(t,e){return new Promise((s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)})):s(t)})):r.samples&&e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let s=0;const i=this.aacOverFlow;let r,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,r=i.sample.unit.byteLength;if(-1===e)o=pt(i.sample.unit,o);else{const n=r-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=E({},e,{type:this._videoTrack?Zi.emsg:Zi.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function Rr(t,e){return((31&t[e+1])<<8)+t[e+2]}function br(t,e){return(31&t[e+10])<<8|t[e+11]}function Ir(t,e,s,i,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e0){let i=e+5,r=l;for(;r>2;){if(106===t[i])!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return kr(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=l+5}return a}function kr(t,e,s,i){i.warn(`parsing error: ${e.message}`),t.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:e,reason:e.message})}function Dr(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function _r(t,e){let s,i,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=pt(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(i=(s[4]<<8)+s[5],i&&i>t.size-6)return null;const h=s[7];192&h&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&h?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=s[8];let d=r+9;if(t.size<=d)return null;t.size-=d;const c=new Uint8Array(t.size);for(let t=0,e=l.length;te){d-=e;continue}s=s.subarray(d),e-=d,d=0}c.set(s,o),o+=e}return i&&(i-=r+3),{data:c,pts:n,dts:a,len:i}}return null}class Pr{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Cr=Math.pow(2,32)-1;class wr{static init(){let t;for(t in wr.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:[]},wr.types)wr.types.hasOwnProperty(t)&&(wr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);wr.HDLR_TYPES={video:e,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);wr.STTS=wr.STSC=wr.STCO=r,wr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),wr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),wr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),wr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);wr.FTYP=wr.box(wr.types.ftyp,n,o,n,a),wr.DINF=wr.box(wr.types.dinf,wr.box(wr.types.dref,i))}static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),i=0,s=8;i>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return wr.box(wr.types.mdia,wr.mdhd(t.timescale||0,t.duration||0),wr.hdlr(t.type),wr.minf(t))}static mfhd(t){return wr.box(wr.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?wr.box(wr.types.minf,wr.box(wr.types.smhd,wr.SMHD),wr.DINF,wr.stbl(t)):wr.box(wr.types.minf,wr.box(wr.types.vmhd,wr.VMHD),wr.DINF,wr.stbl(t))}static moof(t,e,s){return wr.box(wr.types.moof,wr.mfhd(t),wr.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=wr.trak(t[e]);return wr.box.apply(null,[wr.types.moov,wr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(s).concat(wr.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=wr.trex(t[e]);return wr.box.apply(null,[wr.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(Cr+1)),i=Math.floor(e%(Cr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,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 wr.box(wr.types.mvhd,r)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,r;for(i=0;i>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(e=0;e>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=wr.box(wr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return wr.box(wr.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,wr.box(wr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),wr.box(wr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const e=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return wr.box(wr.types.mp4a,wr.audioStsd(t),wr.box(wr.types.esds,wr.esds(t)))}static mp3(t){return wr.box(wr.types[".mp3"],wr.audioStsd(t))}static ac3(t){return wr.box(wr.types["ac-3"],wr.audioStsd(t),wr.box(wr.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return wr.box(wr.types.stsd,wr.STSD,wr.mp4a(t));if("ac3"===e&&t.config)return wr.box(wr.types.stsd,wr.STSD,wr.ac3(t));if("mp3"===e&&"mp3"===t.codec)return wr.box(wr.types.stsd,wr.STSD,wr.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return wr.box(wr.types.stsd,wr.STSD,wr.avc1(t));if("hevc"===e&&t.vps)return wr.box(wr.types.stsd,wr.STSD,wr.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,s=(t.duration||0)*(t.timescale||0),i=t.width||0,r=t.height||0,n=Math.floor(s/(Cr+1)),a=Math.floor(s%(Cr+1));return wr.box(wr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,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,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const s=wr.sdtp(t),i=t.id,r=Math.floor(e/(Cr+1)),n=Math.floor(e%(Cr+1));return wr.box(wr.types.traf,wr.box(wr.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),wr.box(wr.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),wr.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,wr.box(wr.types.trak,wr.tkhd(t),wr.mdia(t))}static trex(t){const e=t.id;return wr.box(wr.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const s=t.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return wr.box(wr.types.trun,n)}static initSegment(t){wr.types||wr.init();const e=wr.moov(t);return pt(wr.FTYP,e)}static hvc1(t){const e=t.params,s=[t.vps,t.sps,t.pps],i=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),s.length]);let r=i.length;for(let t=0;t>8,255&s[t][e].length]),r),r+=2,n.set(s[t][e],r),r+=s[t][e].length}const o=wr.box(wr.types.hvcC,n),l=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return wr.box(wr.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,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,wr.box(wr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),wr.box(wr.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}}wr.types=void 0,wr.HDLR_TYPES=void 0,wr.STTS=void 0,wr.STSC=void 0,wr.STCO=void 0,wr.STSZ=void 0,wr.VMHD=void 0,wr.SMHD=void 0,wr.STSD=void 0,wr.FTYP=void 0,wr.DINF=void 0;function xr(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function Or(t,e=!1){return xr(t,1e3,1/9e4,e)}let Mr,Fr=null,Nr=null;function Ur(t,e,s,i){return{duration:e,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class Br{constructor(t,e,s,i){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.logger=i,this.ISGenerated=!1,null===Fr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Fr=t?parseInt(t[1]):0}if(null===Nr){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Nr=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t[0].pts,i=t.reduce(((t,i)=>{let r=i.pts,n=r-t;return n<-4294967296&&(e=!0,r=$r(r,s),n=r-t),n>0?t:r}),s);return e&&this.logger.debug("PTS rollover detected"),i}remux(t,e,s,i,r,n,a,o){let l,h,d,c,u,f,m=r,p=r;const v=t.pid>-1,y=e.pid>-1,E=e.samples.length,T=t.samples.length>0,S=a&&E>0||E>1;if((!v||T)&&(!y||S)||this.ISGenerated||a){if(this.ISGenerated){var L,A,R,b;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(L=e.pixelRatio)?void 0:L[0])!==(null==(A=t.pixelRatio)?void 0:A[0])||(null==(R=e.pixelRatio)?void 0:R[1])!==(null==(b=t.pixelRatio)?void 0:b[1]))||!t&&S||null===this.nextAudioPts&&T)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(t,e,r,n));const s=this.isVideoContiguous;let i,a=-1;if(S&&(a=function(t){for(let e=0;e0){this.logger.warn(`[mp4-remuxer]: Dropped ${a} out of ${E} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,i=p}else-1===a&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(T&&S){const s=this.getVideoStartPts(e.samples),i=($r(t.samples[0].pts,s)-s)/e.inputTimeScale;m+=Math.max(0,i),p+=Math.max(0,-i)}if(T){if(t.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,r,n)),h=this.remuxAudio(t,m,this.isAudioContiguous,n,y||S||o===g?p:void 0),S){const i=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,p,s,i)}}else S&&(l=this.remuxVideo(e,p,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Gr(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=Kr(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4";if(u&&(h=d=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):wr.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(c=t.inputTimeScale,l&&c===l.timescale?u=!1:h=d=r[0].pts-Math.round(c*s))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:wr.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=Math.round(c*s);d=Math.min(d,$r(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:d,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(t,e,s,i){const r=t.inputTimeScale,n=t.samples,h=[],d=n.length,c=this._initPTS;let u,f,g=this.nextAvcDts,m=8,p=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,T=!1;if(!s||null===g){const t=e*r,i=n[0].pts-$r(n[0].dts,n[0].pts);Fr&&null!==g&&Math.abs(t-i-g)<15e3?s=!0:g=t-i}const S=c.baseTime*r/c.timescale;for(let t=0;t0?t-1:t].dts&&(T=!0)}T&&n.sort((function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i})),u=n[0].dts,f=n[n.length-1].dts;const L=f-u,A=L?Math.round(L/(d-1)):p||t.inputTimeScale/30;if(s){const s=u-g,i=s>A,r=s<-1;if((i||r)&&(i?this.logger.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Or(s,!0)} ms (${s}dts) hole between fragments detected at ${e.toFixed(3)}`):this.logger.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Or(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||g>=n[0].pts||Fr)){u=g;const t=n[0].pts-s;if(i)n[0].dts=u,n[0].pts=t;else{let e=!0;for(let i=0;it&&e);i++){const t=n[i].pts;if(n[i].dts-=s,n[i].pts-=s,i0?e.dts-n[t-1].dts:A;if(a=t>0?e.pts-n[t-1].pts:A,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*r),n=(i?v+i*r:this.nextAudioPts)-e.pts;n>t?(p=n-o,p<0?p=o:P=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=o}else p=o}const l=Math.round(e.pts-e.dts);C=Math.min(C,p),x=Math.max(x,p),w=Math.min(w,a),O=Math.max(O,a),h.push(Ur(e.key,p,o,l))}if(h.length)if(Fr){if(Fr<70){const t=h[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Nr&&O-w0&&(i&&Math.abs(T-y)<9e3||Math.abs($r(p[0].pts-S,T)-y)<20*c),p.forEach((function(t){t.pts=$r(t.pts-S,T)})),!s||y<0){if(p=p.filter((t=>t.pts>=0)),!p.length)return;y=0===r?0:i&&!m?Math.max(0,T):p[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=y;s=e*c&&l<1e4&&m){let e=Math.round(o/c);i=a-e*c,i<0&&(e--,i+=c),0===s&&(this.nextAudioPts=y=i),this.logger.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(i/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n0))return;b+=v;try{L=new Uint8Array(b)}catch(t){return void this.observer.emit(l.ERROR,l.ERROR,{type:a.MUX_ERROR,details:o.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:b,reason:`fail allocating audio mdat ${b}`})}if(!f){new DataView(L.buffer).setUint32(0,b),L.set(wr.types.mdat,4)}}L.set(r,v);const c=r.byteLength;v+=c,g.push(Ur(!0,d,c,0)),R=n}const k=g.length;if(!k)return;const D=g[g.length-1];this.nextAudioPts=y=R+h*D.duration;const _=f?new Uint8Array(0):wr.moof(t.sequenceNumber++,A/h,E({},t,{samples:g}));t.samples=[];const P=A/n,C=y/n,w={data1:_,data2:L,startPTS:P,endPTS:C,startDTS:P,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,w}}function $r(t,e){let s;if(null===e)return t;for(s=e4294967296;)t+=s;return t}function Gr(t,e,s,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;at.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}function Hr(t,e){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(e===H){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Ot(s,!1)}return D.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return D.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}try{Mr=self.performance.now.bind(self.performance)}catch(t){Mr=Date.now}const Vr=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=Ji("video",1),n=this.audioTrack=Ji("audio",1),a=this.txtTrack=Ji("text",1);if(this.id3Track=Ji("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=lt(t);if(o.video){const{id:t,timescale:e,codec:s,supplemental:i}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s,r.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=J.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=i>1?s+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=pt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=at(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(s);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,e);return r.samples=vt(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return s.samples=vt(t,e),{videoTrack:e,audioTrack:Ji(),id3Track:i,textTrack:Ji()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=at(t.samples,["emsg"]);i&&i.forEach((t=>{const i=function(t){const e=t[0];let s="",i="",n=0,a=0,o=0,l=0,h=0,d=0;if(0===e){for(;"\0"!==tt(t.subarray(d,d+1));)s+=tt(t.subarray(d,d+1)),d+=1;for(s+=tt(t.subarray(d,d+1)),d+=1;"\0"!==tt(t.subarray(d,d+1));)i+=tt(t.subarray(d,d+1)),d+=1;i+=tt(t.subarray(d,d+1)),d+=1,n=st(t,12),a=st(t,16),l=st(t,20),h=st(t,24),d=28}else if(1===e){d+=4,n=st(t,d),d+=4;const e=st(t,d);d+=4;const a=st(t,d);for(d+=4,o=2**32*e+a,r(o)||(o=Number.MAX_SAFE_INTEGER,D.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=st(t,d),d+=4,h=st(t,d),d+=4;"\0"!==tt(t.subarray(d,d+1));)s+=tt(t.subarray(d,d+1)),d+=1;for(s+=tt(t.subarray(d,d+1)),d+=1;"\0"!==tt(t.subarray(d,d+1));)i+=tt(t.subarray(d,d+1)),d+=1;i+=tt(t.subarray(d,d+1)),d+=1}return{schemeIdUri:s,value:i,timeScale:n,presentationTime:o,presentationTimeDelta:a,eventDuration:l,id:h,payload:t.subarray(d,t.byteLength)}}(t);if(mr.test(i.schemeIdUri)){const t=pr(i,e);let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Zi.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=pr(i,e);s.samples.push({data:i.payload,len:i.payload.byteLength,dts:t,pts:t,type:Zi.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return s}demuxSampleAes(t,e,s){return Promise.reject(new 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}},remux:class{constructor(t,e,s,i){this.logger=void 0,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.logger=i}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(function(t,e){if(!t||!e)return t;const s=e.keyId;s&&e.isCommonEncryption&&at(t,["moov","trak"]).forEach((t=>{const e=at(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let i=at(e,["enca"]);const r=i.length>0;r||(i=at(e,["encv"])),i.forEach((t=>{at(r?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=gt(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(D.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${w(t)} -> ${w(s)}`),e.set(s,8))}}))}))}));return t}(t,i)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const i=this.initData=lt(t);i.audio&&(e=Hr(i.audio,H)),i.video&&(s=Hr(i.video,V));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:e+","+s,supplemental:i.video.supplemental,initSegment:t,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,supplemental:i.video.supplemental,initSegment:t,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(t,e,s,r,n,a){var o,l;let{initPTS:h,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};i(d)||(d=this.lastEndTime=n||0);const u=e.samples;if(null==u||!u.length)return c;const f={initPTS:void 0,timescale:1};let g=this.initData;if(null!=(o=g)&&o.length||(this.generateInitSegment(u),g=this.initData),null==(l=g)||!l.length)return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,e){let s=0,r=0,n=0;const a=at(t,["moof","traf"]);for(let t=0;tt+e.info.duration||0),0);s=Math.max(s,t+i.earliestPresentationTime/i.timescale),r=s-e}}if(r&&i(r))return r}return r||n}(u,g),p=function(t,e){return at(e,["moof","traf"]).reduce(((e,s)=>{const r=at(s,["tfdt"])[0],n=r[0],a=at(s,["tfhd"]).reduce(((e,s)=>{const a=st(s,4),o=t[a];if(o){let t=st(r,4);if(1===n){if(t===Q)return D.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=Q+1,t+=st(r,8)}const s=t/(o.timescale||9e4);if(i(s)&&(null===e||sr}(h,v,n,m)&&f.timescale===h.timescale||(f.initPTS=v-n,h&&1===h.timescale&&this.logger.warn(`Adjusting initPTS @${n} from ${h.baseTime/h.timescale} to ${f.initPTS}`),this.initPTS=h={baseTime:f.initPTS,timescale:1});const y=t?v-h.baseTime/h.timescale:d,E=y+m;!function(t,e,s){at(e,["moof","traf"]).forEach((e=>{at(e,["tfhd"]).forEach((i=>{const r=st(i,4),n=t[r];if(!n)return;const a=n.timescale||9e4;at(e,["tfdt"]).forEach((t=>{const e=t[0],i=s*a;if(i){let s=st(t,4);if(0===e)s-=i,s=Math.max(s,0),nt(t,4,s);else{s*=Math.pow(2,32),s+=st(t,8),s-=i,s=Math.max(s,0);const e=Math.floor(s/(Q+1)),r=Math.floor(s%(Q+1));nt(t,4,e),nt(t,8,r)}}}))}))}))}(g,u,h.baseTime/h.timescale),m>0?this.lastEndTime=E:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!g.audio,S=!!g.video;let L="";T&&(L+="audio"),S&&(L+="video");const A={data1:u,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:L,hasAudio:T,hasVideo:S,nb:1,dropped:0};return c.audio="audio"===A.type?A:void 0,c.video="audio"!==A.type?A:void 0,c.initSegment=f,c.id3=Gr(s,n,h,h),r.samples.length&&(c.text=Kr(r,n,h)),c}}},{demux:Ar,remux:Br},{demux:class extends tr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const s=xi(t,0);let i=(null==s?void 0:s.length)||0;if(cr(t,i))return!1;for(let s=t.length;i0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(L&&as(L.method)){const t=this.getDecrypter(),e=os(L.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,L.key.buffer,L.iv.buffer,e).then((t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e})),this.decryptionPromise;{let i=t.softwareDecrypt(n,L.key.buffer,L.iv.buffer,e);if(s.part>-1){const e=t.flush();i=e?e.buffer:e}if(!i)return r.executeEnd=Mr(),Wr(s);n=new Uint8Array(i)}}const A=this.needsProbing(u,f);if(A){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=Mr(),Wr(s)}(u||f||p||A)&&this.resetInitSegment(S,v,y,T,e),(u||p||A)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const R=this.transmux(n,L,m,g,s);this.asyncResult=jr(R);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,r.executeEnd=Mr(),R}flush(t){const e=t.transmuxing;e.executeStart=Mr();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then((()=>this.flush(t)));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Mr();const s=[Wr(t)];return this.asyncResult?Promise.resolve(s):s}const h=o.flush(a);return jr(h)?(this.asyncResult=!0,h.then((e=>(this.flushRemux(n,e,t),n)))):(this.flushRemux(n,h,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===f?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Mr()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,i),a.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,i,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer.demuxSampleAes(t,e,s).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id),chunkMeta:r})))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i}=this;let r;for(let e=0,s=Vr.length;e({remuxResult:{},chunkMeta:t});function jr(t){return"then"in t&&t.then instanceof Function}class qr{constructor(t,e,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Xr{constructor(t,e,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let zr=0;class Qr{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=zr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,s=this.hls;if(s&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":s.logger[e.data.logType]&&s.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,s.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===l.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new ki,this.observer.on(l.FRAG_DECRYPTED,n),this.observer.on(l.ERROR,n);const h=Nt(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(s.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=_i[t];if(e)return e.clientCount++,e;const s=new self.URL(t,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return _i[t]=i,i}(r.workerPath)):(s.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=_i[Di];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(e),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return _i[Di]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:h,id:e,config:te(r)})}catch(i){s.warn(`Error setting up "${e}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Yr(this.observer,h,r,"",e,t.logger)}return}}this.transmuxer=new Yr(this.observer,h,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=zr++;const e=this.hls.config,s=Nt(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:te(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=_i[t||Di];if(e&&1==e.clientCount--){const{worker:s,objectURL:i}=e;delete _i[t||Di],i&&self.URL.revokeObjectURL(i),s.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:g}=this,m=n?n.start:r.start,p=r.decryptdata,v=this.frag,y=!(v&&r.cc===v.cc),E=!(v&&l.level===v.level),T=v?l.sn-v.sn:-1,S=this.part?l.part-this.part.index:-1,L=0===T&&l.id>1&&l.id===(null==v?void 0:v.stats.chunkCount),A=!E&&(1===T||0===T&&(1===S||L&&S<=0)),R=self.performance.now();(E||T||0===r.stats.parsing.start)&&(r.stats.parsing.start=R),!n||!S&&A||(n.stats.parsing.start=R);const b=!(v&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=v.initSegment)?void 0:c.url)),I=new Xr(y,A,o,E,m,b);if(!A||y||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===f?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${y}\n trackSwitch: ${E}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${m}\n initSegmentChange: ${b}`);const t=new qr(s,i,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:I},t instanceof ArrayBuffer?[t]:[]);else if(g){const e=g.push(t,p,l,I);jr(e)?e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(s){const e=s.flush(t);jr(e)?e.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")})):this.handleFlushResult(e,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class Zr extends L{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=null==e?void 0:e.renditionReports;if(i){let r=-1;for(let s=0;s=0&&t>e.partTarget&&(a+=1)}const o=s&&Xt(s);return new zt(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,s){const{details:i,stats:r}=e,n=self.performance.now(),h=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-h;const d=this.hls.config.timelineOffset;if(d!==i.appliedTimelineOffset){const t=Math.max(d||0,0);i.appliedTimelineOffset=t,i.fragments.forEach((e=>{e.start=e.playlistOffset+t}))}if(i.live||null!=s&&s.live){const d="levelInfo"in e?e.levelInfo:e.track;if(i.reloaded(s),s&&i.fragments.length>0){Xs(s,i);const t=i.playlistParsingError;if(t){this.warn(t);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var c;const{networkDetails:n}=e;return void s.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(c=i.fragments[0])?void 0:c.type,networkDetails:n,stats:r})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,f=u?u.end-u.len:0,g=Js(i,1e3*(i.edge-f));if(i.requestScheduled+g0){if(c>3*i.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=s&&s.tuneInGoal&&c-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${u} with playlist age: ${i.age}`),u=0;else{const t=Math.floor(u/i.targetduration);if(p+=t,void 0!==v){v+=Math.round(u%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${u} skip sn ${t} to part ${v}`)}i.tuneInGoal=u}if(m=this.getDeliveryDirectives(i,e.deliveryDirectives,p,v),t||!l)return i.requestScheduled=n,void this.loadingPlaylist(d,m)}else(i.canBlockReload||i.canSkipUntil)&&(m=this.getDeliveryDirectives(i,e.deliveryDirectives,p,v));m&&void 0!==p&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(g-2*h,g/2)),this.scheduleLoading(d,m,i)}else this.clearTimer()}scheduleLoading(t,e,s){const i=s||t.details;if(!i)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=i.requestScheduled;if(r>=n)return void this.loadingPlaylist(t,e);const a=n-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(t,e)),a)}getDeliveryDirectives(t,e,s,i){let r=Xt(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=Wt),new zt(s,i,r)}checkRetry(t){const e=t.details,s=ge(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Le||!i.resolved&&r===Te);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=pe(a,n);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,i.resolved=!0}return o}}function Jr(t,e){if(t.length!==e.length)return!1;for(let s=0;st[s]!==e[s]))}function en(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class sn{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,s){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}appendBlocker(t){return new Promise((e=>{const s={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,t)}))}prependBlocker(t){return new Promise((e=>{if(this.queues){const s={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(s)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((t=>{var e;const s=null==(e=t[0])?void 0:e.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(t[0].execute(),t.splice(0,1))}))}unblockAudio(t){if(null===this.queues)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(e){var s;if(i.onError(e),null===this.queues||null===this.tracks)return;const r=null==(s=this.tracks[t])?void 0:s.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,s;return null!=(e=this.queues)&&e[t]||null!=(s=this.tracks)&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const s=null==(e=this.tracks)?void 0:e[t],i=null==s?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map((t=>t.label)).join(", "))||""}}const rn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,nn="HlsJsTrackRemovedError";class an extends Error{constructor(t){super(t),this.name=nn}}function on(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}function ln(t){return"audio"===t?1:0}class hn{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(l.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.BUFFER_CODECS,this.onBufferCodecs,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(l.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.BUFFER_CODECS,this.onBufferCodecs,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&i(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const s=e.filter(((e,s)=>this.isLevelAllowed(e)&&s<=t));return this.clientRect=null,hn.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,s){if(null==t||!t.length)return-1;let i=t.length-1;const r=Math.max(e,s);for(let e=0;e=r||s.height>=r)&&(n=s,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){i=e;break}}var n,a;return i}}const dn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},cn={HLS:"h"},un="CMCD-Request",fn={["CMCD-Object"]:["br","d","ot","tb"],[un]:["bl","dl","mtp","nor","nrr","su"],["CMCD-Session"]:["cid","pr","sf","sid","st","v"],["CMCD-Status"]:["bs","rtp"]};class gn{constructor(t,e){Array.isArray(t)&&(t=t.map((t=>t instanceof gn?t:new gn(t)))),this.value=t,this.params=e}}function mn(t,e,s,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}function pn(t,e,s){return mn("serialize",t,e,s)}class vn{constructor(t){this.description=t}}const yn="Bare Item";function En(t){if(!1===ArrayBuffer.isView(t))throw pn(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Tn(t){if(function(t){return t<-999999999999999||99999999999999912)throw pn(t,"Decimal");const s=e.toString();return s.includes(".")?s:`${s}.0`}const Ln=/[\x00-\x1f\x7f]+/;function An(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw pn(e,"Token");return e}function Rn(t){switch(typeof t){case"number":if(!i(t))throw pn(t,yn);return Number.isInteger(t)?Tn(t):Sn(t);case"string":return function(t){if(Ln.test(t))throw pn(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return An(t);case"boolean":return function(t){if("boolean"!=typeof t)throw pn(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Tn(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return En(t);if(t instanceof vn)return An(t);default:throw pn(t,yn)}}function bn(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw pn(t,"Key");return t}function In(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${bn(t)}`:`;${bn(t)}=${Rn(e)}`)).join("")}function kn(t){return t instanceof gn?`${Rn(t.value)}${In(t.params)}`:Rn(t)}function Dn(t,e={whitespace:!0}){if("object"!=typeof t)throw pn(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),i=(null==e?void 0:e.whitespace)?" ":"";return Array.from(s).map((([t,e])=>{e instanceof gn==!1&&(e=new gn(e));let s=bn(t);var i;return!0===e.value?s+=In(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(kn).join(" ")})${In(i.params)}`:s+=kn(e)),s})).join(`,${i}`)}const _n=t=>Math.round(t),Pn=t=>100*_n(t/100),Cn={br:_n,d:_n,bl:Pn,dl:Pn,mtp:Pn,nor:(t,e)=>((null==e?void 0:e.baseUrl)&&(t=function(t,e){const s=new URL(t),i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:Pn,tb:_n};function wn(t,e){const s={};if(null==t||"object"!=typeof t)return s;const r=Object.keys(t).sort(),n=E({},Cn,null==e?void 0:e.formatters),a=null==e?void 0:e.filter;return r.forEach((r=>{if(null==a?void 0:a(r))return;let o=t[r];const l=n[r];l&&(o=l(o,e)),"v"===r&&1===o||"pr"==r&&1===o||function(t){return"number"==typeof t?i(t):null!=t&&""!==t&&!1!==t}(o)&&(function(t){return"ot"===t||"sf"===t||"st"===t}(r)&&"string"==typeof o&&(o=new vn(o)),s[r]=o)})),s}function xn(t,e={}){return t?function(t,e){return Dn(t,e)}(wn(t,e),E({whitespace:!1},e)):""}function On(t,e,s){return E(t,function(t,e={}){const s={};if(!t)return s;const i=Object.entries(t),r=Object.entries(fn).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),n=i.reduce(((t,e)=>{var s,i;const[n,a]=e,o=(null===(s=r.find((t=>t[1].includes(n))))||void 0===s?void 0:s[0])||un;return null!==(i=t[o])&&void 0!==i||(t[o]={}),t[o][n]=a,t}),{});return Object.entries(n).reduce(((t,[s,i])=>(t[s]=xn(i,e),t)),s)}(e,s))}const Mn=/CMCD=[^&#]+/;function Fn(t,e,s){const i=function(t,e={}){if(!t)return"";const s=xn(t,e);return`CMCD=${encodeURIComponent(s)}`}(e,s);if(!i)return t;if(Mn.test(t))return t.replace(Mn,i);const r=t.includes("?")?"&":"?";return`${t}${r}${i}`}function Nn(t,e,s,i){t&&Object.keys(e).forEach((r=>{const n=t.filter((t=>t.groupId===r)).map((t=>{const n=E({},t);return n.details=void 0,n.attrs=new ss(n.attrs),n.url=n.attrs.URI=Un(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n}));t.push(...n)}))}function Un(t,e,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}class Bn extends L{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Bn.CDMCleanupPromise?[Bn.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:e,initData:s}=t,i=`"${t.type}" event: init data type: "${e}"`;if(this.debug(i),null!==s){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Rs(this.config));const e=t.map(As).filter((t=>!!t));this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then((r=>{const n=vs(r);let a,o;if("sinf"===e){if(n!==us.FAIRPLAY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);const r=tt(new Uint8Array(s));try{const t=gt(ls(JSON.parse(r).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24)),o=us.FAIRPLAY}catch(t){return void this.warn(`${i} Failed to parse sinf: ${t}`)}}else{if(n!==us.WIDEVINE&&n!==us.PLAYREADY)return void this.warn(`Ignoring unexpected "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);const r=function(t){const e=[];if(t instanceof ArrayBuffer){const s=t.byteLength;let i=0;for(;i+32!!t.systemId&&Ls(t.systemId)===n));l.length>1&&this.warn(`${i} Using first of ${l.length} pssh found for selected key-system ${n}`);const h=l[0];if(!h)return void(0===r.length||r.some((t=>!t.systemId))?this.warn(`${i} contains incomplete or invalid pssh data`):this.log(`ignoring ${i} for ${r.map((t=>Ls(t.systemId))).join(",")} pssh data in favor of playlist keys`));if(o=Ls(h.systemId),0===h.version&&h.data)if(o===us.WIDEVINE){const t=h.data.length-22;a=new Uint8Array(h.data.subarray(t,t+16))}else o===us.PLAYREADY&&(a=ks(h.data))}if(!o||!a)return;const l=w(a),{keyIdToKeySessionPromise:h,mediaKeySessions:d}=this;let c=h[l];for(let t=0;tthis.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match"))),c.catch((t=>this.handleError(t)));break}}if(!c){if(o!==n)return void this.log(`Ignoring "${t.type}" event with ${o} init data for selected key-system ${n}`);c=h[l]=this.getKeySystemSelectionPromise([o]).then((({keySystem:t,mediaKeys:i})=>{var r;this.throwIfDestroyed();const n=new _s("ISO-23001-7",l,null!=(r=As(t))?r:"");return n.pssh=new Uint8Array(s),n.keyId=a,this.attemptSetMediaKeys(t,i).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:n,keySystem:t,mediaKeys:i});return this.generateRequestWithPreferredKeySession(r,e,s,"encrypted-event-no-match")}))})),c.catch((t=>this.handleError(t)))}}))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){const t=this.media;this.unregisterListeners(),this.onMediaDetached(),this._clear(t);const 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(l.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(l.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(l.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(l.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(l.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(l.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(l.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,i=e[t];return i?i.licenseUrl:t===us.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error(`no license server URL configured for key-system "${t}"`);return e}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map((t=>t.audioCodec)).filter(s),r=e.map((t=>t.videoCodec)).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise(((e,s)=>{const n=t=>{const l=t.shift();this.getMediaKeysPromise(l,i,r).then((t=>e({keySystem:l,mediaKeys:t}))).catch((e=>{t.length?n(t):s(e instanceof $n?e:new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===bs&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){const i=function(t,e,s,i){let r;switch(t){case us.FAIRPLAY:r=["cenc","sinf"];break;case us.WIDEVINE:case us.PLAYREADY:r=["cenc"];break;case us.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs=${t}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}))),videoCapabilities:s.map((t=>({contentType:`video/mp4; codecs=${t}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null})))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[t];let n=null==r?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${te(i)}`),n=this.requestMediaKeySystemAccess(t,i);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),n.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=s.createMediaKeys().then((e=>(this.log(`Media-keys created for "${t}"`),i.then((s=>s?this.setMediaKeysServerCertificate(e,t,s):e))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return n.then((()=>r.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${w(t.keyId||[])}`);const i=s.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),i=this.getKeyIdString(e),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return w(t.keyId)}updateKeySession(t,e){var s;const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${w((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),i.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((e,s)=>{const i=Rs(this.config),r=t.map(vs).filter((t=>!!t&&-1!==i.indexOf(t)));return this.getKeySystemSelectionPromise(r).then((({keySystem:t})=>{const i=As(t);i?e(i):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)}))}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),i=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];if(!r){r=this.getKeySystemForKeyPromise(e).then((({keySystem:s,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(s,r).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:r,decryptdata:e})))))));(this.keyIdToKeySessionPromise[s]=r.then((t=>{const s=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",s,"playlist-key")}))).catch((t=>this.handleError(t)))}return r}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof $n?this.hls.trigger(l.ERROR,t.data):this.hls.trigger(l.ERROR,{type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=vs(t.keyFormat),s=e?[e]:Rs(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=Rs(this.config)),0===t.length)throw new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${te({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(i),i.then((()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===s.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,s,i){var r,n;const l=null==(r=this.config.drmSystems)||null==(n=r[t.keySystem])?void 0:n.generateRequest;if(l)try{const i=l.call(this.hls,e,s,t);if(!i)throw new Error("Invalid response from configured generateRequest filter");e=i.initDataType,s=i.initData?i.initData:null,t.decryptdata.pssh=s?new Uint8Array(s):null}catch(t){var h;if(this.warn(t.message),null!=(h=this.hls)&&h.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t);const d=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${i}": ${d} (init data type: ${e} length: ${s?s.byteLength:null})`);const c=new ki,u=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void c.emit("error",new Error("invalid state"));const{messageType:i,message:r}=e;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(t,r).catch((t=>{c.eventNames().length?c.emit("error",t):this.handleError(t)})):"license-release"===i?t.keySystem===us.FAIRPLAY&&(this.updateKeySession(t,hs("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${i}"`)},f=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void c.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;c.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${d}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",u),t.mediaKeysSession.addEventListener("keystatuseschange",f);const g=new Promise(((t,e)=>{c.on("error",e),c.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)}))}));return t.mediaKeysSession.generateRequest(e,s).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${d}`)})).catch((t=>{throw new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>g)).catch((e=>{throw c.removeAllListeners(),this.removeSession(t),e})).then((()=>(c.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${w("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${w(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise(((r,n)=>{const l={responseType:"arraybuffer",url:i},h=e.certLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,h)=>{n(new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:S({url:l.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}};s.load(l,d,c)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise(((i,r)=>{t.setServerCertificate(s).then((r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${e}"`),i(t)})).catch((t=>{r(new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then((e=>this.updateKeySession(t,new Uint8Array(e)).catch((t=>{throw new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s in key message");return hs(atob(l))}setupLicenseXHR(t,e,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,s,i)})).catch((n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,s,i)})).then((s=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:s||i}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise(((i,r)=>{const n=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${n}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===l.readyState)if(200===l.status){this._requestLicenseFailureCount=0;let e=l.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,l,n,t)}catch(t){this.error(t)}i(e)}else{const h=s.errorRetry,d=h?h.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||l.status>=400&&l.status<500)r(new $n({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:l,response:{url:n,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${n}). Status: ${l.status} (${l.statusText})`));else{const s=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(i,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=l,this.setupLicenseXHR(l,n,t,e).then((({xhr:e,licenseChallenge:s})=>{t.keySystem==us.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}))}))}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.removeEventListener("encrypted",this.onMediaEncrypted),s.removeEventListener("waitingforkey",this.onWaitingForKey),s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null)}_clear(t){var e;const s=this.mediaKeySessions;this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},_s.clearKeyUriToKeyIdMap();const i=s.length;Bn.CDMCleanupPromise=Promise.all(s.map((t=>this.removeSession(t))).concat(null==t||null==(e=t.setMediaKeys(null))?void 0:e.catch((t=>{var e;this.log(`Could not clear media keys: ${t}`),null==(e=this.hls)||e.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})})))).then((()=>{i&&(this.log("finished closing key sessions and clearing media keys"),s.length=0)})).catch((t=>{var e;this.log(`Could not close sessions and clear media keys: ${t}`),null==(e=this.hls)||e.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce(((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);return i>-1&&this.mediaKeySessions.splice(i,1),e.remove().catch((t=>{var e;this.log(`Could not remove session: ${t}`),null==(e=this.hls)||e.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})})).then((()=>e.close())).catch((t=>{var e;this.log(`Could not close session: ${t}`),null==(e=this.hls)||e.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})}))}}}Bn.CDMCleanupPromise=void 0;class $n extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}function Gn(t,e){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function Kn(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){D.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){D.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function Hn(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues)for(let s=t.cues.length;s--;)e&&t.cues[s].removeEventListener("enter",e),t.removeCue(t.cues[s]);"disabled"===s&&(t.mode=s)}function Vn(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(e<=t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let i,r=0,n=s;for(;r<=n;)if(i=Math.floor((n+r)/2),et[i].startTime&&r-1)for(let n=r,a=t.length;n=e&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e>>0).toString()}const jn=.025;let qn=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Xn(t,e,s){return`${t.identifier}-${s+1}-${Wn(e)}`}class zn{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){if(t>=this.assetList.length)return!0;const e=this.playoutLimit;if(t<=0||isNaN(e))return!1;return this.assetList[t].startOffset>e}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return Qn(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-Qn(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=i(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return Qn(t,e)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"
":t.cue.post?"":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Qn(t,e){return t-e.start{const t=this.interstitial.playoutLimit,e=this.currentTime;this.startOffset+e>=t&&this.hls.trigger(l.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=s,this.assetItem=i;let n=i.uri;try{n=Zn(n,r.sessionId).href}catch(t){}r.loadSource(n);const a=()=>{this.hasDetails=!0};r.once(l.LEVEL_LOADED,a),r.once(l.AUDIO_TRACK_LOADED,a),r.once(l.SUBTITLE_TRACK_LOADED,a),r.on(l.MEDIA_ATTACHING,((t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&e.addEventListener("timeupdate",this.checkPlayout)}))}bufferedInPlaceToEnd(t){var e;if(!this.interstitial.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t||!this._bufferedEosTime)return!1;const s=this.timelineOffset,i=qe.bufferInfo(t,s,0);return this.getAssetTime(i.end)>=this._bufferedEosTime-.02}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=qe.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;return t||0}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const s=t-e;if(Math.abs(s)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,t-e),s)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){this.hls.attachMedia(t)}detachMedia(){this.removeMediaListeners(),this.mediaAttached=null,this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls.transferMedia()}on(t,e,s){this.hls.on(t,e)}once(t,e,s){this.hls.once(t,e)}off(t,e,s){this.hls.off(t,e)}toString(){var t,e;return`HlsAssetPlayer: ${Jn(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${null!=(e=this.interstitial)&&e.appendInPlace?"append-in-place":""}`}}class ea extends L{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((t=>t.reset())),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce(((s,i)=>t<=i.startOffset&&e>i.startOffset?(delete i.error,s+1):s),0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(void 0===e&&(e=t.start),s=this.findItemIndexAtTime(e));s>=0&&null!=(r=i[s])&&r.event;){var r;s--}return s}findItemIndexAtTime(t,e){const s=this.items;if(s)for(let i=0;ir.start&&t1)for(let t=0;ts&&e!a.includes(t.identifier))):[];n.length&&n.sort(((t,e)=>{const s=t.cue.pre,i=t.cue.post,r=e.cue.pre,n=e.cue.post;if(s&&!r)return-1;if(r&&!s)return 1;if(i&&!n)return 1;if(n&&!i)return-1;if(!(s||r||i||n)){const s=t.startTime,i=e.startTime;if(s!==i)return s-i}return t.dateRange.tagOrder-e.dateRange.tagOrder})),this.events=n,o.forEach((t=>{this.removeEvent(t)})),this.updateSchedule(t,o)}updateSchedule(t,e=[]){const s=this.events||[];if(s.length||e.length||this.length<2){const i=this.items,r=this.parseSchedule(s,t);(e.length||(null==i?void 0:i.length)!==r.length||r.some(((t,e)=>Math.abs(t.playout.start-i[e].playout.start)>.005||Math.abs(t.playout.end-i[e].playout.end)>.005)))&&(this.items=r,this.onScheduleUpdate(e,i))}}parseDateRanges(t,e,s){const i=[],r=Object.keys(t);for(let n=0;n!(t.error||t.cue.once&&t.hasPlayed)))).length){this.resolveOffsets(t,e);let i=0,o=0;if(t.forEach(((e,a)=>{const l=e.cue.pre,h=e.cue.post,d=t[a-1]||null,c=e.appendInPlace,u=h?r:e.startOffset,f=e.duration,g=e.timelineOccupancy===qn.Range?f:0,m=e.resumptionOffset,p=(null==d?void 0:d.startTime)===u,v=u+e.cumulativeDuration;let y=c?v+f:u+m;if(l||!h&&u<=0){const t=o;o+=g,e.timelineStart=v;const i=n;n+=f,s.push({event:e,start:v,end:y,playout:{start:i,end:n},integrated:{start:t,end:o}})}else{if(!(u<=r))return;{if(!p){const r=u-i;if(r>.033){const l=i,h=o;o+=r;const d=n;n+=r;const c={previousEvent:t[a-1]||null,nextEvent:e,start:l,end:l+r,playout:{start:d,end:n},integrated:{start:h,end:o}};s.push(c)}else r>0&&d&&(d.cumulativeDuration+=r,s[s.length-1].end=u)}h&&(y=v),e.timelineStart=v;const r=o;o+=g;const l=n;n+=f,s.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const E=e.resumeTime;i=h||E>r?r:E})),i{const h=o.cue.pre,d=o.cue.post,c=h?0:d?r:o.startTime;this.updateAssetDurations(o);if(a===c?o.cumulativeDuration=n:(n=0,a=c),!d&&o.snapOptions.in&&(o.resumeAnchor=de(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(o,e)||(o.appendInPlace=!1)}if(!o.appendInPlace&&l+1jn)return this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1;if(!e)return this.log(`"${t.identifier}" resumption ${s} can not be aligned with media (none selected)`),!1;return!Object.keys(e).some((i=>{const r=e[i].details,n=r.edge;if(s>=n)return this.log(`"${t.identifier}" resumption ${s} past ${i} playlist end ${n}`),!1;const a=de(null,r.fragments,s);if(!a)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${i} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===i?.175:0;return!(Math.abs(a.start-s){const a=e+s;t.startOffset=s,t.timelineStart=a,i||(i=null===t.duration),r||(r=!!t.error);const o=t.error?0:t.duration||0;s+=o})),t.duration=i&&!r?Math.max(s,t.duration):s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function sa(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class ia{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const s=t.assetListUrl;let i;try{i=Zn(s,this.hls.sessionId,t.baseUrl)}catch(e){const i=this.assignAssetListError(t,o.ASSET_LIST_LOAD_ERROR,e,s);return void this.hls.trigger(l.ERROR,i)}e&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+e);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:i.href},h=r.interstitialAssetListLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,s,i,r)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(Array.isArray(a))t.assetListResponse=n,this.hls.trigger(l.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:r});else{const e=this.assignAssetListError(t,o.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,s,r);this.hls.trigger(l.ERROR,e)}},onError:(e,s,i,r)=>{const n=this.assignAssetListError(t,o.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${s.url})`),s.url,r,i);this.hls.trigger(l.ERROR,n)},onTimeout:(e,s,i)=>{const r=this.assignAssetListError(t,o.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,e,i);this.hls.trigger(l.ERROR,r)}};return n.load(a,d,c),this.hls.trigger(l.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,s,i,r,n){return t.error=s,{type:a.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:i,error:s,networkDetails:n,stats:r}}}function ra(t,e,s){na(t,e,s),t.addEventListener(e,s)}function na(t,e,s){t.removeEventListener(e,s)}function aa(t){null==t||t.play().catch((()=>{}))}class oa{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return t[s][e]};this.buffered={get length(){return t.length},end(s){return e("end",s,t.length)},start(s){return e("start",s,t.length)}}}}const la={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},ha=t=>String.fromCharCode(la[t]||t),da=15,ca=100,ua={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},fa={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ga={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ma={25:2,26:4,29:6,30:8,31:10,27:13,28:15},pa=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class va{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;D.log(`${this.time} [${t}] ${s}`)}}}const ya=function(t){const e=[];for(let s=0;sca&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ca)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t=144&&this.backSpace();const e=ha(t);this.pos>=ca?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e"pacData = "+te(t)));let e=t.row-1;if(this.nrRollUpRows&&e"bkgData = "+te(t))),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",i=-1;for(let s=0;s0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}}class Aa{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new La(s),this.nonDisplayedMemory=new La(s),this.lastOutputScreen=new La(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(()=>"MODE="+t)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;ee+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}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){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const s=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s]}this.logger.log(2,"MIDROW: "+te(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Ra{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new va;this.channels=[null,new Aa(t,e,i),new Aa(t+1,s,i)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t"["+ya([e[t],e[t+1]])+"] -> ("+ya([s,i])+")"));const a=this.cmdHistory;if(s>=16&&s<=31){if(Ia(s,i,a)){ba(null,null,a),this.logger.log(3,(()=>"Repeated command ("+ya([s,i])+") is dropped"));continue}ba(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else ba(null,null,a);if(!r&&(n=this.parseChars(s,i),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+ya([s,i])+" orig: "+ya([e[t],e[t+1]])))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const s=20===t||21===t||23===t?1:2,i=this.channels[s];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=s,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+ya([t,e])+")")),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?ua[t]:ga[t]:1===i?fa[t]:ma[t];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=1==(1&s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,(()=>"Special char '"+ha(t)+"' in channel "+s)),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,(()=>"Char codes =  "+ya(i).join(","))),i}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let s;const i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=pa[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let t=0;t100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return L},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Da{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function _a(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class Pa{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i=0&&s<=100)return this.set(t,s),!0}return!1}}function Ca(t,e,s,i){const r=i?t.split(i):[t];for(const t in r){if("string"!=typeof r[t])continue;const i=r[t].split(s);if(2!==i.length)continue;e(i[0],i[1])}}const wa=new ka(0,0,""),xa="middle"===wa.align?"middle":"center";function Oa(t,e,s){const i=t;function r(){const e=_a(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new Pa;Ca(t,(function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",xa,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",xa,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",xa,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===wa.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",xa);let n=i.get("position","auto");"auto"===n&&50===wa.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function Ma(t){return t.replace(//gi,"\n")}class Fa{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Da,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=Ma(t);s0&&d.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(d)},h.forEach((t=>{if(p){if(Ua(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{Ua(t,"LOCAL:")?f=t.slice(6):Ua(t,"MPEGTS:")&&(g=parseInt(t.slice(7)))}));try{m=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(i(e)&&i(s)&&i(r)&&i(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*r,e+=36e5*n,e}(f)/1e3}catch(t){u=t}return}""===t&&(p=!1)}l.parse(t+"\n")})),l.flush()}const Ga="stpp.ttml.im1t",Ka=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ha=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Va={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ya(t,e,s,i){const r=at(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map((t=>C(t))),a=function(t,e,s=1,i=!1){return xr(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach((t=>s(function(t,e){const s=(new DOMParser).parseFromString(t,"text/xml"),i=s.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce(((t,e)=>(t[e]=i.getAttribute(`ttp:${e}`)||r[e],t)),{}),a="preserve"!==i.getAttribute("xml:space"),o=ja(Wa(i,"styling","style")),l=ja(Wa(i,"layout","region")),h=Wa(i,"body","[begin]");return[].map.call(h,(t=>{const s=qa(t,a);if(!s||!t.hasAttribute("begin"))return null;const i=Qa(t.getAttribute("begin"),n),r=Qa(t.getAttribute("dur"),n);let h=Qa(t.getAttribute("end"),n);if(null===i)throw za(t);if(null===h){if(null===r)throw za(t);h=i+r}const d=new ka(i-e,h-e,s);d.id=Ba(d.startTime,d.endTime,d.text);const c=function(t,e,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce(((s,n)=>{const a=Xa(e,i,n)||Xa(t,i,n)||Xa(r,i,n);return a&&(s[n]=a),s}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=Va[u];t&&(d.lineAlign=t),d.align=u}return E(d,c),d})).filter((t=>null!==t))}(t,a))))}catch(t){i(t)}}function Wa(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function ja(t){return t.reduce(((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t}),{})}function qa(t,e){return[].slice.call(t.childNodes).reduce(((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?qa(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function Xa(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function za(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Qa(t,e){if(!t)return null;let s=_a(t);return null===s&&(Ka.test(t)?s=function(t,e){const s=Ka.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):Ha.test(t)&&(s=function(t,e){const s=Ha.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}class Za{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function Ja(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function to(t,e){return!!t&&t.kind===Ja(e)&&en(e,t)}const eo=/\s/,so={newCue(t,e,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u=16?l--:l++;const i=Ma(h.trim()),f=Ba(e,s,i);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),r.forEach((e=>Kn(t,e)))),r}};const io=/(\d+)-(\d+)\/(\d+)/;class ro{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||no,this.controller=new self.AbortController,this.stats=new K}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(E({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=l&&i(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))}),e.timeout);(jr(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((s=>{var n;this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,t,this.response))}),h-(o-r.loading.start)),!s.ok){const{status:t,statusText:e}=s;throw new ao(e||"fetch, bad network response",t,s)}r.loading.first=o,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=io.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(i(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(s.headers)||r.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&i(e.highWaterMark)?this.loadProgressively(s,r,t,e.highWaterMark,l):a?s.arrayBuffer():"json"===t.responseType?s.json():s.text()})).then((s=>{var n,a;const l=this.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const h=s[o];h&&(r.loaded=r.total=h);const d={url:l.url,data:s,code:l.status},c=null==(n=this.callbacks)?void 0:n.onProgress;c&&!i(e.highWaterMark)&&c(r,t,s,l),null==(a=this.callbacks)||a.onSuccess(d,r,t,l)})).catch((e=>{var s;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const i=e&&e.code||0,n=e?e.message:null;null==(s=this.callbacks)||s.onError({code:i,text:n},t,e?e.details:null,r)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,s,i=0,r){const n=new Ai,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(e,s,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h=i&&r(e,s,n.flush().buffer,t)):r(e,s,l.buffer,t),o()})).catch((()=>Promise.reject()));return o()}}function no(t,e){return new self.Request(t.url,e)}class ao extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const oo=/^age:\s*[\d.]+\s*$/im;class lo{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new K,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,e.url)})).catch((t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r(s,e.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)})).catch((t=>{var r;null==(r=this.callbacks)||r.onError({code:s.status,text:t.message},e,s,i)})):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const r=e.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&i(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const r=null!=l?l:e.response;if(null!=r){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,t,r,e);const h={url:e.responseURL,data:r,code:i};return void(null==(a=this.callbacks)||a.onSuccess(h,s,t,e))}}const h=r.loadPolicy.errorRetry;var o;if(ye(h,s.retry,!1,{url:t.url,data:void 0,code:i}))this.retry(h);else D.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,s)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(ye(t,this.stats.retry,!0))this.retry(t);else{var e;D.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=pe(t,s.retry),s.retry++,D.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&oo.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const ho=S(S({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,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:lo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends L{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:s,partCurrent:r,hls:n}=this,{autoLevelEnabled:a,media:o}=n;if(!s||!o)return;const h=performance.now(),d=r?r.stats:s.stats,c=r?r.duration:s.duration,u=h-d.loading.start,f=n.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!a)return;const p=m>-1&&m!==g,v=!!t||p;if(!v&&(o.paused||!o.playbackRate||!o.readyState))return;const y=n.mainForwardBufferInfo;if(!v&&null===y)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(o.playbackRate);if(u<=Math.max(E,c/(2*T)*1e3))return;const S=y?y.len/T:0,L=d.loading.first?d.loading.first-d.loading.start:-1,A=d.loaded&&L>-1,R=this.getBwEstimate(),b=n.levels,I=b[g],k=Math.max(d.loaded,Math.round(c*(s.bitrate||I.averageBitrate)/8));let D=A?u-L:u;D<1&&A&&(D=Math.min(u,8*d.loaded/R));const _=A?1e3*d.loaded/D:0,P=E/1e3,C=_?(k-d.loaded)/_:8*k/R+P;if(C<=S)return;const w=_?8*_:R,x=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),O=this.hls.config.abrBandWidthUpFactor;let M,F=Number.POSITIVE_INFINITY;for(M=g-1;M>f;M--){const t=b[M].maxBitrate,e=!b[M].details||x;if(F=this.getTimeToLoadFrag(P,w,c*t,e),F=C)return;if(F>10*c)return;A?this.bwEstimator.sample(u-Math.min(E,L),d.loaded):this.bwEstimator.sampleTTFB(u);const N=b[M].maxBitrate;this.getBwEstimate()*O>N&&this.resetEstimator(N);const U=this.findBestLevel(N,f,M,0,S,1,1);U>-1&&(M=U),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;\n      Fragment duration: ${s.duration.toFixed(3)}\n      Time to underbuffer: ${S.toFixed(3)} s\n      Estimated load time for current fragment: ${C.toFixed(3)} s\n      Estimated load time for down switch fragment: ${F.toFixed(3)} s\n      TTFB estimate: ${0|L} ms\n      Current BW estimate: ${i(R)?0|R:"Unknown"} bps\n      New BW estimate: ${0|this.getBwEstimate()} bps\n      Switching to level ${M} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=M,this.clearTimer();const B=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===M&&M>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n      Fragment duration: ${s.duration.toFixed(3)} s\n      Time to underbuffer: ${t.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,M>f){let e=this.findBestLevel(this.hls.levels[f].bitrate,f,M,0,t,1,1);-1===e&&(e=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};p||C>2*F?B():this.timer=self.setInterval(B,1e3*F),n.trigger(l.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:d})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new v(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.FRAG_LOADING,this.onFragLoading,this),t.on(l.FRAG_LOADED,this.onFragLoaded,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.FRAG_LOADING,this.onFragLoading,this),t.off(l.FRAG_LOADED,this.onFragLoaded,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(l.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case o.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:r}=e.stats,n=r.end-r.first;i(n)&&(this.lastLevelLoadSec=n/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:s}){const i=s?s.stats:e.stats;if(e.type===f&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:i,frag:e,part:s,id:e.type};this.onFragBuffered(l.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==f||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,e,t,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,h,d);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate){if(!s.codecSet)return t;const r=s.audioGroups;let n=t[s.codecSet];n||(t[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,i),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,r&&r.forEach((t=>{if(!t)return;const s=e.groups[t];s&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{n.channels[t]=(n.channels[t]||0)+s.channels[t]})))})),t}),{})}(g,I,e,s)),n=function(t,e,s,r,n){const a=Object.keys(t),o=null==r?void 0:r.channels,l=null==r?void 0:r.audioCodec,h=null==n?void 0:n.videoCodec,d=o&&2===parseInt(o);let c=!1,u=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=Jt(e,n);for(let e=a.length;e--;){const s=t[a[e]];c||(c=s.channels[2]>0),f=Math.min(f,s.minHeight),g=Math.min(g,s.minFramerate),m=Math.min(m,s.minBitrate),T.filter((t=>s.videoRanges[t]>0)).length>0&&(u=!0)}f=i(f)?f:0,g=i(g)?g:0;const S=Math.max(1080,f),L=Math.max(30,g);m=i(m)?m:s,s=Math.max(m,s),u||(e=void 0);const A=a.length>1;return{codecSet:a.reduce(((e,i)=>{const r=t[i];if(i===e)return e;if(y=u?T.filter((t=>r.videoRanges[t]>0)):[],A){if(r.minBitrate>s)return ee(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return ee(i,"no renditions with default or auto-select sound found"),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return ee(i,`audio codec preference "${l}" not found`),e;if(o&&!d){if(!r.channels[o])return ee(i,`no renditions with ${o} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!l||d)&&c&&0===r.channels[2])return ee(i,"no renditions with stereo sound found"),e;if(r.minHeight>S)return ee(i,`min resolution of ${r.minHeight} > maximum of ${S}`),e;if(r.minFramerate>L)return ee(i,`min framerate of ${r.minFramerate} > maximum of ${L}`),e;if(!y.some((t=>r.videoRanges[t]>0)))return ee(i,`no variants with VIDEO-RANGE of ${te(y)} found`),e;if(h&&i.indexOf(h.substring(0,4))%5!=0)return ee(i,`video codec preference "${h}" not found`),e;if(r.maxScore=Ct(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,v=r.maxScore,i)}),void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(r,L,t,R,b),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:h,minIndex:d,preferHDR:c}=n;k=d,S=a,L=c?o[o.length-1]:o[0],A=l,t=Math.max(t,h),this.log(`picked start tier ${te(n)}`)}else S=null==y?void 0:y.codecSet,L=null==y?void 0:y.videoRange;const D=f?f.duration:u?u.duration:0,_=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let l=s;l>=e;l--){var C;const e=g[l],u=l>c;if(!e)continue;if(v.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&(Kt(e,I,L,A,t,R)||yt(e.videoCodec))?(e.supportedPromise=Ht(e,I,s),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${te(t)}`):t.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${te(t)}`),i>-1&&s.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}))):e.supportedResult=Bt}if((S&&e.codecSet!==S||L&&e.videoRange!==L||u&&A>e.frameRate||!u&&A>0&&A=2*D&&0===n?e.averageBitrate:e.maxBitrate,x=this.getTimeToLoadFrag(_,b,w*y,void 0===m);if(b>=w&&(l===d||0===e.loadError&&0===e.fragmentError)&&(x<=_||!i(x)||E&&!this.bitrateTestDelay||x${l} adjustedbw(${Math.round(b)})-bitrate=${Math.round(b-w)} ttfb:${_.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${T} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=l),l}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),e)}},bufferController:class extends L{constructor(t,e){var s;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:s}=this;t&&this.log("Media source opened"),e&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(l.MEDIA_ATTACHED,{media:e,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(s=_(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===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(){const{hls:t}=this;t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.BUFFER_RESET,this.onBufferReset,this),t.on(l.BUFFER_APPENDING,this.onBufferAppending,this),t.on(l.BUFFER_CODECS,this.onBufferCodecs,this),t.on(l.BUFFER_EOS,this.onBufferEos,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.FRAG_PARSED,this.onFragParsed,this),t.on(l.FRAG_CHANGED,this.onFragChanged,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.BUFFER_RESET,this.onBufferReset,this),t.off(l.BUFFER_APPENDING,this.onBufferAppending,this),t.off(l.BUFFER_CODECS,this.onBufferCodecs,this),t.off(l.BUFFER_EOS,this.onBufferEos,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.FRAG_PARSED,this.onFragParsed,this),t.off(l.FRAG_CHANGED,this.onFragChanged,this),t.off(l.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const s={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===e?E(s,i.tracks):this.sourceBuffers.forEach((t=>{const[e]=t;e&&(s[e]=E({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null})),{media:t,mediaSource:e,tracks:s}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var s;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const s=this.media=e.media,i=_(this.appendSource);if(this.transferData=this.overrides=void 0,s&&i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(r),t)this._objectUrl=s.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{s.removeAttribute("src");const e=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||e&&r instanceof e,on(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,t),s.load()}catch(e){s.src=t}else s.src=t}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,s;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(s=t.constructor)?void 0:s.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const s=this.tracks,i=e.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(i&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${te(s,((t,e)=>"initSegment"===t?void 0:e))};\ntransfer tracks: ${te(i,((t,e)=>"initSegment"===t?void 0:e))}}`),!P(i,s)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(l.MEDIA_DETACHING,{}),this.onMediaAttaching(l.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach((t=>{const e=t,s=i[e];if(s){const t=s.buffer;if(t){const i=this.fragmentTracker,r=s.id;if(i.hasFragments(r)||i.hasParts(r)){const s=qe.getBuffered(t);i.detectEvictedFragments(e,s,r,null,!0)}const n=ln(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,s)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const s=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach((([t])=>{t&&this.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let s=e.length;s--;)t&&e[s].abort(),r.removeSourceBuffer(e[s]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&on(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(l.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach((([t])=>{t&&this.resetBuffer(t)})),this.initTracks()}resetBuffer(t){var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),s)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[ln(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new sn(this.tracks)}onBufferCodecs(t,e){const s=this.tracks,i=Object.keys(e);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const r="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),n=!r&&this.sourceBufferCount&&this.media&&i.some((t=>!s[t]));r||n?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${i}" SourceBuffers`):(i.forEach((t=>{var i,r,n;const a=e[t],{id:o,codec:l,levelCodec:h,container:d,metadata:c,supplemental:u}=a;let f=s[t];const g=null==(i=this.transferData)||null==(r=i.tracks)?void 0:r[t],m=null!=g&&g.buffer?g:f,p=(null==m?void 0:m.pendingCodec)||(null==m?void 0:m.codec),v=null==m?void 0:m.levelCodec;f||(f=s[t]={buffer:void 0,listeners:[],codec:l,supplemental:u,container:d,levelCodec:h,metadata:c,id:o});const y=Mt(p,v),E=null==y?void 0:y.replace(rn,"$1");let T=Mt(l,h);const S=null==(n=T)?void 0:n.replace(rn,"$1");T&&y&&E!==S&&("audio"===t.slice(0,5)&&(T=Ot(T,this.appendSource)),this.log(`switching codec ${p} to ${T}`),T!==(f.pendingCodec||f.codec)&&(f.pendingCodec=T),f.container=d,this.appendChangeType(t,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((t,e)=>{const s=this.tracks[e];return t[e]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t}),{})}appendChangeType(t,e,s){const i=`${e};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),r.codec=s,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const s=t.start,i=s+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,f))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>i||null!=e&&e.buffer&&qe.isBuffered(e.buffer,i)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,f))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:r,frag:t},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:s}=this,{data:i,type:r,parent:n,frag:h,part:d,chunkMeta:c}=e,u=c.buffering[r],f=h.sn,g=self.performance.now();u.start=g;const m=h.stats.buffering,p=d?d.stats.buffering:null;0===m.start&&(m.start=g),p&&0===p.start&&(p.start=g);const v=s.audio;let y=!1;"audio"===r&&"audio/mpeg"===(null==v?void 0:v.container)&&(y=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const E=this.tracks.video,T=null==E?void 0:E.buffer;if(T&&"initSegment"!==f){const t=d||h,e=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend){if("video"===r){const s=t.end;if(e){const t=e.frag.start;(s>t||s{if(u.executeStart=self.performance.now(),y){const t=this.tracks[r];if(t){const e=t.buffer;if(e){const t=S-e.timestampOffset;Math.abs(t)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${S} (delta: ${t}) sn: ${f})`),e.timestampOffset=S)}}}this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();u.executeEnd=u.end=t,0===m.first&&(m.first=t),p&&0===p.first&&(p.first=t);const e={};this.sourceBuffers.forEach((([t,s])=>{t&&(e[t]=qe.getBuffered(s))})),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(l.BUFFER_APPENDED,{type:r,frag:h,part:d,chunkMeta:c,parent:h.type,timeRanges:e})},onError:t=>{var e;const s={type:a.MEDIA_ERROR,parent:h.type,details:o.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:h,part:d,chunkMeta:c,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)s.details=o.BUFFER_FULL_ERROR;else if(t.code!==DOMException.INVALID_STATE_ERR||!this.mediaSourceOpenOrEnded||null!=(e=this.media)&&e.error)if(t.name===nn)0===this.sourceBufferCount?s.errorAction=Ie(!0):++this.appendErrors[r];else{const t=++this.appendErrors[r];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer`),t>=this.hls.config.appendErrorMaxRetry&&(s.fatal=!0)}else s.errorAction=Ie(!0);this.hls.trigger(l.ERROR,s)}};this.append(L,r,this.isPending(this.tracks[r]))}getFlushOp(t,e,s){return this.log(`queuing "${t}" remove ${e}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(l.BUFFER_FLUSHED,{type:t})},onError:i=>{this.warn(`Failed to remove ${e}-${s} from "${t}" SourceBuffer`,i)}}}onBufferFlushing(t,e){const{type:s,startOffset:i,endOffset:r}=e;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach((([t])=>{t&&this.append(this.getFlushOp(t,i,r),t)}))}onFragParsed(t,e){const{frag:s,part:i}=e,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[Y]?r.push("audiovideo"):(n[H]&&r.push("audio"),n[V]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.hls.trigger(l.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.type})}),r)}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var e,s;return t&&(!(null!=(e=this.tracks[t])&&e.ended)||(null==(s=this.tracks[t])?void 0:s.ending))}))}onBufferEos(t,e){var s;this.sourceBuffers.forEach((([t])=>{if(t){const s=this.tracks[t];e.type&&e.type!==t||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${t} buffer reached EOS`)))}}));const i=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)}))&&(i?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(l.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(l.BUFFERED_TO_END,void 0)))}tracksEnded(){this.sourceBuffers.forEach((([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}}))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){const t=this.getDurationAndRange();t&&this.blockUntilOpen((()=>this.updateMediaSource(t)))}onError(t,e){if(e.details===o.BUFFER_APPEND_ERROR&&e.frag){var s;const t=null==(s=e.errorAction)?void 0:s.nextAutoLevel;i(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:s}=this;if(!s||null===e)return;if(!this.sourceBufferCount)return;const r=t.config,n=s.currentTime,a=e.levelTargetDuration,o=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(i(o)&&o>=0){const t=Math.max(o,a),e=Math.floor(n/a)*a-t;this.flushBackBuffer(n,a,e)}if(i(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const t=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),e=Math.max(t,a),s=Math.floor(n/a)*a+e;this.flushFrontBuffer(n,a,s)}}flushBackBuffer(t,e,s){this.sourceBuffers.forEach((([t,e])=>{if(e){const r=qe.getBuffered(e);if(r.length>0&&s>r.start(0)){var i;this.hls.trigger(l.BACK_BUFFER_REACHED,{bufferEnd:s});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger(l.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(l.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:t})}}}))}flushFrontBuffer(t,e,s){this.sourceBuffers.forEach((([e,i])=>{if(i){const r=qe.getBuffered(i),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(s>a||t>=a&&t<=o)return;this.hls.trigger(l.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}}))}getDurationAndRange(){var t;const{details:e,mediaSource:s}=this;if(!e||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const r=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&e.live&&s.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,r)}}return{duration:1/0}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return i(n)?{duration:n}:null;const a=this.media.duration;return r>(i(s.duration)?s.duration:0)&&r>a||!i(a)?{duration:r}:null}updateMediaSource({duration:t,start:e,end:s}){const r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==t&&(i(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),r.duration=t),void 0!==e&&void 0!==s&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${e}-${s}.`),r.setLiveSeekableRange(e,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${te(s)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach((([e,s])=>{if(e){const i=this.tracks[e];t[e]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}})),this.hls.trigger(l.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([t])=>{this.executeNext(t)}))}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in t){const n=r,h=t[n];if(this.isPending(h)){const t=this.getTrackCodec(h,n),r=`${h.container};codecs=${t}`;h.codec=t,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${te(h)}`);try{const t=s.addSourceBuffer(r),i=ln(n),a=[n,t];e[i]=a,h.buffer=t}catch(t){var i;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:r,parent:h.id})}this.trackSourceBuffer(n,h)}}this.bufferCreated()}getTrackCodec(t,e){const s=t.supplemental;let i=t.codec;s&&("video"===e||"audiovideo"===e)&&kt(s,"video")&&(i=function(t,e){const s=[];if(t){const e=t.split(",");for(let t=0;t{const s=e.removedRanges;null!=s&&s.length&&this.hls.trigger(l.BUFFER_FLUSHED,{type:t})}))}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const s=this.currentOp(t);s&&(s.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var s;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,e),this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const r=this.currentOp(t);r&&r.onError(i)}removeExecutor(t,e,s){const{media:r,mediaSource:n}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!r||!n||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const l=i(r.duration)?r.duration:1/0,h=i(n.duration)?n.duration:1/0,d=Math.max(0,e),c=Math.min(s,l,h);c>d&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${d},${c}] from the ${t} SourceBuffer`),o.remove(d,c)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.tracks[e],i=null==s?void 0:s.buffer;if(!i)throw new an(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(t)}blockUntilOpen(t){this.isUpdating()||this.isQueued()?this.blockBuffers(t):t()}isUpdating(){return this.sourceBuffers.some((([t,e])=>t&&e.updating))}isQueued(){return this.sourceBuffers.some((([t])=>t&&!!this.currentOp(t)))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:s}=this,i=e.map((t=>this.appendBlocker(t)));e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then((i=>{s===this.operationQueue&&(t(),this.stepOperationQueue(e))}))}stepOperationQueue(t){t.forEach((t=>{var e;const s=null==(e=this.tracks[t])?void 0:e.buffer;s&&!s.updating&&this.shiftAndExecuteNext(t)}))}append(t,e,s){this.operationQueue&&this.operationQueue.append(t,e,s)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((t,e)=>t+(this.isPending(this.tracks[e])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((t,[e])=>t+(e?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([t])=>t)).filter((t=>!!t))}addBufferListener(t,e,s){const i=this.tracks[t];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,t);i.listeners.push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const s=e.buffer;s&&(e.listeners.forEach((t=>{s.removeEventListener(t.event,t.listener)})),e.listeners.length=0)}},capLevelController:hn,errorController:class extends L{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(l.ERROR,this.onError,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(l.ERROR,this.onError,this),t.off(l.ERROR,this.onErrorOut,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===f?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var s;if(e.fatal)return;const i=this.hls,r=e.context;switch(e.details){case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case o.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction=Ie());case o.FRAG_GAP:case o.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Te);case o.LEVEL_EMPTY_ERROR:case o.LEVEL_PARSING_ERROR:{var n,l;const t=e.parent===f?e.level:i.loadLevel;e.details===o.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(l=n.levelDetails)&&l.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case o.AUDIO_TRACK_LOAD_ERROR:case o.AUDIO_TRACK_LOAD_TIMEOUT:case o.SUBTITLE_LOAD_ERROR:case o.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=i.loadLevelObj;if(t&&(r.type===c&&t.hasAudioGroup(r.groupId)||r.type===u&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=Te,void(e.errorAction.flags=Re)}return;case o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=i.loadLevelObj,s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?e.errorAction={action:Te,flags:be,hdcpLevel:s}:this.keySystemError(e)}return;case o.BUFFER_ADD_CODEC_ERROR:case o.REMUX_ALLOC_ERROR:case o.BUFFER_APPEND_ERROR:var h;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(h=e.level)?h:i.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:return void(e.errorAction=Ie())}e.type===a.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const s=me(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(ye(s,i,ge(t),t.response))return{action:Le,flags:Ae,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=me(t.details.startsWith("key")?n:r,t),l=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(i){t.details!==o.FRAG_GAP&&i.fragmentError++;if(ye(a,l,ge(t),t.response))return{action:Le,flags:Ae,retryConfig:a,retryCount:l}}const h=this.getLevelSwitchAction(t,s);return a&&(h.retryConfig=a,h.retryCount=l),h}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,e===o.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:d,loadLevel:p,minAutoLevel:v,maxAutoLevel:y}=s;s.autoLevelEnabled||(s.loadLevel=-1);const E=null==(r=t.frag)?void 0:r.type,T=(E===g&&e===o.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===o.BUFFER_ADD_CODEC_ERROR||e===o.BUFFER_APPEND_ERROR))&&d.some((({audioCodec:t})=>i.audioCodec!==t)),S="video"===t.sourceBufferName&&(e===o.BUFFER_ADD_CODEC_ERROR||e===o.BUFFER_APPEND_ERROR)&&d.some((({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e)),{type:L,groupId:A}=null!=(n=t.context)?n:{};for(let s=d.length;s--;){const r=(s+p)%d.length;if(r!==p&&r>=v&&r<=y&&0===d[r].loadError){var a,l;const s=d[r];if(e===o.FRAG_GAP&&E===f&&t.frag){const e=d[r].details;if(e){const s=de(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(L===c&&s.hasAudioGroup(A)||L===u&&s.hasSubtitleGroup(A))continue;if(E===g&&null!=(a=i.audioGroups)&&a.some((t=>s.hasAudioGroup(t)))||E===m&&null!=(l=i.subtitleGroups)&&l.some((t=>s.hasSubtitleGroup(t)))||T&&i.audioCodec===s.audioCodec||!T&&i.audioCodec!==s.audioCodec||S&&i.codecSet===s.codecSet)continue}h=r;break}}if(h>-1&&s.loadLevel!==h)return t.levelRetry=!0,this.playlistError=0,{action:Te,flags:Ae,nextAutoLevel:h}}return{action:Te,flags:Re}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Ee:break;case Te:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===o.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:n}=s;switch(i){case Ae:this.switchLevel(t,n);break;case be:r&&(e.maxHdcpLevel=Vt[Vt.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(t,n)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===o.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Ut(t.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${t.sourceBufferName}Codec`]===e&&this.hls.removeLevel(i)}}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(l.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(l.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(l.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(l.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},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:bs,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,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:so,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:class extends Si{constructor(t,e,s){super(t,e,s,"subtitle-stream-controller",m),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(l.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(l.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(l.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(l.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(l.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(l.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=di,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:i}=e;if(j(s)&&(this.fragPrevious=s),this.state=di,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let t=0;t=r[t].start&&a<=r[t].end){n=r[t];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let s=0;snew Qt(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new Qt(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,m),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==hi&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let h=0;if(n.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var d;if(o.details)h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===h&&e&&(h=e.start,Zs(n,h));else n.hasProgramDateTime&&t.hasProgramDateTime?(oi(n,t),h=n.fragmentStart):e&&(h=e.start,Zs(n,h))}if(o.details=n,this.levelLastLoaded=o,a===i&&(this.hls.trigger(l.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===di)){de(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,i=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&as(i.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,os(i.method)).catch((t=>{throw r.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((s=>{const i=performance.now();r.trigger(l.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:i}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=di}))}}doTick(){if(this.media){if(this.state===di){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;if(this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=qe.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:a,len:o}=n,l=s.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const h=l.fragments,d=h.length,c=l.edge;let u=null;const f=this.fragPrevious;if(ac-t?0:t;u=de(f,h,Math.max(h[0].start,a),e),!u&&f&&f.startthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Yn(this.media.textTracks);for(let s=0;s-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(l.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVEL_LOADING,this.onLevelLoading,this),t.off(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(l.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(l.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const s=this.media;if(!s)return;const i=!!e.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;Yn(s.textTracks).forEach((t=>{Hn(t)}))}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const s=re(e,t);if(s>-1)r=t[s];else{const t=re(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(l.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i),t}if(s)return null;{const s=re(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${r}`),this.hls.trigger(l.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Yn(t.textTracks),s=this.currentTrack;let i;if(s&&(i=e.filter((t=>en(s,t)))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==i&&(t.mode="disabled")})),i){const t=this.subtitleDisplay?"showing":"hidden";i.mode!==t&&(i.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!i(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(l.SUBTITLE_TRACK_SWITCH,{id:t});const n=!!r.details&&!r.details.live;if(t===this.trackId&&r===s&&n)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:h,type:d,url:c}=r;this.hls.trigger(l.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:h,type:d,url:c});const u=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(u)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(l.FRAG_LOADING,this.onFragLoading,this),t.on(l.FRAG_LOADED,this.onFragLoaded,this),t.on(l.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(l.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(l.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(l.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(l.FRAG_LOADING,this.onFragLoading,this),t.off(l.FRAG_LOADED,this.onFragLoaded,this),t.off(l.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(l.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(l.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(l.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Za(this,"textTrack1"),e=new Za(this,"textTrack2"),s=new Za(this,"textTrack3"),i=new Za(this,"textTrack4");this.cea608Parser1=new Ra(1,t,e),this.cea608Parser2=new Ra(3,s,i)}addCues(t,e,s,i,r){let n=!1;for(let t=r.length;t--;){const i=r[t],l=(a=i[0],o=i[1],h=e,d=s,Math.min(o,d)-Math.max(a,h));if(l>=0&&(i[0]=Math.min(i[0],e),i[1]=Math.max(i[1],s),n=!0,l/(s-e)>.5))return}var a,o,h,d;if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,s,i)}else{const r=this.Cues.newCue(null,e,s,i);this.hls.trigger(l.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:n}=this;s===f&&(this.initPTS[e.cc]={baseTime:i,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach((t=>{this.onFragLoaded(l.FRAG_LOADED,t)})))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let i=0;i{Hn(i[t]),delete i[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;tt.textCodec===Ga));if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Jr(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?Yn(t.textTracks):null;if(this.tracks.forEach(((t,s)=>{let i;if(e){let s=null;for(let i=0;inull!==t)).map((t=>t.label));t.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map((t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t})));this.hls.trigger(l.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s=`textTrack${e[1]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.media=t)}))}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===f){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:i}=e;if(s.type===m)if(i.byteLength){const t=s.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===Ga?this._parseIMSC1(s,i):this._parseVTTs(e)}}else this.hls.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;Ya(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),s.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{s.logger.log(`Failed to parse IMSC1: ${e}`),s.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:s,payload:i}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(t);const o=this.hls;$a(null!=(e=s.initSegment)&&e.data?pt(s.initSegment.data,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(s,i),o.logger.log(`Failed to parse VTT cue: ${e}`),r&&a>s.cc||o.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})}))}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||Ya(e,this.initPTS[t.cc],(()=>{s.textCodec=Ga,this._parseIMSC1(t,e)}),(()=>{s.textCodec="wvtt"}))}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach((t=>Kn(s,t)))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger(l.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===m&&this.onFragLoaded(l.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=e;if(s.type!==f||"NONE"!==this.closedCaptionsForLevel(s))for(let t=0;tVn(t[i],e,s)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==i){const{textTracks:t}=this;Object.keys(t).forEach((s=>Vn(t[s],e,i)))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r=e){const i=s.start,r=s.end;let n=t.fragments;if(!s.relurl){const{fragmentHint:e}=t;e&&(n=n.concat(e))}return he(n,(t=>t.cce||t.start>=r?-1:0))}return null}(e,s,t)||e&&fe(e.fragments,s)||t}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=hi);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s,this.state=di):this.state=gi,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case di:this.doTickIdle();break;case gi:{const{levels:t,trackId:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=Ei}break}case fi:{var t;const e=performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=di}break}case Ei:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=ui;const t={frag:e,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&(this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${n.cc}`),this.nextLoadPosition=this.findSyncFrag(n).start,this.clearWaitingFragment())}else this.state=di}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.state!==hi&&(this.state=di))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:s,media:i,trackId:r}=this,n=e.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[r])return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=gi,void(this.startFragRequested=!1);const h=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,H,g));const d=this.getFwdBufferInfo(h,g);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return e.trigger(l.BUFFER_EOS,{type:"audio"}),void(this.state=vi);const c=d.len,u=e.maxBufferLength,m=o.fragments,p=m[0].start,v=this.getLoadPosition(),y=this.flushing?v:d.end;if(this.switchingTrack&&i){const t=v;o.PTSKnown&&tp||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=p+.05)}if(c>=u&&!this.switchingTrack&&yT.end){const t=this.fragmentTracker.getFragAtPos(y,f);t&&t.end>T.end&&(T=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,a,y)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map((t=>new Qt(t)))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==hi&&(this.setInterval(100),this.state=di,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(l.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,e){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=e;if(!i)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const h=this.mainDetails;if(!h||r.endCC>h.endCC||h.expired)return this.cachedTrackLoadedData=e,void(this.state!==hi&&(this.state=gi));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=i[n];let c=0;if(r.live||null!=(s=d.details)&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(d.details)c=this.alignPlaylists(r,d.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(ai(r,h),r.alignedSliding||oi(r,h),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(h,c),this.hls.trigger(l.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==gi||this.waitForCdnTuneIn(r)||(this.state=di),this.tick()}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Qr(this.hls,g,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new We(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n);c.push(r,f,d,"",s,i,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Ai,complete:!1};t.push(new Uint8Array(r)),this.state!==hi&&(this.state=Ei)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===f&&j(e.frag)&&(this.mainFragLoading=e,this.state===di&&this.tick())}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===g)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(j(s)){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(l.AUDIO_TRACK_SWITCHED,S({},t)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}else this.audioOnly||s.type!==f||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var s;if(e.fatal)this.state=yi;else switch(e.details){case o.FRAG_GAP:case o.FRAG_PARSING_ERROR:case o.FRAG_DECRYPT_ERROR:case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(g,e);break;case o.AUDIO_TRACK_LOAD_ERROR:case o.AUDIO_TRACK_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==gi||(null==(s=e.context)?void 0:s.type)!==c||(this.state=di);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case o.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==V&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==V){this.flushing=!1,this.bufferFlushed=!0,this.state===vi&&(this.state=di);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,g),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:h,level:d}=a,{details:c}=d,{audio:u,text:f,id3:g,initSegment:m}=r;if(!this.fragContextChanged(o)&&c){if(this.state=mi,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){const t=o.initSegment||o;this._bufferInitSegment(d,m.tracks,t,n),i.trigger(l.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:m.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=u;h&&(h.elementaryStreams[H]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(H,t,e,s,i),this.bufferFragmentData(u,o,h,n)}if(null!=g&&null!=(e=g.samples)&&e.length){const t=E({id:s,frag:o,details:c},g);i.trigger(l.FRAG_PARSING_METADATA,t)}if(f){const t=E({id:s,frag:o,details:c},f);i.trigger(l.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,s,i){if(this.state!==mi)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=g;const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(l.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(l.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||i===ke||i===_e)if(j(t))if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Ei;const s=this.mainDetails;s&&s.fragmentStart!==e.details.fragmentStart&&oi(e.details,s)}else super.loadFragment(t,e,s);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;ne({name:e,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},t,ae)||(le(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(l.AUDIO_TRACK_SWITCHED,S({},t))}},audioTrackController:class extends Zr{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(l.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVEL_LOADING,this.onLevelLoading,this),t.off(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(l.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(l.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const s=re(e,t,ae);if(s>-1)r=t[s];else{const t=re(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const h={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(l.AUDIO_TRACKS_UPDATED,h);const d=this.trackId;if(-1!==i&&-1===d)this.setAudioTrack(i);else if(t.length&&-1===d){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==c||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&ne(t,i,ae))return i;const r=re(t,this.tracksInGroup,ae);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce(((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t}),{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=oe(e,i,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return re(t,n,r)>-1}));return d>-1?d:oe(e,i,(e=>{const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return re(t,n,r)>-1}))}(t,e.levels,s,i,ae);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=re(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t],r=i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger(l.AUDIO_TRACK_SWITCHING,S({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:dn.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:e,part:s}=t,i=this.hls.levels[e.level],r=this.getObjectType(e),n={d:1e3*(s||e).duration,ot:r};r!==dn.VIDEO&&r!==dn.AUDIO&&r!=dn.MUXED||(n.br=i.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=s?this.getNextPart(s):this.getNextFrag(e);null!=a&&a.url&&a.url!==e.url&&(n.nor=a.url),this.apply(t,n)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||t.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHED,this.onMediaDetached,this),t.on(l.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHED,this.onMediaDetached,this),t.off(l.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var s,i;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer}createData(){var t;return{v:1,sf:cn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){E(e,this.createData());const s=e.ot===dn.INIT||e.ot===dn.VIDEO||e.ot===dn.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:i}=this;i&&(e=Object.keys(e).reduce(((t,s)=>(i.includes(s)&&(t[s]=e[s]),t)),{}));const r={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),On(t.headers,e,r)):t.url=Fn(t.url,e,r)}getNextFrag(t){var e;const s=null==(e=this.hls.levels[t.level])?void 0:e.details;if(s){const e=t.sn-s.startSN;return s.fragments[e+1]}}getNextPart(t){var e,s;const{index:i,fragment:r}=t,n=null==(e=this.hls.levels[r.level])||null==(s=e.details)?void 0:s.partList;if(n){const{sn:t}=r;for(let e=n.length-1;e>=0;e--){const s=n[e];if(s.index===i&&s.fragment.sn===t)return n[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?dn.TIMED_TEXT:"initSegment"===t.sn?dn.INIT:"audio"===e?dn.AUDIO:"main"===e?this.hls.audioTracks.length?dn.VIDEO:dn.MUXED:void 0}getTopBandwidth(t){let e,s=0;const i=this.hls;if(t===dn.AUDIO)e=i.audioTracks;else{const t=i.maxAutoLevel,s=t>-1?t+1:i.levels.length;e=i.levels.slice(0,s)}for(const t of e)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const e=this.media,s=t===dn.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!e)return NaN;return 1e3*qe.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}},contentSteeringController:class extends L{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Te&&s.flags===Re){const t=this.levels;let i=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),s.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${te(i)} penalized: ${te(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this._pathwayPriority=t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach((t=>{i-s[t]>3e5&&delete s[t]}));for(let i=0;i0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,si(e),this.hls.trigger(l.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===r)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new ss(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Un(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Qt({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":h}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:i.toString()};this.hls.trigger(l.STEERING_MANIFEST_LOADED,d),h&&this.updatePathwayPriority(h)},onError:(t,e,s,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,r);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,h)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}},interstitialsController:class extends L{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const s=e<=-.01;this.timelinePos=t,this.bufferedPos=t;const i=this.playingItem;if(!i)return void this.checkBuffer();if(s){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule()}if(this.checkBuffer(),s&&t=i.end){var r;const t=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(i)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!s){const e=this.findItemIndex(i);if(t>e){const s=this.schedule.findJumpRestrictedIndex(e+1,t);if(s>e)return void this.setSchedulePosition(s)}}return void this.setSchedulePosition(t)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(i)){const e=i.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;(s&&t=a+o)&&this.setScheduleToAssetAtTime(t,n)},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const s=this.playingAsset;if(!s)return;t>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(t,s)},this.onScheduleUpdate=(t,e)=>{const s=this.schedule,i=this.playingItem,r=s.events||[],n=s.items||[],a=s.durations,o=t.map((t=>t.identifier)),h=!(!r.length&&!o.length);if(h&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map((t=>sa(t)))}`),o.length&&this.log(`Removed events ${o}`),this.playerQueue.forEach((t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,s=t.timelineOffset-e;if(s)try{t.timelineOffset=e}catch(i){Math.abs(s)>jn&&this.warn(`${i} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}})),i){const t=this.updateItem(i,this.timelinePos);this.itemsMatch(i,t)&&(this.playingItem=t,this.waitingItem=this.endedItem=null)}else this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const d=this.bufferingItem;if(d){const t=this.updateItem(d,this.bufferedPos);this.itemsMatch(d,t)?this.bufferingItem=t:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))}if(t.forEach((t=>{t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,null)}))})),h||e){if(this.hls.trigger(l.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(i)&&o.includes(i.event.identifier))return this.warn(`Interstitial "${i.event.identifier}" removed while playing`),void this.primaryFallback(i.event);this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new ia(t),this.schedule=new ea(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(l.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(l.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(l.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(l.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(l.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(l.BUFFER_APPENDED,this.onBufferAppended,this),t.on(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(l.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(l.MEDIA_ENDED,this.onMediaEnded,this),t.on(l.ERROR,this.onError,this),t.on(l.DESTROYING,this.onDestroying,this)}unregisterListeners(){const t=this.hls;t&&(t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(l.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(l.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(l.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(l.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(l.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(l.BUFFER_CODECS,this.onBufferCodecs,this),t.off(l.BUFFER_APPENDED,this.onBufferAppended,this),t.off(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(l.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(l.MEDIA_ENDED,this.onMediaEnded,this),t.off(l.ERROR,this.onError,this),t.off(l.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){na(t,"play",this.onPlay),na(t,"pause",this.onPause),na(t,"seeking",this.onSeeking),na(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const s=this.media=e.media;ra(s,"seeking",this.onSeeking),ra(s,"timeupdate",this.onTimeupdate),ra(s,"play",this.onPlay),ra(s,"pause",this.onPause)}onMediaAttached(t,e){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!i){this.clearScheduleState();const t=this.findItemIndex(s);this.setSchedulePosition(t)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls)return null;const t=this,e=()=>t.bufferingItem||t.waitingItem,s=e=>e?t.getAssetPlayer(e.identifier):e,i=(e,i,r,a,o)=>{if(e){let l=e[i].start;const h=e.event;if(h){if("playout"===i||h.timelineOccupancy!==qn.Point){const t=s(r);(null==t?void 0:t.interstitial)===h&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?n():t[a])-e.start}return l}return 0},r=(e,s)=>{if(0!==e&&"primary"!==s&&t.schedule.length){var i;const r=t.schedule.findItemIndexAtTime(e),n=null==(i=t.schedule.items)?void 0:i[r];if(n){return e+(n[s].start-n.start)}}return e},n=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?a("primary"):Math.max(e,0)},a=e=>{var s;return null!=(s=t.primaryDetails)&&s.live?t.primaryDetails.edge:t.schedule.durations[e]},o=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,r),d=null==(a=t.schedule.items)?void 0:a[h],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,d);if(l&&(f||g)){const n=s(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const s="primary"===r?a.currentTime:i(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-s,h=(f?s:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let s=e;if("primary"!==r){const t=e-d[r].start;s=d.start+t}const i=!t.isInterstitial(d);if(t.isInterstitial(l)&&!l.event.appendInPlace||!i&&!d.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(h>n){const e=t.schedule.findJumpRestrictedIndex(n+1,h);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(i)t.timelinePos=s,t.checkBuffer();else{var m;const t=null==d||null==(m=d.event)?void 0:m.assetList;if(t){const s=e-(d[r]||d).start;for(let e=t.length;e--;){const i=t[e];if(i.duration&&s>=i.startOffset&&s{const s=t.effectivePlayingItem;if(t.isInterstitial(s))return s;const i=e();return t.isInterstitial(i)?i:null},h={get currentTime(){const e=l(),s=t.effectivePlayingItem;return s&&s===e?i(s,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(e){const s=l(),i=t.effectivePlayingItem;i&&i===s&&o(e+i.playout.start,"playout")},get duration(){const t=l();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const s=null==(e=l())?void 0:e.event.assetList;return s?s.map((e=>t.getAssetPlayer(e.identifier))):[]},get playingIndex(){var e;const s=null==(e=l())?void 0:e.event;return s&&t.effectivePlayingAsset?s.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return l()}};this.manager={get events(){var e,s;return(null==(e=t.schedule)||null==(s=e.events)?void 0:s.slice(0))||[]},get schedule(){var e,s;return(null==(e=t.schedule)||null==(s=e.items)?void 0:s.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const s=e();return t.findItemIndex(s)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return n()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){o(t,"primary")},get duration(){return a("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){o(t,"integrated")},get duration(){return a("integrated")},get seekableStart(){var e;return r((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,s=null==e?void 0:e.event;if(s&&!s.restrictions.skip){const i=t.findItemIndex(e);if(s.appendInPlace){const t=e.playout.start+e.event.duration;o(t+.001,"playout")}else t.advanceAfterAssetEnded(s,i,1/0)}}}}return this.manager}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,s=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&s)&&this.findItemIndex(e)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e,s;if(null===this.mediaSelection)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let n=this.media;!n&&null!=(t=this.bufferingItem)&&null!=(e=t.event)&&e.appendInPlace&&(n=this.primaryMedia);const a=null==(s=n)?void 0:s.currentTime;return void 0!==a&&i(a)?a:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,e)}transferMediaFromPlayer(t,e){const s=t.interstitial.appendInPlace,i=t.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&i)return void(this.detachedData={media:i});const s=t.transferMedia();this.log(`transfer MediaSource from ${t} ${te(s)}`),this.detachedData=s}else e&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(t,e){var s,i;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const t=this.getBufferingPlayer();t?(r=t.transferMedia(),h=`${t}`):h="detached MediaSource"}else h="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${te(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach((t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}})),this.hls.detachMedia(),this.detachedData={media:e}}const d=r&&"mediaSource"in r&&"closed"!==(null==(i=r.mediaSource)?void 0:i.readyState),c=d&&r?r:e;if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${h}`),c===r){const e=a&&t.assetId===this.schedule.assetIdAtEnd;c.overrides={duration:this.schedule.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=t.events;if(!e||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(-1===s){const s=this.hls.startPosition;if(this.timelinePos=s,e.length&&e[0].cue.pre){const s=t.findEventIndex(e[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const e=this.timelinePos=s>0?s:0,i=t.findItemIndexAtTime(e);this.setSchedulePosition(i)}}else if(i&&!this.playingItem){const e=t.findItemIndex(i);this.setSchedulePosition(e)}}advanceAfterAssetEnded(t,e,s){const i=s+1;if(t.isAssetPastPlayoutLimit(i)||t.assetList[i].error){const s=this.schedule.items;if(s){const i=e+1;if(i>=s.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos=0?s[t]:null,r=this.playingItem,n=this.playingLastItem;if(this.isInterstitial(r)){var a;const h=r.event,d=this.playingAsset,c=null==d?void 0:d.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(r,i)||void 0!==e&&c!==(null==(a=h.assetList)?void 0:a[e].identifier))){var o;const e=h.findAssetIndex(d);this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${h.assetList.length} ${Jn(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(l.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:e,event:h,schedule:s.slice(0),scheduleIndex:t,player:u}),this.retreiveMediaSource(c,i),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(r,i)&&(this.endedItem=r,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${sa(r)}`),h.hasPlayed=!0,this.hls.trigger(l.INTERSTITIAL_ENDED,{event:h,schedule:s.slice(0),scheduleIndex:t}),h.cue.once)){this.updateSchedule();const t=this.schedule.items;if(i&&t){const s=this.schedule.findItemIndex(i);this.advanceSchedule(s,t,e,r,n)}return}}this.advanceSchedule(t,s,e,r,n)}advanceSchedule(t,e,s,i,r){const n=t>=0?e[t]:null,a=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach((e=>{const s=e.interstitial,i=this.schedule.findEventIndex(s.identifier);(it+1)&&this.clearInterstitial(s,n)})),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);const r=n.event;void 0===s&&(s=this.schedule.findAssetIndex(r,this.timelinePos));const o=this.waitingItem;this.assetsBuffered(n,a)||this.setBufferingItem(n);let h=this.preloadAssets(r,s);if(this.eventItemsMatch(n,o||i)||(this.waitingItem=n,this.log(`INTERSTITIAL_STARTED ${sa(n)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(l.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!a)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=n;const d=r.assetList[s];if(!d){const i=e[t+1],n=this.media;return i&&n&&!this.isInterstitial(i)&&n.currentTime=t.end)&&(s=this.getPrimaryResumption(t,e),this.timelinePos=s),this.attachPrimary(s,t)}if(!s)return;const r=this.schedule.items;r&&(this.log(`resumed ${sa(t)}`),this.hls.trigger(l.INTERSTITIALS_PRIMARY_RESUMED,{schedule:r.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const s=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(st.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return qe.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,s){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(t,s)),s||(this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,e){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(s=i.mainForwardBufferInfo)?void 0:s.start)||i.media.currentTime)-t)>.5?i.startLoad(t,e):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){this.stopLoad(),this.schedule.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(l.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(l.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level)return;const s=this.hls.levels[e.level],i=S(S({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,e){const s=this.hls.audioTracks[e.id],i=this.mediaSelection;if(!i)return void(this.altSelection=S(S({},this.altSelection),{},{audio:s}));const r=S(S({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const s=this.hls.subtitleTracks[e.id],i=this.mediaSelection;if(!i)return void(this.altSelection=S(S({},this.altSelection),{},{subtitles:s}));const r=S(S({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(t,e){const s=ie(e);this.playerQueue.forEach((t=>t.hls.setAudioOption(e)||t.hls.setAudioOption(s)))}onSubtitleTrackSwitch(t,e){const s=ie(e);this.playerQueue.forEach((t=>t.hls.setSubtitleOption(e)||-1!==e.id&&t.hls.setSubtitleOption(s)))}onBufferCodecs(t,e){const s=e.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){const e=this.schedule.events;if(this.bufferedPost)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(t);if(this.bufferedPos=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=i),i-a>1&&!1===(null==r||null==(h=r.event)?void 0:h.appendInPlace))return;if(this.bufferedPos=t,o>s&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start{const s=this.getAssetPlayer(t.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(e))}))}setBufferingItem(t){const e=this.bufferingItem,s=this.schedule;if(this.itemsMatch(t,e))this.bufferingItem!==t&&(this.bufferingItem=t);else{const{items:i,events:r}=s;if(!i||!r)return e;const n=this.isInterstitial(t),a=this.getBufferingPlayer();if(this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos)),!this.playbackDisabled){const s=a?a.remaining:e?e.end-this.timelinePos:0;this.log(`buffered to boundary ${sa(t)}`+(e?` (${s.toFixed(2)} remaining)`:"")),n?t.event.assetList.forEach((t=>{const e=this.getAssetPlayer(t.identifier);e&&e.resumeBuffering()})):(this.hls.resumeBuffering(),this.playerQueue.forEach((t=>t.pauseBuffering())))}this.hls.trigger(l.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}return e}bufferedToItem(t,e=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==s){this.bufferingAsset=null;const e=this.detachedData;if(e)if(e.mediaSource){const e=!0;this.attachPrimary(t.start,t,e)}else this.preloadPrimary(t);else this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),s=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(s)}bufferedToEvent(t,e){const s=t.event,i=0===s.assetList.length&&!s.assetListLoader,r=s.cue.once;if(i||!r){const t=this.preloadAssets(s,e);if(null!=t&&t.interstitial.appendInPlace){const i=s.assetList[e],r=this.primaryMedia;i&&r&&this.bufferAssetPlayer(t,r)}}}preloadAssets(t,e){const s=t.assetUrl,i=t.assetList.length,r=0===i&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart;if(t.appendInPlace){var a;const e=this.playingItem;this.isInterstitial(e)||(null==e||null==(a=e.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(n=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${s?1:i} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),s)return this.createAsset(t,0,0,r,t.duration,s);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&i){for(let s=e;s{this.hls.trigger(l.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})}))}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let s=0;s1){const s=e.duration;s&&t{if(i.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),i={fatal:!0,type:a.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};return void this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,e.message)}const r=i.edge-i.fragmentStart,n=e.duration;(null===n||r>n)&&(this.log(`Interstitial asset "${f}" duration change ${n} > ${r}`),e.duration=r,this.updateSchedule())};p.on(l.LEVEL_UPDATED,((t,{details:e})=>v(e))),p.on(l.LEVEL_PTS_UPDATED,((t,{details:e})=>v(e)));const y=(t,e)=>{const s=this.getAssetPlayer(f);if(s&&e.tracks){s.off(l.BUFFER_CODECS,y),s.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===s.assetItem&&t&&!s.media&&this.bufferAssetPlayer(s,t)}};p.on(l.BUFFER_CODECS,y);const T=()=>{var s;const i=this.getAssetPlayer(f);if(this.log(`buffered to end of asset ${i}`),!i)return;const r=this.schedule.findEventIndex(t.identifier),n=t.findAssetIndex(e),a=n+1,o=null==(s=this.schedule.items)?void 0:s[r];if(this.isInterstitial(o))if(-1===n||t.isAssetPastPlayoutLimit(a)||t.assetList[a].error){var l;const t=null==(l=this.schedule.items)?void 0:l[r+1];t&&this.bufferedToItem(t)}else this.bufferedToItem(o,a)};p.on(l.BUFFERED_TO_END,T);const L=e=>()=>{if(!this.getAssetPlayer(f))return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,s,e)};return p.once(l.MEDIA_ENDED,L(s)),p.once(l.PLAYOUT_LIMIT_REACHED,L(1/0)),p.on(l.ERROR,((e,i)=>{const r=this.getAssetPlayer(f);if(i.details!==o.BUFFER_STALLED_ERROR)this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,`Asset player error ${i.error} ${t}`);else if(null!=r&&r.media){const e=r.currentTime,s=r.duration-e;e&&t.appendInPlace&&s/r.media.playbackRate<.5?(this.log(`Advancing buffer past end of asset ${f} ${t} at ${r.media.currentTime}`),T()):(this.warn(`Stalled at ${e} of ${e+s} in asset ${f} ${t}`),this.onTimeupdate(),this.checkBuffer(!0))}})),p.on(l.DESTROYING,(()=>{if(!this.getAssetPlayer(f))return;const e=new Error(`Asset player destroyed unexpectedly ${f}`),i={fatal:!0,type:a.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(i,t,this.schedule.findEventIndex(t.identifier),s,e.message)})),this.hls.trigger(l.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:s,event:t,player:p}),p}clearInterstitial(t,e){t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,e)})),t.reset()}clearAssetPlayer(t,e){const s=this.getAssetPlayerQueueIndex(t);if(-1!==s){this.log(`clearAssetPlayer "${t}" toSegment: ${e?sa(e):e}`);const i=this.playerQueue[s];this.transferMediaFromPlayer(i,e),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=t,h=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,s[i]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${h} ${t}`),this.hls.trigger(l.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:s.slice(0),scheduleIndex:i,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var s,i;const{interstitial:r,assetItem:n,assetId:l}=t,h=this.schedule.findEventIndex(r.identifier),d=null==(s=this.schedule.items)?void 0:s[h];if(!d)return;this.setBufferingItem(d),this.bufferingAsset=n;const c=this.getBufferingPlayer();if(c===t)return;const u=r.appendInPlace;if(u&&!1===(null==c?void 0:c.interstitial.appendInPlace))return;const f=(null==c?void 0:c.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(u&&n!==this.playingAsset){if(!t.tracks)return;if(f&&!P(f,t.tracks)){const e=new Error(`Asset "${l}" SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(f)}')`),s={fatal:!0,type:a.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},i=r.findAssetIndex(n);return void this.handleAssetItemError(s,r,h,i,e.message)}}this.transferMediaTo(t,e)}handleAssetItemError(t,e,s,i,r){if(t.details===o.BUFFER_STALLED_ERROR)return;const n=e.assetList[i]||null;let a=null;if(n){const t=this.getAssetPlayerQueueIndex(n.identifier);a=this.playerQueue[t]||null}const h=this.schedule.items,d=E({},t,{fatal:!1,errorAction:Ie(!0),asset:n,assetListIndex:i,event:e,schedule:h,scheduleIndex:s,player:a});if(this.warn(`Asset item error: ${t.error}`),this.hls.trigger(l.INTERSTITIAL_ASSET_ERROR,d),!t.fatal)return;const c=new Error(r);n&&(this.playingAsset!==n&&this.clearAssetPlayer(n.identifier,null),n.error=c),e.assetList.some((t=>!t.error))?e.appendInPlace&&(e.error=c):e.error=c,this.primaryFallback(e)}primaryFallback(t){const e=t.timelineStart,s=this.effectivePlayingItem;if(this.updateSchedule(),s){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${this.timelinePos} playing: ${s?sa(s):""} error: ${t.error}`),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e));let i=this.timelinePos;-1===i&&(i=this.hls.startPosition);const r=this.updateItem(s,i);if(this.itemsMatch(s,r))this.clearInterstitial(t,null);else{const t=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(t)}}else this.checkStart()}onAssetListLoaded(t,e){var s;const i=e.event,r=i.identifier,n=e.assetListResponse.ASSETS;if(!this.schedule.hasEvent(r))return;const a=i.timelineStart,o=i.duration;let l=0;n.forEach(((t,e)=>{const s=parseFloat(t.DURATION);this.createAsset(i,e,l,a+l,s,t.URI),l+=s})),i.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${o}) ${i}`);const h=this.waitingItem,d=(null==h?void 0:h.event.identifier)===r;this.updateSchedule();const c=null==(s=this.bufferingItem)?void 0:s.event;if(d){var u;const t=this.schedule.findEventIndex(r),e=null==(u=this.schedule.items)?void 0:u[t];if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return i.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${i}`),void this.primaryFallback(i)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==c?void 0:c.identifier)===r&&c.appendInPlace){const t=i.assetList[0],e=this.getAssetPlayer(t.identifier),s=this.primaryMedia;t&&e&&s&&this.bufferAssetPlayer(e,s)}}onError(t,e){switch(e.details){case o.ASSET_LIST_PARSING_ERROR:case o.ASSET_LIST_LOAD_ERROR:case o.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&this.primaryFallback(t);break}case o.BUFFER_STALLED_ERROR:this.onTimeupdate(),this.checkBuffer(!0)}}}});function co(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(co):Object.keys(t).reduce(((e,s)=>(e[s]=co(t[s]),e)),{}):t}function uo(t,e){const s=t.loader;if(s!==ro&&s!==lo)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=ro,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class fo extends Ye{constructor(t,e){super("gap-controller",t.logger),this.hls=null,this.fragmentTracker=null,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(l.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const s=this.media=e.media;ra(s,"playing",this.onMediaPlaying),ra(s,"waiting",this.onMediaWaiting),ra(s,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:s}=this;s&&(na(s,"playing",this.onMediaPlaying),na(s,"waiting",this.onMediaWaiting),na(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var s,i;const r=null==(s=this.hls)?void 0:s.config;if(!r)return;const{media:n,stalled:a}=this;if(!n)return;const{seeking:o}=n,h=this.seeking&&!o,d=!this.seeking&&o,c=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,t!==e)return e&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!c&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(d||h)return void(h&&this.stallResolved(t));if(c)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(l.MEDIA_ENDED,{stalled:!1})));if(!qe.getBuffered(n).length)return void(this.nudgeRetry=0);const u=qe.bufferInfo(n,t,0),f=u.nextStart||0,g=this.fragmentTracker;if(o&&g&&this.hls){const e=go(this.hls.inFlightFragments,t),s=u.len>2,i=!f||e||f-t>2&&!g.getPartialFragment(t);if(s||i)return;this.moved=!1}const m=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&g){if(!(u.len>0)&&!f)return;const e=Math.max(f,u.start||0)-t,s=!(null==m||!m.live)?2*m.targetduration:2,i=g.getPartialFragment(t);if(e>0&&(e<=s||i))return void(n.paused||this._trySkipBufferHole(i))}const p=r.detectStallWithCurrentTimeMs,v=self.performance.now(),y=this.waiting;if(null===a)return void(this.stalled=y>0&&v-y=p||y)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==m||!m.live)&&Math.abs(t-((null==m?void 0:m.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(l.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}const S=qe.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(S,E)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(l.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&i&&i.length>1&&t>i.end(0)){const s=qe.bufferedInfo(qe.timeRangesToArray(this.buffered.audio),t,0);if(s.len>1&&e>=s.start){const s=qe.timeRangesToArray(i),r=qe.bufferedInfo(s,e,0).bufferedIndex;if(r>-1&&rr)&&n-i<1&&t-i<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${i} -> ${n} buffered index: ${e}`);this.warn(s.message),this.media.currentTime+=1e-6;const r=this.fragmentTracker.getPartialFragment(t)||void 0,h=qe.bufferInfo(this.media,t,0);this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:r,buffer:h.len,bufferInfo:h})}}}}}_tryFixBufferStall(t,e){var s,i;const{fragmentTracker:r,media:n}=this,a=null==(s=this.hls)?void 0:s.config;if(!n||!r||!a)return;const o=n.currentTime,l=null==(i=this.hls)?void 0:i.latestLevelDetails,h=r.getPartialFragment(o);if(h||null!=l&&l.live&&o1&&t.len>a.maxBufferHole||t.nextStart&&t.nextStart-o1e3*a.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}_reportStall(t){const{hls:e,media:s,stallReported:i,stalled:r}=this;if(!i&&null!==r&&s&&e){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${te(t)})`);this.warn(i.message),e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:s,media:i}=this,r=null==(e=this.hls)?void 0:e.config;if(!i||!s||!r)return 0;const n=i.currentTime,h=qe.bufferInfo(i,n,0),d=n0&&h.len<1&&i.readyState<3,g=d-n;if(g>0&&(e||u)){if(g>r.maxBufferHole){let e=!1;if(0===n){const t=s.getAppendedFrag(0,f);t&&d{const t=po();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Eo{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(l.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(t,e){var s;this.media=e.media,!1===(null==(s=e.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){const t=this.hls.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&Hn(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;eyo&&(i=yo);i-s<=0&&(i=s+.25);for(let t=0;tt.type===Zi.audioId3&&o:"video"===i?t=>t.type===Zi.emsg&&a:t=>t.type===Zi.audioId3&&o||t.type===Zi.emsg&&a,Vn(r,e,s,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:s}=this,{dateRanges:r}=t,n=Object.keys(r);let a=this.dateRangeCuesAppended;var o;if(s&&e)if(null!=(o=s.cues)&&o.length){const t=Object.keys(a).filter((t=>!n.includes(t)));for(let e=t.length;e--;){const i=t[e],r=a[i].cues;delete a[i],Object.keys(r).forEach((t=>{try{const e=r[t];e.removeEventListener("enter",this.onEventCueEnter),s.removeCue(e)}catch(t){}}))}}else a=this.dateRangeCuesAppended={};const l=t.fragments[t.fragments.length-1];if(0===n.length||!i(null==l?void 0:l.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const h=po();for(let t=0;t{if(e!==s.id){const i=r[e];if(i.class===s.class&&i.startDate>s.startDate&&(!t||s.startDate.01&&(n.startTime=i,n.endTime=f);else if(h){let t=s.attr[r];is(r)&&(d=t,t=Uint8Array.from(d.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const n=vo(h,i,f,{key:r,data:t},Zi.dateRange);n&&(n.id=e,this.id3Track.addCue(n),l[r]=n,this.hls.config.interstitialsController&&("X-ASSET-LIST"!==r&&"X-ASSET-URL"!==r||n.addEventListener("enter",this.onEventCueEnter)))}}a[e]={cues:l,dateRange:s,durationKnown:u}}var d,c}}class To{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(e,Math.max(1,s));this.changeMediaPlaybackRate(t,i)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:s,targetduration:i}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const s=this.levelDetails;if(null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var s;e.details===o.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var s,i;t.playbackRate!==e&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class So extends Zr{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t=>{t.loadError=0,t.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e;const h=t.attrs;let{audioCodec:d,videoCodec:c}=t;d&&(t.audioCodec=d=Ot(d,s)||void 0),0===(null==(e=c)?void 0:e.indexOf("avc1"))&&(c=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}(c));const{width:u,height:f,unknownCodecs:g}=t;let m=g?g.length:0;if(g)for(let e=m;e--;){const s=g[e];this.isAudioSupported(s)?(t.audioCodec=d=d?`${d},${s}`:s,m--,bt.audio[d.substring(0,4)]=2):this.isVideoSupported(s)&&(t.videoCodec=c=c?`${c},${s}`:s,m--,bt.video[c.substring(0,4)]=2)}if(a||(a=!(!u||!f)),o||(o=!!c),l||(l=!!d),m||d&&!this.isAudioSupported(d)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${h.CODECS}"`);const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=h,L=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(r[L])if(r[L].uri===t.url||t.attrs["PATHWAY-ID"])r[L].addGroupId("audio",h.AUDIO),r[L].addGroupId("text",h.SUBTITLES);else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=this.createLevel(t);r[L]=s,i.push(s)}else{const e=this.createLevel(t);r[L]=e,n[L]=1,i.push(e)}})),this.filterAndSortMediaOptions(i,e,a,o,l)}createLevel(t){const e=new Qt(t),s=t.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(t.message),e.supportedResult=$t(t,[])}return e}isAudioSupported(t){return kt(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return kt(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,s,i,r){let n=[],h=[],d=t;if((s||i)&&r&&(d=d.filter((({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&(!!(r=e)&&Yt.indexOf(r)>-1);var r}))),0===d.length)return void Promise.resolve().then((()=>{if(this.hls){let t="no level with compatible codecs found in manifest",s=t;e.levels.length&&(s=`one or more CODECS in variant not supported: ${te(e.levels.map((t=>t.attrs.CODECS)).filter(((t,e,s)=>s.indexOf(t)===e)))}`,this.warn(s),t+=` (${s})`);const i=new Error(t);this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:i,reason:s})}}));e.audioTracks&&(n=e.audioTracks.filter((t=>!t.audioCodec||this.isAudioSupported(t.audioCodec))),Lo(n)),e.subtitles&&(h=e.subtitles,Lo(h));const c=d.slice(0);d.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Yt.indexOf(t.videoRange)-Yt.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=Pt(t.videoCodec),i=Pt(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=Ct(t.codecSet),i=Ct(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let u=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==c.length))for(let t=0;ts&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const g=r&&!i,m={levels:d,audioTracks:n,subtitleTracks:h,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:!g&&n.some((t=>!!t.url))};this.hls.trigger(l.MANIFEST_PARSED,m)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const s=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],h=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&i&&r===h)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${h?" with Pathway "+h:""} from level ${s}${r?" with Pathway "+r:""}`);const d={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(l.LEVEL_SWITCHING,d);const c=n.details;if(!c||c.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,c);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),s=t.filter((t=>-1!==e.indexOf(t)));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=s}}onError(t,e){!e.fatal&&e.context&&e.context.type===d&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===f){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(i,e,t)}else null!=(s=e.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${s}`),this.hls.trigger(l.LEVEL_LOADING,{url:s,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const s=this._levels.filter(((e,s)=>s!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));si(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(l.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(l.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Lo(t){const e={};t.forEach((t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++}))}function Ao(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ro(){if(!_())return!1;const t=Ao();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class bo extends Si{constructor(t,e,s){super(t,e,s,"stream-controller",f),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=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!i(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const s=this.getFwdBufferInfoAtPos(t,e,f,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(l.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(l.BUFFER_CREATED,this.onBufferCreated,this),t.on(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(l.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(l.BUFFER_CREATED,this.onBufferCreated,this),t.off(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}s>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=di,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=hi}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ti:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=di;break}if(this.hls.nextLoadLevel!==this.level){this.state=di;break}break}case fi:{var t;const e=self.performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,s=null==t?void 0:t[e];this.resetStartWhenNotLoaded(s||null),this.state=di}}}this.state===di&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(l.BUFFER_EOS,t),void(this.state=vi)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const h=n.details;if(!h||this.state===Ti||this.waitForLive(n))return this.level=r,this.state=Ti,void(this.startFragRequested=!1);const d=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let g=this.getNextFragment(u,h);if(this.couldBacktrack&&!this.fragPrevious&&g&&j(g)&&this.fragmentTracker.getState(g)!==Pe){var m;const t=(null!=(m=this.backtrackFragment)?m:g).sn-h.startSN,e=h.fragments[t-1];e&&g.cc===e.cc&&(g=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,u)){if(!g.gap){const t=this.audioOnly&&!this.altAudio?H:V,e=(t===V?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,f)}g=this.getNextFragmentLoopLoading(g,h,a,f,c)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,n,u))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i===ke||i===_e?j(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,s):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,f)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let s;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case ci:case ui:case fi:case mi:case pi:this.state=di}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;ra(s,"playing",this.onMediaPlaying),ra(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:s}=this;s&&(na(s,"playing",this.onMediaPlaying),na(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(l.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let s=!1,i=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),i=i||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&i&&!function(){var t;const e=Ao();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:s}=this;if(!s||this.state!==di)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Ti)}onLevelLoaded(t,e){var s;const{levels:i,startFragRequested:r}=this,n=e.level,a=e.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const h=e.levelInfo,d=this.fragCurrent;!d||this.state!==ui&&this.state!==fi||d.level!==e.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(s=h.details)&&s.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,h.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(h.details=a,this.levelLastLoaded=h,r||this.setStartPosition(a,c),this.hls.trigger(l.LEVEL_UPDATED,{details:a,level:n}),this.state===Ti){if(this.waitForCdnTuneIn(a))return;this.state=di}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r{var t;null==(t=this.hls)||t.trigger(l.AUDIO_TRACK_SWITCHED,e)})),void s.trigger(l.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(l.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=le(e.url,this.hls);if(s){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=s?2:0,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(r=t,i=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e,r=s.type===f;if(r){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===pi&&(this.state=di));const t=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),j(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&qe.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var s;if(e.fatal)this.state=yi;else switch(e.details){case o.FRAG_GAP:case o.FRAG_PARSING_ERROR:case o.FRAG_DECRYPT_ERROR:case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f,e);break;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ti||(null==(s=e.context)?void 0:s.type)!==d||(this.state=di);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case o.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=di,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==H||!this.altAudio){const t=(e===V?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,f),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let s=this.startPosition;if(s>=0&&e0&&(o{const{hls:s}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=di,this.startFragRequested=!1,this.bitrateTest=!1;const r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(l.FRAG_LOADED,t),i.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const s=this.playlistType,{hls:r}=this,{remuxResult:n,chunkMeta:a}=t,o=this.getCurrentContext(a);if(!o)return void this.resetWhenMissingContext(a);const{frag:h,part:d,level:c}=o,{video:u,text:f,id3:g,initSegment:m}=n,{details:p}=c,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(h))this.fragmentTracker.removeFragment(h);else{if(this.state=mi,m){if(null!=m&&m.tracks){const t=h.initSegment||h;this._bufferInitSegment(c,m.tracks,t,a),r.trigger(l.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:m.tracks})}const t=m.initPTS,e=m.timescale;i(t)&&(this.initPTS[h.cc]={baseTime:t,timescale:e},r.trigger(l.INIT_PTS_FOUND,{frag:h,id:s,initPTS:t,timescale:e}))}if(u&&p){const t=p.fragments[h.sn-1-p.startSN],e=h.sn===p.startSN,s=!t||h.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:i,startDTS:r,endDTS:n}=u;if(d)d.elementaryStreams[u.type]={startPTS:t,endPTS:i,startDTS:r,endDTS:n};else if(u.firstKeyFrame&&u.independent&&1===a.id&&!s&&(this.couldBacktrack=!0),u.dropped&&u.independent){const r=this.getMainFwdBufferInfo(),a=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=u.firstKeyFramePTS?u.firstKeyFramePTS:t;if(!e&&a2&&(h.gap=!0);h.setElementaryStreamInfo(u.type,t,i,r,n),this.backtrackFragment&&(this.backtrackFragment=h),this.bufferFragmentData(u,h,d,a,e||s)}else{if(!e&&!s)return void this.backtrack(h);h.gap=!0}}if(v){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=v;d&&(d.elementaryStreams[H]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),h.setElementaryStreamInfo(H,t,e,s,i),this.bufferFragmentData(v,h,d,a)}if(p&&null!=g&&null!=(e=g.samples)&&e.length){const t={id:s,frag:h,details:p,samples:g.samples};r.trigger(l.FRAG_PARSING_METADATA,t)}if(p&&f){const t={id:s,frag:h,details:p,samples:f.samples};r.trigger(l.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,i){if(this.state!==mi)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:r,video:n,audiovideo:a}=e;if(r){let s=Mt(r.codec,t.audioCodec);"mp4a"===s&&(s="mp4a.40.5");const i=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===i.indexOf("firefox")&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),t.audioCodec&&t.audioCodec!==s&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${s}"`),r.levelCodec=s,r.id=f,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${t.audioCodec||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=f;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(l.BUFFER_CODECS,e),!this.hls)return;o.forEach((t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(l.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,f)}get maxBufferLength(){const{levels:t,level:e}=this,s=null==t?void 0:t[e];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=di}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(qe.isBuffered(t,s)?e=this.getAppendedFrag(s):qe.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger(l.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(l.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return i(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(i(e)){const t=this.getLevelDetails(),s=this.currentFrag||(t?de(null,t.fragments,e):null);if(s){const t=s.programDateTime;if(null!==t){const i=t+1e3*(e-s.start);return new Date(i)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Io{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=o.KEY_LOAD_ERROR,s,i,r){return new Ve({type:a.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=t;for(let t=0;t{r.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var s,i;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const s=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var l;if(null!=(i=a)&&i.keyLoadPromise)switch(null==(l=a.mediaKeySessionContext)?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(r.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(s);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,s)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,i=new(0,s.loader)(s);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,i)=>{const{frag:a,keyInfo:l,url:h}=s;if(!a.decryptdata||l!==this.keyUriToKeyInfo[h])return n(this.createKeyLoadError(a,o.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));l.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,l.loader=null,r({frag:a,keyInfo:l})},onError:(t,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,o.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,S({url:a.url,data:void 0},t)))},onTimeout:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,o.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,o.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,h,d)}))}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function ko(t){const{type:e}=t;switch(e){case c:return g;case u:return m;default:return f}}function Do(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}class _o{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(l.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_LOADING,this.onLevelLoading,this),t.off(l.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(l.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:h,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:d,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:c,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:u,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const s=this.loaders[d];if(s){const t=s.context;t&&!e.levels.some((e=>e===t.levelOrTrack))&&(s.abort(),delete this.loaders[d])}}load(t){var e;const s=this.hls.config;let r,n=this.getInternalLoader(t);if(n){const e=this.hls.logger,s=n.context;if(s&&s.levelOrTrack===t.levelOrTrack&&(s.url===t.url||s.deliveryDirectives&&!t.deliveryDirectives))return void(s.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${s.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(r=t.type===h?s.manifestLoadPolicy.default:E({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),i(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===d&&null!==t.level?e=this.hls.levels[t.level].details:t.type===c&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===u&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);r=E({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),Ms.isMediaPlaylist(n)||s.type!==h?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),i||null,e)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};n.load(t,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=Do(t,s),o=Ms.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:h,levels:d,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g}=o;this.variableList=g;const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Ms.parseMasterPlaylistMedia(n,a,o);if(m.length){m.some((t=>!t.url))||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ss({}),bitrate:0,url:""}))}r.trigger(l.MANIFEST_LOADED,{levels:d,audioTracks:m,subtitles:p,captions:v,contentSteering:h,url:a,stats:e,networkDetails:i,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,s,r,n){const a=this.hls,{id:o,level:d,type:c}=s,u=Do(t,s),f=i(d)?d:i(o)?o:0,g=ko(s),m=Ms.parseLevelPlaylist(t.data,u,f,g,0,this.variableList);if(c===h){const t={attrs:new ss({}),bitrate:0,details:m,name:"",url:u};m.requestScheduled=e.loading.start+Js(m,0),a.trigger(l.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:u,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=m,this.handlePlaylistLoaded(m,t,e,s,r,n)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.MANIFEST_PARSING_ERROR,fatal:e.type===h,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===d?n+=`: ${t.level} id: ${t.id}`:t.type!==c&&t.type!==u||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const f=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let g=o.UNKNOWN,m=!1;const p=this.getInternalLoader(t);switch(t.type){case h:g=s?o.MANIFEST_LOAD_TIMEOUT:o.MANIFEST_LOAD_ERROR,m=!0;break;case d:g=s?o.LEVEL_LOAD_TIMEOUT:o.LEVEL_LOAD_ERROR,m=!1;break;case c:g=s?o.AUDIO_TRACK_LOAD_TIMEOUT:o.AUDIO_TRACK_LOAD_ERROR,m=!1;break;case u:g=s?o.SUBTITLE_TRACK_LOAD_TIMEOUT:o.SUBTITLE_LOAD_ERROR,m=!1}p&&this.resetInternalLoader(t.type);const v={type:a.NETWORK_ERROR,details:g,fatal:m,url:t.url,loader:p,context:t,error:f,networkDetails:e,stats:r};if(i){const s=(null==e?void 0:e.url)||t.url;v.response=S({url:s,data:void 0},i)}this.hls.trigger(l.ERROR,v)}handlePlaylistLoaded(t,e,s,i,r,n){const g=this.hls,{type:m,level:p,id:v,groupId:y,deliveryDirectives:E}=i,T=Do(e,i),S=ko(i),L="number"==typeof i.level&&S===f?p:void 0;if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void g.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_EMPTY_ERROR,fatal:!1,url:T,error:n,reason:n.message,response:e,context:i,level:L,parent:S,networkDetails:r,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const A=t.playlistParsingError;if(A){if(this.hls.logger.warn(A),!g.config.ignorePlaylistParsingErrors)return void g.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:T,error:A,reason:A.message,response:e,context:i,level:L,parent:S,networkDetails:r,stats:s});t.playlistParsingError=null}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),m){case h:case d:g.trigger(l.LEVEL_LOADED,{details:t,levelInfo:i.levelOrTrack||g.levels[0],level:L||0,id:v||0,stats:s,networkDetails:r,deliveryDirectives:E,withoutMultiVariant:m===h});break;case c:g.trigger(l.AUDIO_TRACK_LOADED,{details:t,track:i.levelOrTrack,id:v||0,groupId:y||"",stats:s,networkDetails:r,deliveryDirectives:E});break;case u:g.trigger(l.SUBTITLE_TRACK_LOADED,{details:t,track:i.levelOrTrack,id:v||0,groupId:y||"",stats:s,networkDetails:r,deliveryDirectives:E})}}}class Po{static get version(){return Di}static isMSESupported(){return Ro()}static isSupported(){return function(){if(!Ro())return!1;const t=_();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(_t(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(_t(e,"audio")))))}()}static getMediaSource(){return _()}static get Events(){return l}static get MetadataSchema(){return Zi}static get ErrorTypes(){return a}static get ErrorDetails(){return o}static get DefaultConfig(){return Po.defaultConfig?Po.defaultConfig:ho}static set DefaultConfig(t){Po.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ki,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;const e=this.logger=function(t,e,s){const i=b();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach((e=>{i[e]=I(e,t,s)}));try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.0`)}catch(t){return b()}r.forEach((e=>{k[e]=I(e,t)}))}else E(k,i);return i}(t.debug||!1,"Hls instance",t.assetPlayerId),s=this.config=function(t,e,s){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=co(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];r.forEach((s=>{const r=`${t}Loading${s}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=i[n].default;switch(e[n]={default:t},s){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${te(e[n])}`)})),S(S({},i),e)}(Po.DefaultConfig,t,e);this.userConfig=t,s.progressive&&uo(s,e);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=s,h=new a(this),d=this.abrController=new i(this),c=new Ce(this),u=s.interstitialsController,f=u?this.interstitialsController=new u(this,Po):null,g=this.bufferController=new r(this,c),m=this.capLevelController=new n(this),p=new o(this),v=new _o(this),y=s.contentSteeringController,T=y?new y(this):null,L=this.levelController=new So(this,T),A=new Eo(this),R=new Io(this.config),D=this.streamController=new bo(this,c,R),_=this.gapController=new fo(this,c);m.setStreamController(D),p.setStreamController(D);const P=[v,L,D];f&&P.splice(1,0,f),T&&P.splice(1,0,T),this.networkControllers=P;const C=[d,g,_,m,p,A,c];this.audioTrackController=this.createController(s.audioTrackController,P);const w=s.audioStreamController;w&&P.push(this.audioStreamController=new w(this,c,R)),this.subtitleTrackController=this.createController(s.subtitleTrackController,P);const x=s.subtitleStreamController;x&&P.push(this.subtititleStreamController=new x(this,c,R)),this.createController(s.timelineController,C),R.emeController=this.emeController=this.createController(s.emeController,C),this.cmcdController=this.createController(s.cmcdController,C),this.latencyController=this.createController(To,C),this.coreComponents=C,P.push(h);const O=h.onErrorOut;"function"==typeof O&&this.on(l.ERROR,O,h),this.on(l.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,i){this._emitter.off(t,e,s,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const s=t===l.ERROR;this.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(l.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,s=e?t.media:t,i=e?t:{media:s};this._media=s,this.trigger(l.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(l.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(l.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,s=this._url,i=this._url=G.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),e&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(l.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", ":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s{t.resumeBuffering&&t.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((t=>{t.pauseBuffering&&t.pauseBuffering()})))}get inFlightFragments(){const t={[f]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[g]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[m]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)}))}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Vt.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const s=t.length;for(let i=0;i=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=s)return e}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return Ht(t,se(e),navigator.mediaCapabilities)}}Po.defaultConfig=void 0}}]);