ogplayer 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ogplayer.js CHANGED
@@ -1,4 +1,4 @@
1
- var B=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Kd=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=qd},qd=Number.MAX_SAFE_INTEGER||9007199254740991,W=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),L=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.ASSET_LIST_LOAD_ERROR="assetListLoadError",r.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",r.ASSET_LIST_PARSING_ERROR="assetListParsingError",r.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.ATTACH_MEDIA_ERROR="attachMediaError",r.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",r.UNKNOWN="unknown",r}({}),y=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.MEDIA_ENDED="hlsMediaEnded",r.STALL_RESOLVED="hlsStallResolved",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFERED_TO_END="hlsBufferedToEnd",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r.ASSET_LIST_LOADING="hlsAssetListLoading",r.ASSET_LIST_LOADED="hlsAssetListLoaded",r.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",r.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",r.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",r.INTERSTITIAL_STARTED="hlsInterstitialStarted",r.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",r.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",r.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",r.INTERSTITIAL_ENDED="hlsInterstitialEnded",r.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",r.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",r.EVENT_CUE_ENTER="hlsEventCueEnter",r}({});function Wd(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Us={exports:{}},pa;function Yd(){return pa||(pa=1,function(r,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,c){if(c=c||{},l=l.trim(),d=d.trim(),!d){if(!c.alwaysNormalize)return l;var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var u=o.parseURL(d);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return c.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(m.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)m.path=f.path,u.params||(m.params=f.params,u.query||(m.query=f.query));else{var p=f.path,v=p.substring(0,p.lastIndexOf("/")+1)+u.path;m.path=o.normalizePath(v)}return m.path===null&&(m.path=c.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(m)},parseURL:function(l){var d=i.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};r.exports=o})()}(Us)),Us.exports}var Nr=Yd(),ri=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},te={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack",MEDIA_FRAGMENT:"media-fragment",KEY:"key",STEERING_MANIFEST:"steering-manifest",SERVER_CERTIFICATE:"server-certificate",INTERSTITIAL_ASSET_LIST:"interstitial-asset-list"},H={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},he={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},ji=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,jd(this,"stats")}setByteRange(e,t){let i=e.split("@",2),s;i.length===1?s=t?.byteRangeEndOffset||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[he.AUDIO]:null,[he.VIDEO]:null,[he.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new ri),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=Nr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[he.AUDIO]=null,e[he.VIDEO]=null,e[he.AUDIOVIDEO]=null,this.url=null}};function ve(r){return r.sn!=="initSegment"}function Zt(r,e){return r.sn===e?.sn&&r.level===e.level}function gn(r,e){return r.sn===e?.sn&&r.level===e.level&&r.cc===e.cc}var Ut=class extends ji{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(B(e)&&B(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let i=Object.keys(t);if(i.length===1){let s=this._decryptdata=t[i[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=B(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;let i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!B(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ve(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let s=t[e];s&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,n)}},mn=class extends ji{constructor(e,t,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===H.SUBTITLE&&this.stats.loaded)}};function Ho(r,e){let t=Object.getPrototypeOf(r);if(t){let i=Object.getOwnPropertyDescriptor(t,e);return i||Ho(t,e)}}function jd(r,e){let t=Ho(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}function zd(r,e,t){return(e=Zd(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function ce(){return ce=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(r[i]=t[i])}return r},ce.apply(null,arguments)}function ya(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,i)}return t}function Y(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ya(Object(t),!0).forEach(function(i){zd(r,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):ya(Object(t)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(t,i))})}return r}function Ps(r,e){if(r==null)return{};var t,i,s=Xd(r,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);for(i=0;i<n.length;i++)t=n[i],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(r,t)&&(s[t]=r[t])}return s}function Xd(r,e){if(r==null)return{};var t={};for(var i in r)if({}.hasOwnProperty.call(r,i)){if(e.indexOf(i)!==-1)continue;t[i]=r[i]}return t}function Qd(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var i=t.call(r,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Zd(r){var e=Qd(r,"string");return typeof e=="symbol"?e:e+""}function zi(r){switch(r.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:case L.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Ko(r){return r.details.startsWith("key")}function qo(r){return Ko(r)&&!!r.frag&&!r.frag.decryptdata}function va(r,e){let t=zi(e);return r.default[`${t?"timeout":"error"}Retry`]}function Br(r,e){let t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function Ea(r){return Y(Y({},r),{errorRetry:null,timeoutRetry:null})}function ai(r,e,t,i){if(!r)return!1;let s=i?.code,n=e<r.maxNumRetry&&(Jd(s)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,n):n}function Jd(r){return oi(r)||!!r&&(r<400||r>499)}function oi(r){return r===0&&navigator.onLine===!1}function Wo(r,e){return e>0&&r.loadError>0&&r.loadErrorTime!==0&&self.performance.now()-r.loadErrorTime>e}var pt=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},pn=class{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new pt(e),this.fast_=new pt(t),this.defaultTTFB_=s,this.ttfb_=new pt(e)}update(e,t){let{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new pt(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new pt(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new pt(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){if(t<=0)return;let i=Math.min(this.minDelayMs_,t/1e5),s=8*t,n=Math.max(e,i)/1e3,a=s/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}sampleTTFB(e){let t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},Oe=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=yt,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}},yt=function(){},ec={trace:yt,debug:yt,log:yt,warn:yt,info:yt,error:yt};function yn(){return ce({},ec)}function tc(r,e){let t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):yt}function Ta(r,e,t){return e[r]?e[r].bind(e):tc(r,t)}var vn=yn();function ic(r,e,t){let i=yn();if(typeof console=="object"&&r===!0||typeof r=="object"){let s=["debug","log","info","warn","error"];s.forEach(n=>{i[n]=Ta(n,r,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.7.1`)}catch{return yn()}s.forEach(n=>{vn[n]=Ta(n,r)})}else ce(vn,i);return i}var oe=vn;function bt(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function sc(r){return typeof self<"u"&&r===self.ManagedMediaSource}function Yo(r,e){let t=Object.keys(r),i=Object.keys(e),s=t.length,n=i.length;return!s||!n||s===n&&!t.some(a=>i.indexOf(a)===-1)}function nc(r){return btoa(String.fromCharCode(...r))}function _s(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}var rc="utf-16",Gs="utf-16be",Sa="utf-16le",Vi="utf-8";function ac(r,e={}){let t;_s(r)?t=new DataView(r):t=new DataView(r.buffer,r.byteOffset,r.byteLength);let i=0,{encoding:s}=e;if(!s){let d=t.getUint8(0),c=t.getUint8(1);d==239&&c==187&&t.getUint8(2)==191?(s=Vi,i=3):d==254&&c==255?(s=Gs,i=2):d==255&&c==254?(s=Sa,i=2):s=Vi}if(typeof TextDecoder<"u")return new TextDecoder(s).decode(t);let{byteLength:n}=t,a=s!==Gs,o="",l;for(;i<n;){switch(s){case Vi:if(l=t.getUint8(i),l<128)i++;else if(l>=194&&l<=223)if(i+1<n){let d=t.getUint8(i+1);d>=128&&d<=191?(l=(l&31)<<6|d&63,i+=2):i++}else i++;else if(l>=224&&l<=239)if(i+2<=n-1){let d=t.getUint8(i+1),c=t.getUint8(i+2);d>=128&&d<=191&&c>=128&&c<=191?(l=(l&15)<<12|(d&63)<<6|c&63,i+=3):i++}else i++;else if(l>=240&&l<=244)if(i+3<=n-1){let d=t.getUint8(i+1),c=t.getUint8(i+2),h=t.getUint8(i+3);d>=128&&d<=191&&c>=128&&c<=191&&h>=128&&h<=191?(l=(l&7)<<18|(d&63)<<12|(c&63)<<6|h&63,i+=4):i++}else i++;else i++;break;case Gs:case rc:case Sa:l=t.getUint16(i,a),i+=2;break}o+=String.fromCodePoint(l)}return o}function oc(r){let e=typeof r=="string"?new URL(r):r;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function jo(r,e){if(r<0)return-jo(-r,e);let t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){let i=Math.floor(r*t);return(i%2===0?i:i+1)/t}else return Math.round(r*t)/t}function lc(r,e){let t;try{t=new URL(r)}catch{return r}let i=new URL(e);if(t.origin!==i.origin)return r;let s=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1),a=Math.min(s.length,n.length);for(let o=0;o<a&&s[o]===n[o];o++)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+t.search+t.hash}function zo(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?s:s&3|8).toString(16)})}}}function $r(r,e){return e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function ks(r,e){let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t}function dc(r,e){return $r(r,e)&&ks(r,e+6)+10<=r.length-e}function Xo(r,e){return e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function li(r,e){let t=e,i=0;for(;$r(r,e);){i+=10;let s=ks(r,e+6);i+=s,Xo(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)}function cc(r){return _s(r)?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Vs(r,e=0,t=1/0){return hc(r,e,t,Uint8Array)}function hc(r,e,t,i){let s=uc(r),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);let a=fc(r)?r.byteOffset:0,o=(a+r.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o)));return new i(s,d,Math.floor(Math.min(d+Math.max(t,0),o))-d)}function uc(r){return _s(r)?r:r.buffer}function fc(r){return r&&_s(r.buffer)&&r.byteLength!==void 0&&r.byteOffset!==void 0}function He(r,e=!1){let t=e?r.indexOf(0):r.length,i=ac(new DataView(r.buffer,r.byteOffset,t),{encoding:Vi});return e?i:i.replace(/\0/g,"")}function gc(r){let e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let i=r.data.subarray(1).indexOf(0);if(i===-1)return;let s=He(Vs(r.data,1,i)),n=r.data[2+i],a=r.data.subarray(3+i).indexOf(0);if(a===-1)return;let o=He(Vs(r.data,3+i,a)),l;return s==="-->"?l=He(Vs(r.data,4+i+a)):l=cc(r.data.subarray(4+i+a)),e.mimeType=s,e.pictureType=n,e.description=o,e.data=l,e}function mc(r){if(r.size<2)return;let e=He(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function pc(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1,{data:i}=r,s=He(i.subarray(t),!0);t+=s.length+1;let n=He(i.subarray(t));return{key:r.type,info:s,data:n}}let e=He(r.data.subarray(1));return{key:r.type,info:"",data:e}}function yc(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1,i=He(r.data.subarray(t),!0);t+=i.length+1;let s=He(r.data.subarray(t));return{key:r.type,info:i,data:s}}let e=He(r.data);return{key:r.type,info:"",data:e}}function vc(r){return r.type==="PRIV"?mc(r):r.type[0]==="W"?yc(r):r.type==="APIC"?gc(r):pc(r)}function Ec(r){let e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=ks(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}var Ri=10,Tc=10;function Qo(r){let e=0,t=[];for(;$r(r,e);){let i=ks(r,e+6);r[e+5]>>6&1&&(e+=Ri),e+=Ri;let s=e+i;for(;e+Tc<s;){let n=Ec(r.subarray(e)),a=vc(n);a&&t.push(a),e+=n.size+Ri}Xo(r,e)&&(e+=Ri)}return t}function Zo(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function Sc(r){if(r.data.byteLength===8){let e=new Uint8Array(r.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Ur(r){let e=Qo(r);for(let t of e)if(Zo(t))return Sc(t)}function Ie(r){let e="";for(let t=0;t<r.length;t++){let i=r[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function Jo(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Gr(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function et(r){return String.fromCharCode.apply(null,r)}var nt=Math.pow(2,32)-1,X={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},el={video:1,audio:2,id3:3,text:4};function tl(r,e){let t=r[e]<<8|r[e+1];return t<0?65536+t:t}function V(r,e){let t=r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3];return t<0?4294967296+t:t}function ba(r,e){let t=V(r,e);return t*=Math.pow(2,32),t+=V(r,e+4),t}function Pi(r,e){let t="";for(let i=e;i<r.length;i++)if(t+=String.fromCharCode(r[i]),r[i]===0)return t;return null}function En(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Se(r,e,t){r[e]=t>>24,r[e+1]=t>>16&255,r[e+2]=t>>8&255,r[e+3]=t&255}function Aa(r,e,t){let i=e.byteOffset-r.byteOffset-8,s=8+t,n=e.byteLength+8-s;n<8||(Se(r,i,s),Se(r,i+s,n),Se(r,i+s+4,X.free))}function Tn(r,e){return[r.byteOffset-e-8,r.byteOffset-e+r.byteLength]}function il(r,e){e.sort((o,l)=>o[0]-l[0]);let t=e.reduce((o,[l,d])=>o+d-l,0),i=new Uint8Array(r.byteLength-t),s=0,n=0;for(let o=0;o<e.length;o++){let[l,d]=e[o];i.set(r.subarray(s,l),n),n+=l-s,s=d}return i.set(r.subarray(s),n),{result:i,dropped:t,droppedBefore:o=>e.reduce((l,[d,c])=>c<=o?l+c-d:l,0)}}function bc(r){let e=Q(r,["moov"]);if(e.length!==1||Q(r,["moof"]).length)return null;let t=r.byteOffset,i=[],s=[],n=!1,a=Q(e[0],["trak"]);for(let f=0;f<a.length;f++){let g=a[f],m=Q(g,["mdia","hdlr"])[0];if((m?et(m.subarray(8,12)):"")==="vide"){n=!0;continue}let v=Q(g,["tkhd"])[0];if(!v)return null;let T=v[0];s.push(V(v,T===0?12:20)),i.push(Tn(g,t))}if(!n||!i.length)return null;let o=Q(e[0],["mvex"])[0],l=0;if(o){let f=Q(o,["trex"]);for(let g=0;g<f.length;g++){let m=f[g];s.indexOf(V(m,4))!==-1&&(i.push(Tn(m,t)),l+=m.byteLength+8)}}let{result:d,dropped:c,droppedBefore:h}=il(r,i),u=e[0].byteOffset-t-8;if(Se(d,u,e[0].byteLength+8-c),o&&l){let f=o.byteOffset-t-8;Se(d,f-h(f),o.byteLength+8-l)}return d}function Ac(r,e,t,i,s){if(t<1)return null;let n=Q(r,["moof"]);if(n.length!==1)return null;let a=n[0],o=r.byteOffset,l=[],d=[],c=Q(a,["traf"]),h=!0;for(let m=0;m<c.length;m++){let p=c[m],v=Q(p,["tfhd"])[0];if(!v)return null;V(v,4)===e?(l.push(p),V(v,0)&131072||(h=!1)):d.push(Tn(p,o))}if(!l.length||d.length&&!h)return null;if(i!==void 0){let m=t;for(let v=0;v<l.length;v++){let T=l[v],E=0,S=Q(T,["trun"]);for(let x=0;x<S.length;x++){let R=S[x],P=Math.min(m,V(R,4));if(P){Se(r,R.byteOffset-o+4,P);let I=V(R,0)&16777215,k=(I&256?4:0)+(I&512?4:0)+(I&1024?4:0)+(I&2048?4:0);Aa(r,R,8+(I&1?4:0)+(I&4?4:0)+P*k)}else Se(r,R.byteOffset-o-4,X.free);m-=P,E+=P}let b=Q(T,["senc"])[0];b&&Se(r,b.byteOffset-o+4,E);let A=Q(T,["saiz"])[0];if(A){let x=A[1]<<16|A[2]<<8|A[3],R=4;x&1&&(R+=8);let P=A[R];R+=1,Se(r,A.byteOffset-o+R,E),Aa(r,A,R+4+(P===0?E:0))}}let p=Q(r,["mdat"]);if(p.length===1){let v=p[0].byteOffset-o-8;Se(r,v,i-v)}}let u=r,f=0,g=()=>0;if(d.length){({result:u,dropped:f,droppedBefore:g}=il(r,d)),Se(u,a.byteOffset-o-8,a.byteLength+8-f);for(let m=0;m<l.length;m++){let p=l[m],v=g(p.byteOffset-o),T=Q(p,["trun"]);for(let E=0;E<T.length;E++){let S=T[E];V(S,0)&1&&Se(u,S.byteOffset-o-v+8,V(S,8)-f)}if(v){let E=Q(p,["saio"]);for(let S=0;S<E.length;S++){let b=E[S],A=b[0]===0?4:8,x=V(b,0)&1?12:4,R=V(b,x);for(x+=4;R--;x+=A){let P=x+A-4;Se(u,b.byteOffset-o-v+P,V(b,P)-v)}}}}}if(s){let{durationOffset:m,value:p}=s;Se(u,m-g(m),p)}return i!==void 0?u.subarray(0,i-f):u}function xc(r,e){let t=r.byteLength;for(let i=0;i<t;){let s=V(r,i);if(s>8&&V(r,i+4)===X[e])return!0;i=s>1?i+s:t}return!1}function Q(r,e){let t=[];return e.length&&sl(r,e,0,0,r.byteLength,t),t}function sl(r,e,t,i,s,n){let a=e[t];if(a?.length!==4)return;let o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),c=a.charCodeAt(3),h=e.length-1;for(let u=i;u<s;){let f=u+8<=s,g=u+4<=s?r[u]*16777216+(r[u+1]<<16|r[u+2]<<8|r[u+3]):V(r,u),m=g>1?u+g:s;if(f&&r[u+4]===o&&r[u+5]===l&&r[u+6]===d&&r[u+7]===c){let p=Math.min(m,s);t===h?n.push(r.subarray(u+8,p)):sl(r,e,t+1,u+8,p,n)}u=m}}function Ic(r){let e=[],t=r[0],i=8,s=V(r,i);i+=4;let n=0,a=0;t===0?(n=V(r,i),a=V(r,i+4),i+=8):(n=ba(r,i),a=ba(r,i+8),i+=16),i+=2;let o=r.length+a,l=tl(r,i);i+=2;for(let d=0;d<l;d++){let c=i,h=V(r,c);c+=4;let u=h&2147483647;if((h&2147483648)>>>31===1)return oe.warn("SIDX has hierarchical references (not supported)"),null;let g=V(r,c);c+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/s,start:o,end:o+u-1}}),o+=u,c+=4,i=c}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:l,references:e}}function nl(r){let e=[],t=Q(r,["moov","trak"]);for(let s=0;s<t.length;s++){let n=t[s],a=Q(n,["tkhd"])[0];if(a){let o=a[0],l=V(a,o===0?12:20),d=Q(n,["mdia","mdhd"])[0];if(d){o=d[0];let c=V(d,o===0?12:20),h=Q(n,["mdia","hdlr"])[0];if(h){let u=et(h.subarray(8,12)),f={soun:he.AUDIO,vide:he.VIDEO}[u],g=Q(n,["mdia","minf","stbl","stsd"])[0],m=Lc(g);f?(e[l]={timescale:c,type:f,stsd:m},e[f]=Y({timescale:c,id:l},m)):e[l]={timescale:c,type:u,stsd:m}}}}}return Q(r,["moov","mvex","trex"]).forEach(s=>{let n=V(s,4),a=e[n];a&&(a.default={duration:V(s,12),sampleSize:V(s,16),flags:V(s,20)})}),e}function Lc(r){let e=r.subarray(8),t=e.subarray(86),i=et(e.subarray(4,8)),s=i,n,a=i==="enca"||i==="encv";if(a){let d=Q(e,[i])[0].subarray(i==="enca"?28:78);Q(d,["sinf"]).forEach(h=>{let u=Q(h,["schm"])[0];if(u){let f=et(u.subarray(4,8));if(f==="cbcs"||f==="cenc"){let g=Q(h,["frma"])[0];g&&(s=et(g))}}})}let o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{let l=Q(t,["avcC"])[0];l&&l.length>3&&(s+="."+ki(l[1])+ki(l[2])+ki(l[3]),n=_i(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=Q(e,[i])[0],d=Q(l.subarray(28),["esds"])[0];if(d&&d.length>7){let c=4;if(d[c++]!==3)break;c=Hs(d,c),c+=2;let h=d[c++];if(h&128&&(c+=2),h&64&&(c+=d[c++]),d[c++]!==4)break;c=Hs(d,c);let u=d[c++];if(u===64)s+="."+ki(u);else break;if(c+=12,d[c++]!==5)break;c=Hs(d,c);let f=d[c++],g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((d[c]&224)>>5)),s+="."+g}break}case"hvc1":case"hev1":{let l=Q(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],c=["","A","B","C"][d>>6],h=d&31,u=V(l,2),f=(d&32)>>5?"H":"L",g=l[12],m=l.subarray(6,12);s+="."+c+h,s+="."+Rc(u).toString(16).toUpperCase(),s+="."+f+g;let p="";for(let v=m.length;v--;){let T=m[v];(T||p)&&(p="."+T.toString(16).toUpperCase()+p)}s+=p}n=_i(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=_i(s,t)||s;break}case"vp09":{let l=Q(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],c=l[5],h=l[6]>>4&15;s+="."+rt(d)+"."+rt(c)+"."+rt(h)}break}case"av01":{let l=Q(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,c=l[1]&31,h=l[2]>>>7?"H":"M",u=(l[2]&64)>>6,f=(l[2]&32)>>5,g=d===2&&u?f?12:10:u?10:8,m=(l[2]&16)>>4,p=(l[2]&8)>>3,v=(l[2]&4)>>2,T=l[2]&3;s+="."+d+"."+rt(c)+h+"."+rt(g)+"."+m+"."+p+v+T+"."+rt(1)+"."+rt(1)+"."+rt(1)+"."+0,n=_i("dav1",t)}break}}return{codec:s,encrypted:a,supplemental:n}}function _i(r,e){let t=Q(e,["dvvC"]),i=t.length?t[0]:Q(e,["dvcC"])[0];if(i){let s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return r+"."+rt(s)+"."+rt(n)}}function Rc(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function Hs(r,e){let t=e+5;for(;r[e++]&128&&e<t;);return e}function ki(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function rt(r){return(r<10?"0":"")+r}function Pc(r,e){if(!r||!e)return;let t=e.keyId;t?.byteLength===16&&e.isCommonEncryption&&rl(r,(i,s)=>{let n=i.subarray(8,24);n.some(a=>a!==0)||(oe.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Ie(n)} -> ${Ie(t)}`),i.set(t,8))})}function _c(r){let e=[];return rl(r,t=>e.push(t.subarray(8,24))),e}function rl(r,e){Q(r,["moov","trak"]).forEach(i=>{let s=Q(i,["mdia","minf","stbl","stsd"])[0];if(!s)return;let n=s.subarray(8),a=Q(n,["enca"]),o=a.length>0;o||(a=Q(n,["encv"])),a.forEach(l=>{let d=o?l.subarray(28):l.subarray(78);Q(d,["sinf"]).forEach(h=>{let u=al(h);u&&e(u,o)})})})}function al(r){let e=Q(r,["schm"])[0];if(e){let t=et(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let i=Q(r,["schi","tenc"])[0];if(i)return i}}}var xa;function kc(r){return typeof TextDecoder>"u"?He(r):(xa||(xa=new TextDecoder("utf-8"))).decode(r).replace(/\0/g,"")}function Dc(r){let e=r.byteLength,t=[];for(let i=0;i<e;){let s=i+8<=e,n=i+4<=e?r[i]*16777216+(r[i+1]<<16|r[i+2]<<8|r[i+3]):V(r,i),a=n>1?i+n:e;if(s&&r[i+4]===109&&r[i+5]===111&&r[i+6]===111&&r[i+7]===102){let o=Math.min(a,e);for(let l=i+8;l<o;){let d=l+8<=o,c=l+4<=o?r[l]*16777216+(r[l+1]<<16|r[l+2]<<8|r[l+3]):V(r,l),h=c>1?l+c:o;if(d&&r[l+4]===116&&r[l+5]===114&&r[l+6]===97&&r[l+7]===102){let u=Math.min(h,o),f,g,m=[];for(let p=l+8;p<u;){let v=p+8<=u,T=p+4<=u?r[p]*16777216+(r[p+1]<<16|r[p+2]<<8|r[p+3]):V(r,p),E=T>1?p+T:u;if(v&&r[p+4]===116){let S=Math.min(E,u);r[p+5]===102&&r[p+6]===104&&r[p+7]===100?g||(g=r.subarray(p+8,S)):r[p+5]===102&&r[p+6]===100&&r[p+7]===116?f||(f=r.subarray(p+8,S)):r[p+5]===114&&r[p+6]===117&&r[p+7]===110&&m.push(r.subarray(p+8,S))}p=E}t.push({moofOffset:r.byteOffset+i,tfdt:f,tfhd:g,truns:m})}l=h}}i=a}return t}function Cc(r,e,t,i,s=!0){return ol(r,e,i,s)}function wc(r,e,t,i,s=!1){let n=[],a=e.samples,o=ol(a,t,i,s,{isHEVCFlavor:bi(e.codec),samples:n,timeOffset:r,timescale:e.timescale,trackId:e.id});return{samples:n,sampleData:{includeSampleDetails:s,tracks:o}}}function ol(r,e,t,i,s){let n={},a=!1,o=Dc(r),l=r.byteLength;for(let h=0;h<o.length;h++){let{moofOffset:u,tfdt:f,tfhd:g,truns:m}=o[h],p=V(g,4),v=e[p];if(!v)continue;let T=n[p]||(n[p]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type}),E;if(f){let M=f[0];E=V(f,4),M===1&&(E===nt?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(E*=nt+1,E+=V(f,8))),B(E)&&(!B(T.start)||E<T.start)&&(T.start=E),s&&B(E)&&(s.timeOffset=E/s.timescale)}let S=s?.trackId===p&&v.type===he.VIDEO,b=v.default,A=V(g,0)&16777215,x=b?.duration||0,R,P=b?.sampleSize||0,I=8;A&1&&(I+=8),A&2&&(I+=4),A&8&&(x=V(g,I),R=g.byteOffset-r.byteOffset+I,I+=4),A&16&&(P=V(g,I));let k=0,D=(A&1)!==0,F=!D&&(A&131072)!==0;D?(k=V(g,8),k*=Math.pow(2,32),k+=V(g,12)):F&&(k=u);let G=E||0,$=0,C=x;for(let M=0;M<m.length;M++){let w=m[M],N=V(w,4),K=T.sampleCount;T.sampleCount+=N;let O=w[3]&1,U=0,Z=w[3]&4,j=w[2]&1,ie=w[2]&2,z=w[2]&4,ne=w[2]&8,ee=8;O&&(U=En(w,ee),ee+=4),Z&&(!(w[ee+1]&1)&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=K),ee+=4);let ae=k+U;if(!i&&w[1]===0&&w[2]===6&&w[3]===1){var d,c;let ge=G,Ke=ae,tt=ee,q=-1,se=0,re=0,Ae=(d=s?.timeOffset)!=null?d:0,Te=x/((c=s?.timescale)!=null?c:1),Ce=s?.isHEVCFlavor===!0,je=Ce?2:1;for(let Pe=0;Pe<N;Pe++){let we=w[ee]===0?w[ee+1]<<16|w[ee+2]<<8|w[ee+3]:V(w,ee),qe=q===-1&&T.keyFrameIndex===void 0&&(w[ee+5]&1)===0;ee+=8;let $e=ae+we;if(S){if(we>0){let De=ae;do{let gt=r[De]===0?r[De+1]<<16|r[De+2]<<8|r[De+3]:V(r,De);De+=4;let ct=r[De],ze=Ce?ct>>1&63:ct&31;(Ce?ze===39||ze===40:ze===6)&&di(r.subarray(De,De+gt),je,Ae,s.samples),De+=gt}while(De<$e)}Ae+=Te}ae=$e,qe&&(q=Pe,se=ae)}if(ae<=l)re=N;else{let Pe=Ke,we=tt;for(let qe=0;qe<N;qe++){let $e=w[we]===0?w[we+1]<<16|w[we+2]<<8|w[we+3]:V(w,we);if(Pe+=$e,Pe>l)break;re=qe+1,we+=8}}if(S&&(s.timeOffset=Ae),q!==-1&&se<=l&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=q,T.keyFrameStart=ge+q*x),re){(!B(T.ptsMin)||ge<T.ptsMin)&&(T.ptsMin=ge);let Pe=ge+re*x;(!B(T.ptsMax)||Pe>T.ptsMax)&&(T.ptsMax=Pe)}let It=x*N;G=ge+It,$+=It;continue}let be,Fe;i&&(be=[],Fe={sampleOffset:ae,samples:be,defaultSampleDurationOffset:R},ae<=l&&T.trun.push(Fe));let dt;for(let ge=0;ge<N;ge++){let Ke;j?(i&&(Ke=w.byteOffset-r.byteOffset+ee),C=V(w,ee),ee+=4):C=x,ie?(dt=V(w,ee),ee+=4):dt=P;let tt,q;z&&(q=w[ee+1]&1?1:0,i&&(tt={isNonSync:q,dependsOn:(w[ee]&3)===1?1:2}),ee+=4);let se=0;if(ne&&(se=w[0]===0?V(w,ee):En(w,ee),ee+=4),S){let re=ae,Ae=0;for(;Ae<dt;){let Te=V(r,re);re+=4,ll(s.isHEVCFlavor,r[re])&&di(r.subarray(re,re+Te),s.isHEVCFlavor?2:1,s.timeOffset+se/s.timescale,s.samples),re+=Te,Ae+=Te+4}s.timeOffset+=C/s.timescale}if(ae+=dt,ae<=l){Fe&&Ke!==void 0&&(Fe.lastSampleDurationOffset=Ke),q===0&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=ge,T.keyFrameStart=G);let re=G+se;(!B(T.ptsMin)||re<T.ptsMin)&&(T.ptsMin=re),(!B(T.ptsMax)||re+C>T.ptsMax)&&(T.ptsMax=re+C),be&&(be[ge]={cts:se,duration:C,flags:tt,size:dt})}G+=C,$+=C}!$&&x&&($+=x*N)}T.duration+=$,T.duration&&(a=!0)}if(!a){let h=1/0,u=0,f=Q(r,["sidx"]);for(let g=0;g<f.length;g++){let m=Ic(f[g]);if(m!=null&&m.references){h=Math.min(h,m.earliestPresentationTime/m.timescale);let p=m.references.reduce((v,T)=>v+T.info.duration||0,0);u=Math.max(u,p+m.earliestPresentationTime/m.timescale)}}u&&B(u)&&Object.keys(n).forEach(g=>{n[g].duration||(n[g].duration=u*n[g].timescale-n[g].start)})}return n}function Mc(r){let e={valid:null,remainder:null},t=Q(r,["moof"]);if(t.length<2)return e.remainder=r,e;let i=t[t.length-1];return e.valid=r.slice(0,i.byteOffset-8),e.remainder=r.slice(i.byteOffset-8),e}function Ye(r,e){let t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Oc(r,e){let t=[],i=e.samples,s=e.timescale,n=e.id,a=!1;return Q(i,["moof"]).map(l=>{let d=l.byteOffset-8;Q(l,["traf"]).map(h=>{let u=Q(h,["tfdt"]).map(f=>{let g=f[0],m=V(f,4);return g===1&&(m*=Math.pow(2,32),m+=V(f,8)),m/s})[0];return u!==void 0&&(r=u),Q(h,["tfhd"]).map(f=>{let g=V(f,4),m=V(f,0)&16777215,p=(m&1)!==0,v=0,T=(m&2)!==0,E=(m&8)!==0,S=0,b=(m&16)!==0,A=0,x=(m&32)!==0,R=!p&&(m&131072)!==0,P=8;g===n&&(p?(v=V(f,P),P+=4,v*=Math.pow(2,32),v+=V(f,P),P+=4):R&&(v=d),T&&(P+=4),E&&(S=V(f,P),P+=4),b&&(A=V(f,P),P+=4),x&&(P+=4),e.type==="video"&&(a=bi(e.codec)),Q(h,["trun"]).map(I=>{let k=I[0],D=V(I,0)&16777215,F=(D&1)!==0,G=0,$=(D&4)!==0,C=(D&256)!==0,M=0,w=(D&512)!==0,N=0,K=(D&1024)!==0,O=(D&2048)!==0,U=0,Z=V(I,4),j=8;F&&(G=V(I,j),j+=4),$&&(j+=4);let ie=v+G;for(let z=0;z<Z;z++){if(C?(M=V(I,j),j+=4):M=S,w?(N=V(I,j),j+=4):N=A,K&&(j+=4),O&&(k===0?U=V(I,j):U=En(I,j),j+=4),e.type===he.VIDEO){let ne=0;for(;ne<N;){let ee=V(i,ie);if(ie+=4,ll(a,i[ie])){let ae=i.subarray(ie,ie+ee);di(ae,a?2:1,r+U/s,t)}ie+=ee,ne+=ee+4}}r+=M/s}}))})})}),t}function bi(r){if(!r)return!1;let e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function ll(r,e){if(r){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function di(r,e,t,i){let s=dl(r),n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(l===255);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(l===255);let d=s.length-n,c=n;if(o<d)n+=o;else if(o>d){oe.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(s[c++]===181){let u=tl(s,c);if(c+=2,u===49){let f=V(s,c);if(c+=4,f===1195456820){let g=s[c++];if(g===3){let m=s[c++],p=31&m,v=64&m,T=v?2+p*3:0,E=new Uint8Array(T);if(v){E[0]=m;for(let S=1;S<T;S++)E[S]=s[c++]}i.push({type:g,payloadType:a,pts:t,bytes:E})}}}}}else if(a===5&&o>16){let h=[];for(let g=0;g<16;g++){let m=s[c++].toString(16);h.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&h.push("-")}let u=o-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=s[c++];i.push({payloadType:a,pts:t,uuid:h.join(""),userData:kc(f),userDataBytes:f})}}}function dl(r){let e=r.byteLength,t,i=r.indexOf(3,3);for(;i!==-1;)r[i-1]===0&&r[i-2]===0&&(t||(t=[])).push(i),i=r.indexOf(3,i+1);if(!t)return r;let s=e-t.length,n=new Uint8Array(s),a=0,o=0;for(let l=0;l<s;o++,l++)o===t[a]&&(o++,a++),n[l]=r[o];return n}function Fc(r){let e=r[0],t="",i="",s=0,n=0,a,o=0,l=0,d=4;if(e===0){let h=Pi(r,d),u=h!==null?Pi(r,d+h.length):null;h!==null&&u!==null?(t=h,i=u,d+=h.length+u.length,s=V(r,d),d+=4,n=V(r,d),d+=4,o=V(r,d),d+=4,l=V(r,d),d+=4):(oe.warn(`Unterminated ${h===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),d=r.length)}else if(e===1){s=V(r,d),d+=4;let h=V(r,d);d+=4;let u=V(r,d);d+=4,a=2**32*h+u,Kd(a)||(a=Number.MAX_SAFE_INTEGER,oe.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=V(r,d),d+=4,l=V(r,d),d+=4;let f=Pi(r,d),g=f!==null?Pi(r,d+f.length):null;f!==null&&(t=f,d+=f.length),g!==null?(i=g,d+=g.length):(oe.warn(`Unterminated ${f===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${f===null?"strings and payload":"value and payload"}`),d=r.length)}let c=r.subarray(d,r.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function Nc(r,...e){let t=e.length,i=8,s=t;for(;s--;)i+=e[s].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(r,4),s=0,i=8;s<t;s++)n.set(e[s],i),i+=e[s].byteLength;return n}function Bc(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let i,s;i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Nc([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,a,t)}function cl(r){let e=[];if(r instanceof ArrayBuffer){let t=r.byteLength,i=0;for(;i+32<t;){let s=new DataView(r,i),n=Uc(s);e.push(n),i+=n.size}}return e}function $c(r){let e=[];for(let t=0;t<r.length;){let i=r[t++],s=i&7;if(s===0){for(;r[t++]&128;);continue}if(s!==2){t+=s===1?8:4;continue}let n=0;for(let a=0,o=128;o&128;a+=7)n|=((o=r[t++])&127)<<a;if(i>>3===2)if(n===32){let a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(r[t+o*2],r[t+o*2+1]),16);e.push(a)}else n===16&&e.push(r.subarray(t,t+16));t+=n}return e}function Uc(r){let e=r.getUint32(0),t=r.byteOffset,i=r.byteLength;if(i<e)return{offset:t,size:i};if(r.getUint32(4)!==1886614376)return{offset:t,size:e};let n=r.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=r.buffer,o=Ie(new Uint8Array(a,t+12,16)),l=null,d=null,c=0;if(n===0)c=28;else{let u=r.getUint32(28);if(!u||i<32+u*16)return{offset:t,size:e};l=[];for(let f=0;f<u;f++)l.push(new Uint8Array(a,t+32+f*16,16));c=32+u*16}if(!c)return{offset:t,size:e};let h=r.getUint32(c);return e-32<h?{offset:t,size:e}:(d=new Uint8Array(a,t+c+4,h),n===0&&(l=$c(d)),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}var Yt=hl("userAgent"),Gc=hl("vendor"),Ks,qs,Ws;function hl(r){try{return navigator[r]||""}catch{}return""}function Vc(){if(Ws===void 0){let r=Yt.match(/Safari\/(\d+)/i);Ws=r?parseInt(r[1]):0}return Ws}function ei(){if(Ks===void 0){let r=Yt.match(/Chrome\/(\d+)/i);Ks=r?parseInt(r[1]):0}return Ks}function Hc(){if(qs===void 0){let r=Yt.match(/Firefox\/(\d+)/i);qs=r?parseInt(r[1]):0}return qs}function ul(){return/\(Windows.+Firefox\//i.test(Yt)}function Kc(){return Gc.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Yt)}function qc(){return/Android/.test(Yt)}var Kt={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},image:{mjpg:1}};function Vr(r,e){let t=Kt[e];return!!t&&!!t[r.slice(0,4)]}function ci(r,e,t=!0){return!r.split(",").some(i=>!Hr(i,e,t))}function Hr(r,e,t=!0){var i;let s=bt(t);return(i=s?.isTypeSupported(hi(r,e)))!=null?i:!1}function hi(r,e){return`${e}/mp4;codecs=${r}`}function Ia(r){if(r){let e=r.substring(0,4);return Kt.video[e]}return 2}function Xi(r){let e=ul();return r.split(",").reduce((t,i)=>{let n=e&&bi(i)?9:Kt.video[i];return n?(n*2+t)/(t?3:2):(Kt.audio[i]+t)/(t?2:1)},0)}var Ys={};function Wc(r,e=!0){if(Ys[r])return Ys[r];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let s=0;s<t.length;s++){var i;if(Hr(t[s],"audio",e))return Ys[r]=t[s],t[s];if(t[s]==="mp3"&&(i=bt(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return r}var Yc=/flac|opus|mp4a\.40\.34/i;function Qi(r,e=!0){return r.replace(Yc,t=>Wc(t.toLowerCase(),e))}function jc(r,e){let t=[];if(r){let i=r.split(",");for(let s=0;s<i.length;s++)Vr(i[s],"video")||t.push(i[s])}return e&&t.push(e),t.join(",")}function Hi(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(La(r,"audio")||La(r,"video")))return r;if(e){let t=e.split(",");if(t.length>1){if(r){for(let i=t.length;i--;)if(t[i].substring(0,4)===r.substring(0,4))return t[i]}return t[0]}}return e||r}function La(r,e){return Vr(r,e)&&Hr(r,e)}function zc(r){let e=r.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Xc(r){if(r.startsWith("av01.")){let e=r.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return r}function Ra(r){let e=bt(r)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Sn(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Qc={supported:!0,powerEfficient:!0,smooth:!0},Zc={supported:!1,smooth:!1,powerEfficient:!1},fl={supported:!0,configurations:[],decodingInfoResults:[Qc]};function gl(r,e){return{supported:!1,configurations:e,decodingInfoResults:[Zc],error:r}}function Jc(r,e,t,i,s,n){let a=r.videoCodec,o=r.audioCodec?r.audioGroups:null,l=n?.audioCodec,d=n?.channels,c=d?parseInt(d):l?1/0:2,h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=e.groups[o[0]].channels:h=o.reduce((u,f)=>{if(f){let g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(m=>{u[m]=(u[m]||0)+g.channels[m]})}return u},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(u=>bi(u))||r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(i,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(s,8e6))||!!h&&B(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function ml(r,e,t,i={}){let s=r.videoCodec;if(!s&&!r.audioCodec||!t)return Promise.resolve(fl);let n=[],a=eh(r),o=a.length,l=th(r,e,o>0),d=l.length;for(let c=o||1*d||1;c--;){let h={type:"media-source"};if(o&&(h.video=a[c%o]),d){h.audio=l[c%d];let u=h.audio.bitrate;h.video&&u&&(h.video.bitrate-=u)}n.push(h)}if(s){let c=navigator.userAgent;if(s.split(",").some(h=>bi(h))&&ul())return Promise.resolve(gl(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{let h=ih(c);return i[h]||(i[h]=t.decodingInfo(c))})).then(c=>({supported:!c.some(h=>!h.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:!1,configurations:n,decodingInfoResults:[],error:c}))}function eh(r){var e;let t=(e=r.videoCodec)==null?void 0:e.split(","),i=yl(r),s=r.width||640,n=r.height||480,a=r.frameRate||30,o=r.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:hi(Xc(l),"video"),width:s,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function th(r,e,t){var i;let s=(i=r.audioCodec)==null?void 0:i.split(","),n=yl(r);return s&&r.audioGroups?r.audioGroups.reduce((a,o)=>{var l;let d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((c,h)=>{if(h.groupId===o){let u=parseFloat(h.channels||"");s.forEach(f=>{let g={contentType:hi(f,"audio"),bitrate:t?pl(f,n):n};u&&(g.channels=""+u),c.push(g)})}return c},a):a},[]):[]}function pl(r,e){if(e<=1)return 1;let t=128e3;return r==="ec-3"?t=768e3:r==="ac-3"&&(t=64e4),Math.min(e/2,t)}function yl(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function ih(r){let e="",{audio:t,video:i}=r;if(i){let s=Sn(i.contentType);e+=`${s}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){let s=Sn(t.contentType);e+=`${i?"_":""}${s}_c${t.channels}`}return e}function Tt(r,e,t){let i=encodeURIComponent(e),s=`${i}=${encodeURIComponent(t)}`,n=!1,a=[];r.search.substring(1).split("&").forEach(o=>{o===i||o.startsWith(i+"=")?n||(a.push(s),n=!0):o&&a.push(o)}),n||a.push(s),r.search=a.join("&")}var bn=["NONE","TYPE-0","TYPE-1",null];function sh(r){return bn.indexOf(r)>-1}var Zi=["SDR","PQ","HLG"];function nh(r){return!!r&&Zi.indexOf(r)>-1}var Ki={No:"",Yes:"YES",v2:"v2"};function Pa(r){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=r,s=i<e/2;return e&&s?t?Ki.v2:Ki.Yes:Ki.No}var Ji=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&Tt(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&Tt(t,"_HLS_part",this.part.toString()),this.skip&&Tt(t,"_HLS_skip",this.skip),t.href}},Ct=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return _a(this._audioGroups,e)}hasSubtitleGroup(e){return _a(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function _a(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function rh(){if(typeof matchMedia=="function"){let r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function ah(r,e){let t=!1,i=[];if(r&&(t=r!=="SDR",i=[r]),e){i=e.allowedVideoRanges||Zi.slice(0);let s=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:s&&rh(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}var oh=r=>{let e=new WeakSet;return(t,i)=>{if(r&&(i=r(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},fe=(r,e)=>JSON.stringify(r,oh(e));function lh(r,e,t,i,s){let n=Object.keys(r),a=i?.channels,o=i?.audioCodec,l=s?.videoCodec,d=a&&parseInt(a)===2,c=!1,h=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[],{preferHDR:T,allowedVideoRanges:E}=ah(e,s);for(let R=n.length;R--;){let P=r[n[R]];c||(c=P.channels[2]>0),u=Math.min(u,P.minHeight),f=Math.min(f,P.minFramerate),g=Math.min(g,P.minBitrate),E.filter(k=>P.videoRanges[k]>0).length>0&&(h=!0)}u=B(u)?u:0,f=B(f)?f:0;let S=Math.max(1080,u),b=Math.max(30,f);g=B(g)?g:t,t=Math.max(g,t),h||(e=void 0);let A=n.length>1;return{codecSet:n.reduce((R,P)=>{let I=r[P];if(P===R)return R;if(v=h?E.filter(k=>I.videoRanges[k]>0):[],A){if(I.minBitrate>t)return it(P,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),R;if(!I.hasDefaultAudio)return it(P,"no renditions with default or auto-select sound found"),R;if(o&&P.indexOf(o.substring(0,4))%5!==0)return it(P,`audio codec preference "${o}" not found`),R;if(a&&!d){if(!I.channels[a])return it(P,`no renditions with ${a} channel sound found (channels options: ${Object.keys(I.channels)})`),R}else if((!o||d)&&c&&I.channels[2]===0)return it(P,"no renditions with stereo sound found"),R;if(I.minHeight>S)return it(P,`min resolution of ${I.minHeight} > maximum of ${S}`),R;if(I.minFramerate>b)return it(P,`min framerate of ${I.minFramerate} > maximum of ${b}`),R;if(!v.some(k=>I.videoRanges[k]>0))return it(P,`no variants with VIDEO-RANGE of ${fe(v)} found`),R;if(l&&P.indexOf(l.substring(0,4))%5!==0)return it(P,`video codec preference "${l}" not found`),R;if(I.maxScore<p)return it(P,`max score of ${I.maxScore} < selected max of ${p}`),R}return R&&(Xi(P)>=Xi(R)||I.fragmentError>r[R].fragmentError)?R:(m=I.minIndex,p=I.maxScore,P)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:m}}function it(r,e){oe.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function vl(r){return r.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function dh(r,e,t,i){return r.slice(t,i+1).reduce((s,n,a)=>{if(!n.codecSet)return s;let o=n.audioGroups,l=s[n.codecSet];l||(s[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;let h=e.groups[c];h&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{l.channels[u]=(l.channels[u]||0)+h.channels[u]}))}),s},{})}function ka(r){if(!r)return r;let{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}=r;return{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}}function ot(r,e,t){if("attrs"in r){let i=e.indexOf(r);if(i!==-1)return i}for(let i=0;i<e.length;i++){let s=e[i];if(kt(r,s,t))return i}return-1}function kt(r,e,t){let{groupId:i,name:s,lang:n,assocLang:a,default:o}=r,l=r.forced;return(i===void 0||e.groupId===i)&&(s===void 0||e.name===s)&&(n===void 0||ch(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in r)||hh(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function ch(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function hh(r,e=""){let t=r.split(","),i=e.split(",");return t.length===i.length&&!t.some(s=>i.indexOf(s)===-1)}function _t(r,e){let{audioCodec:t,channels:i}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function uh(r,e,t,i,s){let n=e[i],o=e.reduce((u,f,g)=>{let m=f.uri;return(u[m]||(u[m]=[])).push(g),u},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));let l=n.videoRange,d=n.frameRate,c=n.codecSet.substring(0,4),h=Da(e,i,u=>{if(u.videoRange!==l||u.frameRate!==d||u.codecSet.substring(0,4)!==c)return!1;let f=u.audioGroups,g=t.filter(m=>ui(m.groupId,f));return ot(r,g,s)>-1});return h>-1?h:Da(e,i,u=>{let f=u.audioGroups,g=t.filter(m=>ui(m.groupId,f));return ot(r,g,s)>-1})}function Da(r,e,t){for(let i=e;i>-1;i--)if(t(r[i]))return i;for(let i=e+1;i<r.length;i++)if(t(r[i]))return i;return-1}function es(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}function ui(r,e){return e?e.indexOf(r)!==-1:!0}function El(r,e){if(e||r){let t=ce({},e);return r&&(r.videoCodec&&(t.videoCodec=r.videoCodec),r.videoRange&&(t.allowedVideoRanges=[r.videoRange])),t}}var An=class extends Oe{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-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.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;let{fragCurrent:s,partCurrent:n,hls:a}=this;if(!a)return;let{autoLevelEnabled:o,media:l}=a;if(!s||!l)return;let d=performance.now(),c=n?n.stats:s.stats,h=n?n.duration:s.duration,u=d-c.loading.start,f=a.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let p=m>-1&&m!==g,v=!!t||p;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let T=a.mainForwardBufferInfo;if(!v&&T===null)return;let E=this.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(u<=Math.max(E,1e3*(h/(S*2))))return;let b=T?T.len/S:0,A=c.loading.first?c.loading.first-c.loading.start:-1,x=c.loaded&&A>-1,R=this.getBwEstimate(),P=a.levels,I=P[g],k=Math.max(c.loaded,Math.round(h*(s.bitrate||I.averageBitrate)/8)),D=x?u-A:u;D<1&&x&&(D=Math.min(u,c.loaded*8/R));let F=x?c.loaded*1e3/D:0,G=E/1e3,$=F?(k-c.loaded)/F:k*8/R+G;if($<=b)return;let C=F?F*8:R,M=((i=t?.details||a.latestLevelDetails)==null?void 0:i.live)===!0,w=a.config.abrBandWidthUpFactor,N=Number.POSITIVE_INFINITY,K;for(K=g-1;K>f;K--){let j=P[K].maxBitrate,ie=!P[K].details||M;if(N=this.getTimeToLoadFrag(G,C,h*j,ie),N<Math.min(b,h+G))break}if(N>=$||N>h*10)return;x?this.bwEstimator.sample(u-Math.min(E,A),c.loaded):this.bwEstimator.sampleTTFB(u);let O=P[K].maxBitrate;this.getBwEstimate()*w>O&&(this.firstAutoFloor=Math.min(K,a.firstLevel),this.resetEstimator(O));let U=this.findBestLevel(O,f,K,0,b,1,1);U>-1&&(K=U),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${g} is loading too slowly;
1
+ var B=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Yd=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=jd},jd=Number.MAX_SAFE_INTEGER||9007199254740991,W=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),L=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.ASSET_LIST_LOAD_ERROR="assetListLoadError",r.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",r.ASSET_LIST_PARSING_ERROR="assetListParsingError",r.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.ATTACH_MEDIA_ERROR="attachMediaError",r.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",r.UNKNOWN="unknown",r}({}),y=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.MEDIA_ENDED="hlsMediaEnded",r.STALL_RESOLVED="hlsStallResolved",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFERED_TO_END="hlsBufferedToEnd",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r.ASSET_LIST_LOADING="hlsAssetListLoading",r.ASSET_LIST_LOADED="hlsAssetListLoaded",r.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",r.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",r.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",r.INTERSTITIAL_STARTED="hlsInterstitialStarted",r.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",r.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",r.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",r.INTERSTITIAL_ENDED="hlsInterstitialEnded",r.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",r.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",r.EVENT_CUE_ENTER="hlsEventCueEnter",r}({});function zd(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Vs={exports:{}},Ea;function Xd(){return Ea||(Ea=1,function(r,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,c){if(c=c||{},l=l.trim(),d=d.trim(),!d){if(!c.alwaysNormalize)return l;var h=o.parseURL(l);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var u=o.parseURL(d);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return c.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(m.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)m.path=f.path,u.params||(m.params=f.params,u.query||(m.query=f.query));else{var p=f.path,v=p.substring(0,p.lastIndexOf("/")+1)+u.path;m.path=o.normalizePath(v)}return m.path===null&&(m.path=c.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(m)},parseURL:function(l){var d=i.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};r.exports=o})()}(Vs)),Vs.exports}var $r=Xd(),ri=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},te={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack",MEDIA_FRAGMENT:"media-fragment",KEY:"key",STEERING_MANIFEST:"steering-manifest",SERVER_CERTIFICATE:"server-certificate",INTERSTITIAL_ASSET_LIST:"interstitial-asset-list"},H={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},he={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},ji=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Qd(this,"stats")}setByteRange(e,t){let i=e.split("@",2),s;i.length===1?s=t?.byteRangeEndOffset||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[he.AUDIO]:null,[he.VIDEO]:null,[he.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new ri),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=$r.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[he.AUDIO]=null,e[he.VIDEO]=null,e[he.AUDIOVIDEO]=null,this.url=null}};function ve(r){return r.sn!=="initSegment"}function Zt(r,e){return r.sn===e?.sn&&r.level===e.level}function pn(r,e){return r.sn===e?.sn&&r.level===e.level&&r.cc===e.cc}var Ut=class extends ji{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(B(e)&&B(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let i=Object.keys(t);if(i.length===1){let s=this._decryptdata=t[i[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=B(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;let i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!B(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ve(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let s=t[e];s&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,n)}},yn=class extends ji{constructor(e,t,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===H.SUBTITLE&&this.stats.loaded)}};function Wo(r,e){let t=Object.getPrototypeOf(r);if(t){let i=Object.getOwnPropertyDescriptor(t,e);return i||Wo(t,e)}}function Qd(r,e){let t=Wo(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}function Zd(r,e,t){return(e=tc(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function ce(){return ce=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(r[i]=t[i])}return r},ce.apply(null,arguments)}function Ta(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),t.push.apply(t,i)}return t}function Y(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ta(Object(t),!0).forEach(function(i){Zd(r,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Ta(Object(t)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(t,i))})}return r}function Ps(r,e){if(r==null)return{};var t,i,s=Jd(r,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);for(i=0;i<n.length;i++)t=n[i],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(r,t)&&(s[t]=r[t])}return s}function Jd(r,e){if(r==null)return{};var t={};for(var i in r)if({}.hasOwnProperty.call(r,i)){if(e.indexOf(i)!==-1)continue;t[i]=r[i]}return t}function ec(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var i=t.call(r,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function tc(r){var e=ec(r,"string");return typeof e=="symbol"?e:e+""}function zi(r){switch(r.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:case L.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Yo(r){return r.details.startsWith("key")}function jo(r){return Yo(r)&&!!r.frag&&!r.frag.decryptdata}function Sa(r,e){let t=zi(e);return r.default[`${t?"timeout":"error"}Retry`]}function Ur(r,e){let t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function ba(r){return Y(Y({},r),{errorRetry:null,timeoutRetry:null})}function ai(r,e,t,i){if(!r)return!1;let s=i?.code,n=e<r.maxNumRetry&&(ic(s)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,i,n):n}function ic(r){return oi(r)||!!r&&(r<400||r>499)}function oi(r){return r===0&&navigator.onLine===!1}function zo(r,e){return e>0&&r.loadError>0&&r.loadErrorTime!==0&&self.performance.now()-r.loadErrorTime>e}var pt=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},vn=class{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new pt(e),this.fast_=new pt(t),this.defaultTTFB_=s,this.ttfb_=new pt(e)}update(e,t){let{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new pt(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new pt(t,s.getEstimate(),s.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new pt(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){if(t<=0)return;let i=Math.min(this.minDelayMs_,t/1e5),s=8*t,n=Math.max(e,i)/1e3,a=s/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}sampleTTFB(e){let t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},Oe=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=yt,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}},yt=function(){},sc={trace:yt,debug:yt,log:yt,warn:yt,info:yt,error:yt};function En(){return ce({},sc)}function nc(r,e){let t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):yt}function Aa(r,e,t){return e[r]?e[r].bind(e):nc(r,t)}var Tn=En();function rc(r,e,t){let i=En();if(typeof console=="object"&&r===!0||typeof r=="object"){let s=["debug","log","info","warn","error"];s.forEach(n=>{i[n]=Aa(n,r,t)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.7.1`)}catch{return En()}s.forEach(n=>{Tn[n]=Aa(n,r)})}else ce(Tn,i);return i}var oe=Tn;function bt(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ac(r){return typeof self<"u"&&r===self.ManagedMediaSource}function Xo(r,e){let t=Object.keys(r),i=Object.keys(e),s=t.length,n=i.length;return!s||!n||s===n&&!t.some(a=>i.indexOf(a)===-1)}function oc(r){return btoa(String.fromCharCode(...r))}function _s(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}var lc="utf-16",Hs="utf-16be",xa="utf-16le",Vi="utf-8";function dc(r,e={}){let t;_s(r)?t=new DataView(r):t=new DataView(r.buffer,r.byteOffset,r.byteLength);let i=0,{encoding:s}=e;if(!s){let d=t.getUint8(0),c=t.getUint8(1);d==239&&c==187&&t.getUint8(2)==191?(s=Vi,i=3):d==254&&c==255?(s=Hs,i=2):d==255&&c==254?(s=xa,i=2):s=Vi}if(typeof TextDecoder<"u")return new TextDecoder(s).decode(t);let{byteLength:n}=t,a=s!==Hs,o="",l;for(;i<n;){switch(s){case Vi:if(l=t.getUint8(i),l<128)i++;else if(l>=194&&l<=223)if(i+1<n){let d=t.getUint8(i+1);d>=128&&d<=191?(l=(l&31)<<6|d&63,i+=2):i++}else i++;else if(l>=224&&l<=239)if(i+2<=n-1){let d=t.getUint8(i+1),c=t.getUint8(i+2);d>=128&&d<=191&&c>=128&&c<=191?(l=(l&15)<<12|(d&63)<<6|c&63,i+=3):i++}else i++;else if(l>=240&&l<=244)if(i+3<=n-1){let d=t.getUint8(i+1),c=t.getUint8(i+2),h=t.getUint8(i+3);d>=128&&d<=191&&c>=128&&c<=191&&h>=128&&h<=191?(l=(l&7)<<18|(d&63)<<12|(c&63)<<6|h&63,i+=4):i++}else i++;else i++;break;case Hs:case lc:case xa:l=t.getUint16(i,a),i+=2;break}o+=String.fromCodePoint(l)}return o}function cc(r){let e=typeof r=="string"?new URL(r):r;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function Qo(r,e){if(r<0)return-Qo(-r,e);let t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){let i=Math.floor(r*t);return(i%2===0?i:i+1)/t}else return Math.round(r*t)/t}function hc(r,e){let t;try{t=new URL(r)}catch{return r}let i=new URL(e);if(t.origin!==i.origin)return r;let s=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1),a=Math.min(s.length,n.length);for(let o=0;o<a&&s[o]===n[o];o++)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+t.search+t.hash}function Zo(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?s:s&3|8).toString(16)})}}}function Gr(r,e){return e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function ks(r,e){let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t}function uc(r,e){return Gr(r,e)&&ks(r,e+6)+10<=r.length-e}function Jo(r,e){return e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function li(r,e){let t=e,i=0;for(;Gr(r,e);){i+=10;let s=ks(r,e+6);i+=s,Jo(r,e+10)&&(i+=10),e+=i}if(i>0)return r.subarray(t,t+i)}function fc(r){return _s(r)?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function Ks(r,e=0,t=1/0){return gc(r,e,t,Uint8Array)}function gc(r,e,t,i){let s=mc(r),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);let a=pc(r)?r.byteOffset:0,o=(a+r.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o)));return new i(s,d,Math.floor(Math.min(d+Math.max(t,0),o))-d)}function mc(r){return _s(r)?r:r.buffer}function pc(r){return r&&_s(r.buffer)&&r.byteLength!==void 0&&r.byteOffset!==void 0}function He(r,e=!1){let t=e?r.indexOf(0):r.length,i=dc(new DataView(r.buffer,r.byteOffset,t),{encoding:Vi});return e?i:i.replace(/\0/g,"")}function yc(r){let e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let i=r.data.subarray(1).indexOf(0);if(i===-1)return;let s=He(Ks(r.data,1,i)),n=r.data[2+i],a=r.data.subarray(3+i).indexOf(0);if(a===-1)return;let o=He(Ks(r.data,3+i,a)),l;return s==="-->"?l=He(Ks(r.data,4+i+a)):l=fc(r.data.subarray(4+i+a)),e.mimeType=s,e.pictureType=n,e.description=o,e.data=l,e}function vc(r){if(r.size<2)return;let e=He(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function Ec(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1,{data:i}=r,s=He(i.subarray(t),!0);t+=s.length+1;let n=He(i.subarray(t));return{key:r.type,info:s,data:n}}let e=He(r.data.subarray(1));return{key:r.type,info:"",data:e}}function Tc(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1,i=He(r.data.subarray(t),!0);t+=i.length+1;let s=He(r.data.subarray(t));return{key:r.type,info:i,data:s}}let e=He(r.data);return{key:r.type,info:"",data:e}}function Sc(r){return r.type==="PRIV"?vc(r):r.type[0]==="W"?Tc(r):r.type==="APIC"?yc(r):Ec(r)}function bc(r){let e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=ks(r,4),i=10;return{type:e,size:t,data:r.subarray(i,i+t)}}var Ri=10,Ac=10;function el(r){let e=0,t=[];for(;Gr(r,e);){let i=ks(r,e+6);r[e+5]>>6&1&&(e+=Ri),e+=Ri;let s=e+i;for(;e+Ac<s;){let n=bc(r.subarray(e)),a=Sc(n);a&&t.push(a),e+=n.size+Ri}Jo(r,e)&&(e+=Ri)}return t}function tl(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function xc(r){if(r.data.byteLength===8){let e=new Uint8Array(r.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Vr(r){let e=el(r);for(let t of e)if(tl(t))return xc(t)}function Ie(r){let e="";for(let t=0;t<r.length;t++){let i=r[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function il(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Hr(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function et(r){return String.fromCharCode.apply(null,r)}var nt=Math.pow(2,32)-1,X={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},sl={video:1,audio:2,id3:3,text:4};function nl(r,e){let t=r[e]<<8|r[e+1];return t<0?65536+t:t}function V(r,e){let t=r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3];return t<0?4294967296+t:t}function Ia(r,e){let t=V(r,e);return t*=Math.pow(2,32),t+=V(r,e+4),t}function Pi(r,e){let t="";for(let i=e;i<r.length;i++)if(t+=String.fromCharCode(r[i]),r[i]===0)return t;return null}function Sn(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Se(r,e,t){r[e]=t>>24,r[e+1]=t>>16&255,r[e+2]=t>>8&255,r[e+3]=t&255}function La(r,e,t){let i=e.byteOffset-r.byteOffset-8,s=8+t,n=e.byteLength+8-s;n<8||(Se(r,i,s),Se(r,i+s,n),Se(r,i+s+4,X.free))}function bn(r,e){return[r.byteOffset-e-8,r.byteOffset-e+r.byteLength]}function rl(r,e){e.sort((o,l)=>o[0]-l[0]);let t=e.reduce((o,[l,d])=>o+d-l,0),i=new Uint8Array(r.byteLength-t),s=0,n=0;for(let o=0;o<e.length;o++){let[l,d]=e[o];i.set(r.subarray(s,l),n),n+=l-s,s=d}return i.set(r.subarray(s),n),{result:i,dropped:t,droppedBefore:o=>e.reduce((l,[d,c])=>c<=o?l+c-d:l,0)}}function Ic(r){let e=Q(r,["moov"]);if(e.length!==1||Q(r,["moof"]).length)return null;let t=r.byteOffset,i=[],s=[],n=!1,a=Q(e[0],["trak"]);for(let f=0;f<a.length;f++){let g=a[f],m=Q(g,["mdia","hdlr"])[0];if((m?et(m.subarray(8,12)):"")==="vide"){n=!0;continue}let v=Q(g,["tkhd"])[0];if(!v)return null;let T=v[0];s.push(V(v,T===0?12:20)),i.push(bn(g,t))}if(!n||!i.length)return null;let o=Q(e[0],["mvex"])[0],l=0;if(o){let f=Q(o,["trex"]);for(let g=0;g<f.length;g++){let m=f[g];s.indexOf(V(m,4))!==-1&&(i.push(bn(m,t)),l+=m.byteLength+8)}}let{result:d,dropped:c,droppedBefore:h}=rl(r,i),u=e[0].byteOffset-t-8;if(Se(d,u,e[0].byteLength+8-c),o&&l){let f=o.byteOffset-t-8;Se(d,f-h(f),o.byteLength+8-l)}return d}function Lc(r,e,t,i,s){if(t<1)return null;let n=Q(r,["moof"]);if(n.length!==1)return null;let a=n[0],o=r.byteOffset,l=[],d=[],c=Q(a,["traf"]),h=!0;for(let m=0;m<c.length;m++){let p=c[m],v=Q(p,["tfhd"])[0];if(!v)return null;V(v,4)===e?(l.push(p),V(v,0)&131072||(h=!1)):d.push(bn(p,o))}if(!l.length||d.length&&!h)return null;if(i!==void 0){let m=t;for(let v=0;v<l.length;v++){let T=l[v],E=0,S=Q(T,["trun"]);for(let x=0;x<S.length;x++){let R=S[x],P=Math.min(m,V(R,4));if(P){Se(r,R.byteOffset-o+4,P);let I=V(R,0)&16777215,k=(I&256?4:0)+(I&512?4:0)+(I&1024?4:0)+(I&2048?4:0);La(r,R,8+(I&1?4:0)+(I&4?4:0)+P*k)}else Se(r,R.byteOffset-o-4,X.free);m-=P,E+=P}let b=Q(T,["senc"])[0];b&&Se(r,b.byteOffset-o+4,E);let A=Q(T,["saiz"])[0];if(A){let x=A[1]<<16|A[2]<<8|A[3],R=4;x&1&&(R+=8);let P=A[R];R+=1,Se(r,A.byteOffset-o+R,E),La(r,A,R+4+(P===0?E:0))}}let p=Q(r,["mdat"]);if(p.length===1){let v=p[0].byteOffset-o-8;Se(r,v,i-v)}}let u=r,f=0,g=()=>0;if(d.length){({result:u,dropped:f,droppedBefore:g}=rl(r,d)),Se(u,a.byteOffset-o-8,a.byteLength+8-f);for(let m=0;m<l.length;m++){let p=l[m],v=g(p.byteOffset-o),T=Q(p,["trun"]);for(let E=0;E<T.length;E++){let S=T[E];V(S,0)&1&&Se(u,S.byteOffset-o-v+8,V(S,8)-f)}if(v){let E=Q(p,["saio"]);for(let S=0;S<E.length;S++){let b=E[S],A=b[0]===0?4:8,x=V(b,0)&1?12:4,R=V(b,x);for(x+=4;R--;x+=A){let P=x+A-4;Se(u,b.byteOffset-o-v+P,V(b,P)-v)}}}}}if(s){let{durationOffset:m,value:p}=s;Se(u,m-g(m),p)}return i!==void 0?u.subarray(0,i-f):u}function Rc(r,e){let t=r.byteLength;for(let i=0;i<t;){let s=V(r,i);if(s>8&&V(r,i+4)===X[e])return!0;i=s>1?i+s:t}return!1}function Q(r,e){let t=[];return e.length&&al(r,e,0,0,r.byteLength,t),t}function al(r,e,t,i,s,n){let a=e[t];if(a?.length!==4)return;let o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),c=a.charCodeAt(3),h=e.length-1;for(let u=i;u<s;){let f=u+8<=s,g=u+4<=s?r[u]*16777216+(r[u+1]<<16|r[u+2]<<8|r[u+3]):V(r,u),m=g>1?u+g:s;if(f&&r[u+4]===o&&r[u+5]===l&&r[u+6]===d&&r[u+7]===c){let p=Math.min(m,s);t===h?n.push(r.subarray(u+8,p)):al(r,e,t+1,u+8,p,n)}u=m}}function Pc(r){let e=[],t=r[0],i=8,s=V(r,i);i+=4;let n=0,a=0;t===0?(n=V(r,i),a=V(r,i+4),i+=8):(n=Ia(r,i),a=Ia(r,i+8),i+=16),i+=2;let o=r.length+a,l=nl(r,i);i+=2;for(let d=0;d<l;d++){let c=i,h=V(r,c);c+=4;let u=h&2147483647;if((h&2147483648)>>>31===1)return oe.warn("SIDX has hierarchical references (not supported)"),null;let g=V(r,c);c+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/s,start:o,end:o+u-1}}),o+=u,c+=4,i=c}return{earliestPresentationTime:n,timescale:s,version:t,referencesCount:l,references:e}}function ol(r){let e=[],t=Q(r,["moov","trak"]);for(let s=0;s<t.length;s++){let n=t[s],a=Q(n,["tkhd"])[0];if(a){let o=a[0],l=V(a,o===0?12:20),d=Q(n,["mdia","mdhd"])[0];if(d){o=d[0];let c=V(d,o===0?12:20),h=Q(n,["mdia","hdlr"])[0];if(h){let u=et(h.subarray(8,12)),f={soun:he.AUDIO,vide:he.VIDEO}[u],g=Q(n,["mdia","minf","stbl","stsd"])[0],m=_c(g);f?(e[l]={timescale:c,type:f,stsd:m},e[f]=Y({timescale:c,id:l},m)):e[l]={timescale:c,type:u,stsd:m}}}}}return Q(r,["moov","mvex","trex"]).forEach(s=>{let n=V(s,4),a=e[n];a&&(a.default={duration:V(s,12),sampleSize:V(s,16),flags:V(s,20)})}),e}function _c(r){let e=r.subarray(8),t=e.subarray(86),i=et(e.subarray(4,8)),s=i,n,a=i==="enca"||i==="encv";if(a){let d=Q(e,[i])[0].subarray(i==="enca"?28:78);Q(d,["sinf"]).forEach(h=>{let u=Q(h,["schm"])[0];if(u){let f=et(u.subarray(4,8));if(f==="cbcs"||f==="cenc"){let g=Q(h,["frma"])[0];g&&(s=et(g))}}})}let o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{let l=Q(t,["avcC"])[0];l&&l.length>3&&(s+="."+ki(l[1])+ki(l[2])+ki(l[3]),n=_i(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=Q(e,[i])[0],d=Q(l.subarray(28),["esds"])[0];if(d&&d.length>7){let c=4;if(d[c++]!==3)break;c=qs(d,c),c+=2;let h=d[c++];if(h&128&&(c+=2),h&64&&(c+=d[c++]),d[c++]!==4)break;c=qs(d,c);let u=d[c++];if(u===64)s+="."+ki(u);else break;if(c+=12,d[c++]!==5)break;c=qs(d,c);let f=d[c++],g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((d[c]&224)>>5)),s+="."+g}break}case"hvc1":case"hev1":{let l=Q(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],c=["","A","B","C"][d>>6],h=d&31,u=V(l,2),f=(d&32)>>5?"H":"L",g=l[12],m=l.subarray(6,12);s+="."+c+h,s+="."+kc(u).toString(16).toUpperCase(),s+="."+f+g;let p="";for(let v=m.length;v--;){let T=m[v];(T||p)&&(p="."+T.toString(16).toUpperCase()+p)}s+=p}n=_i(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=_i(s,t)||s;break}case"vp09":{let l=Q(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],c=l[5],h=l[6]>>4&15;s+="."+rt(d)+"."+rt(c)+"."+rt(h)}break}case"av01":{let l=Q(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,c=l[1]&31,h=l[2]>>>7?"H":"M",u=(l[2]&64)>>6,f=(l[2]&32)>>5,g=d===2&&u?f?12:10:u?10:8,m=(l[2]&16)>>4,p=(l[2]&8)>>3,v=(l[2]&4)>>2,T=l[2]&3;s+="."+d+"."+rt(c)+h+"."+rt(g)+"."+m+"."+p+v+T+"."+rt(1)+"."+rt(1)+"."+rt(1)+"."+0,n=_i("dav1",t)}break}}return{codec:s,encrypted:a,supplemental:n}}function _i(r,e){let t=Q(e,["dvvC"]),i=t.length?t[0]:Q(e,["dvcC"])[0];if(i){let s=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return r+"."+rt(s)+"."+rt(n)}}function kc(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function qs(r,e){let t=e+5;for(;r[e++]&128&&e<t;);return e}function ki(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function rt(r){return(r<10?"0":"")+r}function Dc(r,e){if(!r||!e)return;let t=e.keyId;t?.byteLength===16&&e.isCommonEncryption&&ll(r,(i,s)=>{let n=i.subarray(8,24);n.some(a=>a!==0)||(oe.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Ie(n)} -> ${Ie(t)}`),i.set(t,8))})}function Cc(r){let e=[];return ll(r,t=>e.push(t.subarray(8,24))),e}function ll(r,e){Q(r,["moov","trak"]).forEach(i=>{let s=Q(i,["mdia","minf","stbl","stsd"])[0];if(!s)return;let n=s.subarray(8),a=Q(n,["enca"]),o=a.length>0;o||(a=Q(n,["encv"])),a.forEach(l=>{let d=o?l.subarray(28):l.subarray(78);Q(d,["sinf"]).forEach(h=>{let u=dl(h);u&&e(u,o)})})})}function dl(r){let e=Q(r,["schm"])[0];if(e){let t=et(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let i=Q(r,["schi","tenc"])[0];if(i)return i}}}var Ra;function wc(r){return typeof TextDecoder>"u"?He(r):(Ra||(Ra=new TextDecoder("utf-8"))).decode(r).replace(/\0/g,"")}function Mc(r){let e=r.byteLength,t=[];for(let i=0;i<e;){let s=i+8<=e,n=i+4<=e?r[i]*16777216+(r[i+1]<<16|r[i+2]<<8|r[i+3]):V(r,i),a=n>1?i+n:e;if(s&&r[i+4]===109&&r[i+5]===111&&r[i+6]===111&&r[i+7]===102){let o=Math.min(a,e);for(let l=i+8;l<o;){let d=l+8<=o,c=l+4<=o?r[l]*16777216+(r[l+1]<<16|r[l+2]<<8|r[l+3]):V(r,l),h=c>1?l+c:o;if(d&&r[l+4]===116&&r[l+5]===114&&r[l+6]===97&&r[l+7]===102){let u=Math.min(h,o),f,g,m=[];for(let p=l+8;p<u;){let v=p+8<=u,T=p+4<=u?r[p]*16777216+(r[p+1]<<16|r[p+2]<<8|r[p+3]):V(r,p),E=T>1?p+T:u;if(v&&r[p+4]===116){let S=Math.min(E,u);r[p+5]===102&&r[p+6]===104&&r[p+7]===100?g||(g=r.subarray(p+8,S)):r[p+5]===102&&r[p+6]===100&&r[p+7]===116?f||(f=r.subarray(p+8,S)):r[p+5]===114&&r[p+6]===117&&r[p+7]===110&&m.push(r.subarray(p+8,S))}p=E}t.push({moofOffset:r.byteOffset+i,tfdt:f,tfhd:g,truns:m})}l=h}}i=a}return t}function Oc(r,e,t,i,s=!0){return cl(r,e,i,s)}function Fc(r,e,t,i,s=!1){let n=[],a=e.samples,o=cl(a,t,i,s,{isHEVCFlavor:bi(e.codec),samples:n,timeOffset:r,timescale:e.timescale,trackId:e.id});return{samples:n,sampleData:{includeSampleDetails:s,tracks:o}}}function cl(r,e,t,i,s){let n={},a=!1,o=Mc(r),l=r.byteLength;for(let h=0;h<o.length;h++){let{moofOffset:u,tfdt:f,tfhd:g,truns:m}=o[h],p=V(g,4),v=e[p];if(!v)continue;let T=n[p]||(n[p]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type}),E;if(f){let M=f[0];E=V(f,4),M===1&&(E===nt?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(E*=nt+1,E+=V(f,8))),B(E)&&(!B(T.start)||E<T.start)&&(T.start=E),s&&B(E)&&(s.timeOffset=E/s.timescale)}let S=s?.trackId===p&&v.type===he.VIDEO,b=v.default,A=V(g,0)&16777215,x=b?.duration||0,R,P=b?.sampleSize||0,I=8;A&1&&(I+=8),A&2&&(I+=4),A&8&&(x=V(g,I),R=g.byteOffset-r.byteOffset+I,I+=4),A&16&&(P=V(g,I));let k=0,D=(A&1)!==0,F=!D&&(A&131072)!==0;D?(k=V(g,8),k*=Math.pow(2,32),k+=V(g,12)):F&&(k=u);let G=E||0,$=0,C=x;for(let M=0;M<m.length;M++){let w=m[M],N=V(w,4),K=T.sampleCount;T.sampleCount+=N;let O=w[3]&1,U=0,Z=w[3]&4,j=w[2]&1,ie=w[2]&2,z=w[2]&4,ne=w[2]&8,ee=8;O&&(U=Sn(w,ee),ee+=4),Z&&(!(w[ee+1]&1)&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=K),ee+=4);let ae=k+U;if(!i&&w[1]===0&&w[2]===6&&w[3]===1){var d,c;let ge=G,Ke=ae,tt=ee,q=-1,se=0,re=0,Ae=(d=s?.timeOffset)!=null?d:0,Te=x/((c=s?.timescale)!=null?c:1),Ce=s?.isHEVCFlavor===!0,je=Ce?2:1;for(let Pe=0;Pe<N;Pe++){let we=w[ee]===0?w[ee+1]<<16|w[ee+2]<<8|w[ee+3]:V(w,ee),qe=q===-1&&T.keyFrameIndex===void 0&&(w[ee+5]&1)===0;ee+=8;let $e=ae+we;if(S){if(we>0){let De=ae;do{let gt=r[De]===0?r[De+1]<<16|r[De+2]<<8|r[De+3]:V(r,De);De+=4;let ct=r[De],ze=Ce?ct>>1&63:ct&31;(Ce?ze===39||ze===40:ze===6)&&di(r.subarray(De,De+gt),je,Ae,s.samples),De+=gt}while(De<$e)}Ae+=Te}ae=$e,qe&&(q=Pe,se=ae)}if(ae<=l)re=N;else{let Pe=Ke,we=tt;for(let qe=0;qe<N;qe++){let $e=w[we]===0?w[we+1]<<16|w[we+2]<<8|w[we+3]:V(w,we);if(Pe+=$e,Pe>l)break;re=qe+1,we+=8}}if(S&&(s.timeOffset=Ae),q!==-1&&se<=l&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=q,T.keyFrameStart=ge+q*x),re){(!B(T.ptsMin)||ge<T.ptsMin)&&(T.ptsMin=ge);let Pe=ge+re*x;(!B(T.ptsMax)||Pe>T.ptsMax)&&(T.ptsMax=Pe)}let It=x*N;G=ge+It,$+=It;continue}let be,Fe;i&&(be=[],Fe={sampleOffset:ae,samples:be,defaultSampleDurationOffset:R},ae<=l&&T.trun.push(Fe));let dt;for(let ge=0;ge<N;ge++){let Ke;j?(i&&(Ke=w.byteOffset-r.byteOffset+ee),C=V(w,ee),ee+=4):C=x,ie?(dt=V(w,ee),ee+=4):dt=P;let tt,q;z&&(q=w[ee+1]&1?1:0,i&&(tt={isNonSync:q,dependsOn:(w[ee]&3)===1?1:2}),ee+=4);let se=0;if(ne&&(se=w[0]===0?V(w,ee):Sn(w,ee),ee+=4),S){let re=ae,Ae=0;for(;Ae<dt;){let Te=V(r,re);re+=4,hl(s.isHEVCFlavor,r[re])&&di(r.subarray(re,re+Te),s.isHEVCFlavor?2:1,s.timeOffset+se/s.timescale,s.samples),re+=Te,Ae+=Te+4}s.timeOffset+=C/s.timescale}if(ae+=dt,ae<=l){Fe&&Ke!==void 0&&(Fe.lastSampleDurationOffset=Ke),q===0&&T.keyFrameIndex===void 0&&(T.keyFrameIndex=ge,T.keyFrameStart=G);let re=G+se;(!B(T.ptsMin)||re<T.ptsMin)&&(T.ptsMin=re),(!B(T.ptsMax)||re+C>T.ptsMax)&&(T.ptsMax=re+C),be&&(be[ge]={cts:se,duration:C,flags:tt,size:dt})}G+=C,$+=C}!$&&x&&($+=x*N)}T.duration+=$,T.duration&&(a=!0)}if(!a){let h=1/0,u=0,f=Q(r,["sidx"]);for(let g=0;g<f.length;g++){let m=Pc(f[g]);if(m!=null&&m.references){h=Math.min(h,m.earliestPresentationTime/m.timescale);let p=m.references.reduce((v,T)=>v+T.info.duration||0,0);u=Math.max(u,p+m.earliestPresentationTime/m.timescale)}}u&&B(u)&&Object.keys(n).forEach(g=>{n[g].duration||(n[g].duration=u*n[g].timescale-n[g].start)})}return n}function Nc(r){let e={valid:null,remainder:null},t=Q(r,["moof"]);if(t.length<2)return e.remainder=r,e;let i=t[t.length-1];return e.valid=r.slice(0,i.byteOffset-8),e.remainder=r.slice(i.byteOffset-8),e}function Ye(r,e){let t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Bc(r,e){let t=[],i=e.samples,s=e.timescale,n=e.id,a=!1;return Q(i,["moof"]).map(l=>{let d=l.byteOffset-8;Q(l,["traf"]).map(h=>{let u=Q(h,["tfdt"]).map(f=>{let g=f[0],m=V(f,4);return g===1&&(m*=Math.pow(2,32),m+=V(f,8)),m/s})[0];return u!==void 0&&(r=u),Q(h,["tfhd"]).map(f=>{let g=V(f,4),m=V(f,0)&16777215,p=(m&1)!==0,v=0,T=(m&2)!==0,E=(m&8)!==0,S=0,b=(m&16)!==0,A=0,x=(m&32)!==0,R=!p&&(m&131072)!==0,P=8;g===n&&(p?(v=V(f,P),P+=4,v*=Math.pow(2,32),v+=V(f,P),P+=4):R&&(v=d),T&&(P+=4),E&&(S=V(f,P),P+=4),b&&(A=V(f,P),P+=4),x&&(P+=4),e.type==="video"&&(a=bi(e.codec)),Q(h,["trun"]).map(I=>{let k=I[0],D=V(I,0)&16777215,F=(D&1)!==0,G=0,$=(D&4)!==0,C=(D&256)!==0,M=0,w=(D&512)!==0,N=0,K=(D&1024)!==0,O=(D&2048)!==0,U=0,Z=V(I,4),j=8;F&&(G=V(I,j),j+=4),$&&(j+=4);let ie=v+G;for(let z=0;z<Z;z++){if(C?(M=V(I,j),j+=4):M=S,w?(N=V(I,j),j+=4):N=A,K&&(j+=4),O&&(k===0?U=V(I,j):U=Sn(I,j),j+=4),e.type===he.VIDEO){let ne=0;for(;ne<N;){let ee=V(i,ie);if(ie+=4,hl(a,i[ie])){let ae=i.subarray(ie,ie+ee);di(ae,a?2:1,r+U/s,t)}ie+=ee,ne+=ee+4}}r+=M/s}}))})})}),t}function bi(r){if(!r)return!1;let e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function hl(r,e){if(r){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function di(r,e,t,i){let s=ul(r),n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(l===255);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(l===255);let d=s.length-n,c=n;if(o<d)n+=o;else if(o>d){oe.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(s[c++]===181){let u=nl(s,c);if(c+=2,u===49){let f=V(s,c);if(c+=4,f===1195456820){let g=s[c++];if(g===3){let m=s[c++],p=31&m,v=64&m,T=v?2+p*3:0,E=new Uint8Array(T);if(v){E[0]=m;for(let S=1;S<T;S++)E[S]=s[c++]}i.push({type:g,payloadType:a,pts:t,bytes:E})}}}}}else if(a===5&&o>16){let h=[];for(let g=0;g<16;g++){let m=s[c++].toString(16);h.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&h.push("-")}let u=o-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=s[c++];i.push({payloadType:a,pts:t,uuid:h.join(""),userData:wc(f),userDataBytes:f})}}}function ul(r){let e=r.byteLength,t,i=r.indexOf(3,3);for(;i!==-1;)r[i-1]===0&&r[i-2]===0&&(t||(t=[])).push(i),i=r.indexOf(3,i+1);if(!t)return r;let s=e-t.length,n=new Uint8Array(s),a=0,o=0;for(let l=0;l<s;o++,l++)o===t[a]&&(o++,a++),n[l]=r[o];return n}function $c(r){let e=r[0],t="",i="",s=0,n=0,a,o=0,l=0,d=4;if(e===0){let h=Pi(r,d),u=h!==null?Pi(r,d+h.length):null;h!==null&&u!==null?(t=h,i=u,d+=h.length+u.length,s=V(r,d),d+=4,n=V(r,d),d+=4,o=V(r,d),d+=4,l=V(r,d),d+=4):(oe.warn(`Unterminated ${h===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),d=r.length)}else if(e===1){s=V(r,d),d+=4;let h=V(r,d);d+=4;let u=V(r,d);d+=4,a=2**32*h+u,Yd(a)||(a=Number.MAX_SAFE_INTEGER,oe.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=V(r,d),d+=4,l=V(r,d),d+=4;let f=Pi(r,d),g=f!==null?Pi(r,d+f.length):null;f!==null&&(t=f,d+=f.length),g!==null?(i=g,d+=g.length):(oe.warn(`Unterminated ${f===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${f===null?"strings and payload":"value and payload"}`),d=r.length)}let c=r.subarray(d,r.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function Uc(r,...e){let t=e.length,i=8,s=t;for(;s--;)i+=e[s].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(r,4),s=0,i=8;s<t;s++)n.set(e[s],i),i+=e[s].byteLength;return n}function Gc(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let i,s;i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Uc([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,a,t)}function fl(r){let e=[];if(r instanceof ArrayBuffer){let t=r.byteLength,i=0;for(;i+32<t;){let s=new DataView(r,i),n=Hc(s);e.push(n),i+=n.size}}return e}function Vc(r){let e=[];for(let t=0;t<r.length;){let i=r[t++],s=i&7;if(s===0){for(;r[t++]&128;);continue}if(s!==2){t+=s===1?8:4;continue}let n=0;for(let a=0,o=128;o&128;a+=7)n|=((o=r[t++])&127)<<a;if(i>>3===2)if(n===32){let a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(r[t+o*2],r[t+o*2+1]),16);e.push(a)}else n===16&&e.push(r.subarray(t,t+16));t+=n}return e}function Hc(r){let e=r.getUint32(0),t=r.byteOffset,i=r.byteLength;if(i<e)return{offset:t,size:i};if(r.getUint32(4)!==1886614376)return{offset:t,size:e};let n=r.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=r.buffer,o=Ie(new Uint8Array(a,t+12,16)),l=null,d=null,c=0;if(n===0)c=28;else{let u=r.getUint32(28);if(!u||i<32+u*16)return{offset:t,size:e};l=[];for(let f=0;f<u;f++)l.push(new Uint8Array(a,t+32+f*16,16));c=32+u*16}if(!c)return{offset:t,size:e};let h=r.getUint32(c);return e-32<h?{offset:t,size:e}:(d=new Uint8Array(a,t+c+4,h),n===0&&(l=Vc(d)),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}var Yt=gl("userAgent"),Kc=gl("vendor"),Ws,Ys,js;function gl(r){try{return navigator[r]||""}catch{}return""}function qc(){if(js===void 0){let r=Yt.match(/Safari\/(\d+)/i);js=r?parseInt(r[1]):0}return js}function ei(){if(Ws===void 0){let r=Yt.match(/Chrome\/(\d+)/i);Ws=r?parseInt(r[1]):0}return Ws}function Wc(){if(Ys===void 0){let r=Yt.match(/Firefox\/(\d+)/i);Ys=r?parseInt(r[1]):0}return Ys}function ml(){return/\(Windows.+Firefox\//i.test(Yt)}function Yc(){return Kc.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Yt)}function jc(){return/Android/.test(Yt)}var Kt={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},image:{mjpg:1}};function Kr(r,e){let t=Kt[e];return!!t&&!!t[r.slice(0,4)]}function ci(r,e,t=!0){return!r.split(",").some(i=>!qr(i,e,t))}function qr(r,e,t=!0){var i;let s=bt(t);return(i=s?.isTypeSupported(hi(r,e)))!=null?i:!1}function hi(r,e){return`${e}/mp4;codecs=${r}`}function Pa(r){if(r){let e=r.substring(0,4);return Kt.video[e]}return 2}function Xi(r){let e=ml();return r.split(",").reduce((t,i)=>{let n=e&&bi(i)?9:Kt.video[i];return n?(n*2+t)/(t?3:2):(Kt.audio[i]+t)/(t?2:1)},0)}var zs={};function zc(r,e=!0){if(zs[r])return zs[r];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let s=0;s<t.length;s++){var i;if(qr(t[s],"audio",e))return zs[r]=t[s],t[s];if(t[s]==="mp3"&&(i=bt(e))!=null&&i.isTypeSupported("audio/mpeg"))return""}return r}var Xc=/flac|opus|mp4a\.40\.34/i;function Qi(r,e=!0){return r.replace(Xc,t=>zc(t.toLowerCase(),e))}function Qc(r,e){let t=[];if(r){let i=r.split(",");for(let s=0;s<i.length;s++)Kr(i[s],"video")||t.push(i[s])}return e&&t.push(e),t.join(",")}function Hi(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(_a(r,"audio")||_a(r,"video")))return r;if(e){let t=e.split(",");if(t.length>1){if(r){for(let i=t.length;i--;)if(t[i].substring(0,4)===r.substring(0,4))return t[i]}return t[0]}}return e||r}function _a(r,e){return Kr(r,e)&&qr(r,e)}function Zc(r){let e=r.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Jc(r){if(r.startsWith("av01.")){let e=r.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return r}function ka(r){let e=bt(r)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function An(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var eh={supported:!0,powerEfficient:!0,smooth:!0},th={supported:!1,smooth:!1,powerEfficient:!1},pl={supported:!0,configurations:[],decodingInfoResults:[eh]};function yl(r,e){return{supported:!1,configurations:e,decodingInfoResults:[th],error:r}}function ih(r,e,t,i,s,n){let a=r.videoCodec,o=r.audioCodec?r.audioGroups:null,l=n?.audioCodec,d=n?.channels,c=d?parseInt(d):l?1/0:2,h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=e.groups[o[0]].channels:h=o.reduce((u,f)=>{if(f){let g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(m=>{u[m]=(u[m]||0)+g.channels[m]})}return u},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(u=>bi(u))||r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(i,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(s,8e6))||!!h&&B(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function vl(r,e,t,i={}){let s=r.videoCodec;if(!s&&!r.audioCodec||!t)return Promise.resolve(pl);let n=[],a=sh(r),o=a.length,l=nh(r,e,o>0),d=l.length;for(let c=o||1*d||1;c--;){let h={type:"media-source"};if(o&&(h.video=a[c%o]),d){h.audio=l[c%d];let u=h.audio.bitrate;h.video&&u&&(h.video.bitrate-=u)}n.push(h)}if(s){let c=navigator.userAgent;if(s.split(",").some(h=>bi(h))&&ml())return Promise.resolve(yl(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{let h=rh(c);return i[h]||(i[h]=t.decodingInfo(c))})).then(c=>({supported:!c.some(h=>!h.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:!1,configurations:n,decodingInfoResults:[],error:c}))}function sh(r){var e;let t=(e=r.videoCodec)==null?void 0:e.split(","),i=Tl(r),s=r.width||640,n=r.height||480,a=r.frameRate||30,o=r.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:hi(Jc(l),"video"),width:s,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function nh(r,e,t){var i;let s=(i=r.audioCodec)==null?void 0:i.split(","),n=Tl(r);return s&&r.audioGroups?r.audioGroups.reduce((a,o)=>{var l;let d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((c,h)=>{if(h.groupId===o){let u=parseFloat(h.channels||"");s.forEach(f=>{let g={contentType:hi(f,"audio"),bitrate:t?El(f,n):n};u&&(g.channels=""+u),c.push(g)})}return c},a):a},[]):[]}function El(r,e){if(e<=1)return 1;let t=128e3;return r==="ec-3"?t=768e3:r==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Tl(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function rh(r){let e="",{audio:t,video:i}=r;if(i){let s=An(i.contentType);e+=`${s}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(t){let s=An(t.contentType);e+=`${i?"_":""}${s}_c${t.channels}`}return e}function Tt(r,e,t){let i=encodeURIComponent(e),s=`${i}=${encodeURIComponent(t)}`,n=!1,a=[];r.search.substring(1).split("&").forEach(o=>{o===i||o.startsWith(i+"=")?n||(a.push(s),n=!0):o&&a.push(o)}),n||a.push(s),r.search=a.join("&")}var xn=["NONE","TYPE-0","TYPE-1",null];function ah(r){return xn.indexOf(r)>-1}var Zi=["SDR","PQ","HLG"];function oh(r){return!!r&&Zi.indexOf(r)>-1}var Ki={No:"",Yes:"YES",v2:"v2"};function Da(r){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=r,s=i<e/2;return e&&s?t?Ki.v2:Ki.Yes:Ki.No}var Ji=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&Tt(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&Tt(t,"_HLS_part",this.part.toString()),this.skip&&Tt(t,"_HLS_skip",this.skip),t.href}},Ct=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Ca(this._audioGroups,e)}hasSubtitleGroup(e){return Ca(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Ca(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function lh(){if(typeof matchMedia=="function"){let r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function dh(r,e){let t=!1,i=[];if(r&&(t=r!=="SDR",i=[r]),e){i=e.allowedVideoRanges||Zi.slice(0);let s=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:s&&lh(),t||(i=["SDR"])}return{preferHDR:t,allowedVideoRanges:i}}var ch=r=>{let e=new WeakSet;return(t,i)=>{if(r&&(i=r(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i}},fe=(r,e)=>JSON.stringify(r,ch(e));function hh(r,e,t,i,s){let n=Object.keys(r),a=i?.channels,o=i?.audioCodec,l=s?.videoCodec,d=a&&parseInt(a)===2,c=!1,h=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,v=[],{preferHDR:T,allowedVideoRanges:E}=dh(e,s);for(let R=n.length;R--;){let P=r[n[R]];c||(c=P.channels[2]>0),u=Math.min(u,P.minHeight),f=Math.min(f,P.minFramerate),g=Math.min(g,P.minBitrate),E.filter(k=>P.videoRanges[k]>0).length>0&&(h=!0)}u=B(u)?u:0,f=B(f)?f:0;let S=Math.max(1080,u),b=Math.max(30,f);g=B(g)?g:t,t=Math.max(g,t),h||(e=void 0);let A=n.length>1;return{codecSet:n.reduce((R,P)=>{let I=r[P];if(P===R)return R;if(v=h?E.filter(k=>I.videoRanges[k]>0):[],A){if(I.minBitrate>t)return it(P,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),R;if(!I.hasDefaultAudio)return it(P,"no renditions with default or auto-select sound found"),R;if(o&&P.indexOf(o.substring(0,4))%5!==0)return it(P,`audio codec preference "${o}" not found`),R;if(a&&!d){if(!I.channels[a])return it(P,`no renditions with ${a} channel sound found (channels options: ${Object.keys(I.channels)})`),R}else if((!o||d)&&c&&I.channels[2]===0)return it(P,"no renditions with stereo sound found"),R;if(I.minHeight>S)return it(P,`min resolution of ${I.minHeight} > maximum of ${S}`),R;if(I.minFramerate>b)return it(P,`min framerate of ${I.minFramerate} > maximum of ${b}`),R;if(!v.some(k=>I.videoRanges[k]>0))return it(P,`no variants with VIDEO-RANGE of ${fe(v)} found`),R;if(l&&P.indexOf(l.substring(0,4))%5!==0)return it(P,`video codec preference "${l}" not found`),R;if(I.maxScore<p)return it(P,`max score of ${I.maxScore} < selected max of ${p}`),R}return R&&(Xi(P)>=Xi(R)||I.fragmentError>r[R].fragmentError)?R:(m=I.minIndex,p=I.maxScore,P)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:m}}function it(r,e){oe.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function Sl(r){return r.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function uh(r,e,t,i){return r.slice(t,i+1).reduce((s,n,a)=>{if(!n.codecSet)return s;let o=n.audioGroups,l=s[n.codecSet];l||(s[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;let h=e.groups[c];h&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{l.channels[u]=(l.channels[u]||0)+h.channels[u]}))}),s},{})}function wa(r){if(!r)return r;let{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}=r;return{lang:e,assocLang:t,characteristics:i,channels:s,audioCodec:n}}function ot(r,e,t){if("attrs"in r){let i=e.indexOf(r);if(i!==-1)return i}for(let i=0;i<e.length;i++){let s=e[i];if(kt(r,s,t))return i}return-1}function kt(r,e,t){let{groupId:i,name:s,lang:n,assocLang:a,default:o}=r,l=r.forced;return(i===void 0||e.groupId===i)&&(s===void 0||e.name===s)&&(n===void 0||fh(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in r)||gh(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function fh(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function gh(r,e=""){let t=r.split(","),i=e.split(",");return t.length===i.length&&!t.some(s=>i.indexOf(s)===-1)}function _t(r,e){let{audioCodec:t,channels:i}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function mh(r,e,t,i,s){let n=e[i],o=e.reduce((u,f,g)=>{let m=f.uri;return(u[m]||(u[m]=[])).push(g),u},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));let l=n.videoRange,d=n.frameRate,c=n.codecSet.substring(0,4),h=Ma(e,i,u=>{if(u.videoRange!==l||u.frameRate!==d||u.codecSet.substring(0,4)!==c)return!1;let f=u.audioGroups,g=t.filter(m=>ui(m.groupId,f));return ot(r,g,s)>-1});return h>-1?h:Ma(e,i,u=>{let f=u.audioGroups,g=t.filter(m=>ui(m.groupId,f));return ot(r,g,s)>-1})}function Ma(r,e,t){for(let i=e;i>-1;i--)if(t(r[i]))return i;for(let i=e+1;i<r.length;i++)if(t(r[i]))return i;return-1}function es(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}function ui(r,e){return e?e.indexOf(r)!==-1:!0}function bl(r,e){if(e||r){let t=ce({},e);return r&&(r.videoCodec&&(t.videoCodec=r.videoCodec),r.videoRange&&(t.allowedVideoRanges=[r.videoRange])),t}}var In=class extends Oe{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-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.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;let{fragCurrent:s,partCurrent:n,hls:a}=this;if(!a)return;let{autoLevelEnabled:o,media:l}=a;if(!s||!l)return;let d=performance.now(),c=n?n.stats:s.stats,h=n?n.duration:s.duration,u=d-c.loading.start,f=a.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let p=m>-1&&m!==g,v=!!t||p;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let T=a.mainForwardBufferInfo;if(!v&&T===null)return;let E=this.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(u<=Math.max(E,1e3*(h/(S*2))))return;let b=T?T.len/S:0,A=c.loading.first?c.loading.first-c.loading.start:-1,x=c.loaded&&A>-1,R=this.getBwEstimate(),P=a.levels,I=P[g],k=Math.max(c.loaded,Math.round(h*(s.bitrate||I.averageBitrate)/8)),D=x?u-A:u;D<1&&x&&(D=Math.min(u,c.loaded*8/R));let F=x?c.loaded*1e3/D:0,G=E/1e3,$=F?(k-c.loaded)/F:k*8/R+G;if($<=b)return;let C=F?F*8:R,M=((i=t?.details||a.latestLevelDetails)==null?void 0:i.live)===!0,w=a.config.abrBandWidthUpFactor,N=Number.POSITIVE_INFINITY,K;for(K=g-1;K>f;K--){let j=P[K].maxBitrate,ie=!P[K].details||M;if(N=this.getTimeToLoadFrag(G,C,h*j,ie),N<Math.min(b,h+G))break}if(N>=$||N>h*10)return;x?this.bwEstimator.sample(u-Math.min(E,A),c.loaded):this.bwEstimator.sampleTTFB(u);let O=P[K].maxBitrate;this.getBwEstimate()*w>O&&(this.firstAutoFloor=Math.min(K,a.firstLevel),this.resetEstimator(O));let U=this.findBestLevel(O,f,K,0,b,1,1);U>-1&&(K=U),this.warn(`Fragment ${s.sn}${n?" part "+n.index:""} of level ${g} is loading too slowly;
2
2
  Fragment duration: ${s.duration.toFixed(3)}
3
3
  Time to underbuffer: ${b.toFixed(3)} s
4
4
  Estimated load time for current fragment: ${$.toFixed(3)} s
@@ -8,45 +8,45 @@ var B=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},Kd=Nu
8
8
  New BW estimate: ${this.getBwEstimate()|0} bps
9
9
  Switching to level ${K} @ ${O|0} bps`),a.nextLoadLevel=a.nextAutoLevel=K,this.clearTimer();let Z=()=>{this.clearTimer();let j=this.hls;if(this.fragCurrent===s&&j.loadLevel===K&&K>0){let ie=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${K>0?"and switching down":""}
10
10
  Fragment duration: ${s.duration.toFixed(3)} s
11
- Time to underbuffer: ${ie.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,K>f){let z=this.findBestLevel(j.levels[f].bitrate,f,K,0,ie,1,1);z===-1&&(z=f),j.nextLoadLevel=j.nextAutoLevel=z,this.firstAutoFloor=Math.min(z,j.firstLevel),this.resetEstimator(j.levels[z].bitrate)}}};p||$>N*2?Z():this.timer=self.setInterval(Z,N*1e3),a.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:c})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){let e=this.hls.config;return new pn(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:s,partCurrent:n}=this;if(i&&gn(i,s)){let a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){let h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(h,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,s){let n=e+i/t,a=s?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let i=this.hls.config,{loading:s}=t.stats,n=s.end-s.first;B(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var i;let{frag:s,part:n}=t,a=n?n.stats:s.stats;if(s.type===H.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(s)){if(this.clearTimer(),s.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(i=this.hls)!=null&&i.config.abrMaxWithRealBitrate){let o=n?n.duration:s.duration,l=this.hls.levels[s.level],d=(l.loaded?l.loaded.bytes:0)+a.loaded,c=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:d,duration:c},l.realBitrate=Math.round(8*d/c)}if(s.bitrateTest){let o={stats:a,frag:s,part:n,id:s.type};this.onFragBuffered(y.FRAG_BUFFERED,o),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}}onFragBuffered(e,t){let{frag:i,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let o=((i.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==H.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{hls:e}=this;if(!e)return 0;let{maxAutoLevel:t,minAutoLevel:i}=e,s=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(s,i,t,n/2,a,1,1);if(o>-1)return o;let l=e.firstLevel,d=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,c=Math.min(Math.max(l,i),t,d);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${c}`),c}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:s,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),c=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(d){let p=this.findBestLevel(l,a,s,d,0,c,h);if(p>=0)return this.rebufferNotice=-1,p}let u=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){let p=this.bitrateTestDelay;p&&(u=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),c=h=1)}let f=this.findBestLevel(l,a,s,d,u,c,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let g=i.levels[a],m=i.loadLevelObj;return m&&g?.bitrate<m.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e?.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,i,s,n,a,o){let{hls:l,lastLoadedFragLevel:d,fragCurrent:c,partCurrent:h}=this;if(!l)return-1;let u=s+n,f=d===-1?l.firstLevel:d,{levels:g,allAudioTracks:m,loadLevel:p,latestLevelDetails:v,config:T}=l;if(g.length===1)return 0;let E=g[f],S=!!(v!=null&&v.live),b=p===-1||d===-1,A,x="SDR",R=E?.frameRate||0,{audioPreference:P,videoPreference:I}=T,k=this.audioTracksByGroup||(this.audioTracksByGroup=vl(m)),D=-1;if(b){if(this.firstSelection!==-1)return this.firstSelection;let M=this.codecTiers||(this.codecTiers=dh(g,k,t,i)),w=lh(M,x,e,P,I),{codecSet:N,videoRanges:K,minFramerate:O,minBitrate:U,minIndex:Z,preferHDR:j}=w;D=Z,A=N,x=j?K[K.length-1]:K[0],R=O,e=Math.max(e,U),this.log(`picked start tier ${fe(w)}`)}else A=E?.codecSet,x=E?.videoRange;let F=h?h.duration:c?c.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,$=[];for(let M=i;M>=t;M--){var C;let w=g[M],N=M>f;if(!w)continue;if(T.useMediaCapabilities&&!w.supportedResult&&!w.supportedPromise){let z=navigator.mediaCapabilities;typeof z?.decodingInfo=="function"&&Jc(w,k,x,R,e,P)?(w.supportedPromise=ml(w,k,z,this.supportedCache),w.supportedPromise.then(ne=>{if(!this.hls)return;w.supportedResult=ne;let ee=this.hls.levels,ae=ee.indexOf(w);ne.error?this.warn(`MediaCapabilities decodingInfo error: "${ne.error}" for level ${ae} ${fe(ne)}`):ne.supported?ne.decodingInfoResults.some(be=>be.smooth===!1||be.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ae} not smooth or powerEfficient: ${fe(ne)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ae} ${fe(ne)}`),ae>-1&&ee.length>1&&(this.log(`Removing unsupported level ${ae}`),this.hls.removeLevel(ae),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ne=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ne}`)})):w.supportedResult=fl}if((A&&w.codecSet!==A||x&&w.videoRange!==x||N&&R>w.frameRate||!N&&R>0&&R<w.frameRate||(C=w.supportedResult)!=null&&(C=C.decodingInfoResults)!=null&&C.some(z=>z.smooth===!1))&&(!b||M!==D)){$.push(M);continue}let K=w.details,O=(h?K?.partTarget:K?.averagetargetduration)||F||1,U;N?U=o*e:U=a*e;let Z=F&&s>=F*2&&n===0?w.averageBitrate:w.maxBitrate,j=this.getTimeToLoadFrag(G,U,Z*O,!K||K.live);if(U>=Z&&(M===d||w.loadError===0&&w.fragmentError===0||Wo(w,T.errorPenaltyExpireMs))&&(j<=G||!B(j)||S&&!this.bitrateTestDelay||j<u)){let z=this.forcedAutoLevel;return M!==p&&(z===-1||z!==p)&&($.length&&this.trace(`Skipped level(s) ${$.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[$[0]].codecs}" ${g[$[0]].videoRange}; not compatible with "${A}" ${x}`),this.info(`switch candidate:${f}->${M} adjustedbw(${Math.round(U)})-bitrate=${Math.round(U-Z)} ttfb:${G.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${b} codecSet:${w.codecSet} videoRange:${w.videoRange} hls.loadLevel:${p}`)),b&&(this.firstSelection=M),M}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},Tl={search:function(r,e){let t=0,i=r.length-1,s=null,n=null;for(;t<=i;){s=(t+i)/2|0,n=r[s];let a=e(n);if(a>0)t=s+1;else if(a<0)i=s-1;else return n}return null}};function fh(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!B(e))return null;let i=r[0].programDateTime;if(e<(i||0))return null;let s=r[r.length-1].endProgramDateTime;if(e>=(s||0))return null;for(let n=0;n<r.length;++n){let a=r[n];if(mh(e,t,a))return a}return null}function qt(r,e,t=0,i=0,s=.005){let n=null;if(r){n=e[1+r.sn-e[0].sn]||null;let o=r.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&r.level!==n.level&&n.end<=r.end&&(n=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!r||r.level===n.level)&&Ca(t,i,n)===0||gh(n,r,Math.min(s,i))))return n;let a=Tl.search(e,Ca.bind(null,t,i));return a&&(a!==r||!n)?a:n}function gh(r,e,t){if(e?.start===0&&e.level<r.level&&(e.endPTS||0)>0){let i=e.tagList.reduce((s,n)=>(n[0]==="INF"&&(s+=parseFloat(n[1])),s),t);return r.start<=i}return!1}function Ca(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function mh(r,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function Sl(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){let i=r.fragments,{fragmentHint:s}=r;s&&(i=i.concat(s));let n;return Tl.search(i,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function bl(r,e){return e===r.endSN&&r.fragmentHint?r.fragmentHint:r.fragments[1+e-r.startSN]||null}var Re={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Le={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},xn=class extends Oe{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.ERROR,this.onError,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(y.ERROR,this.onError,this),e.off(y.ERROR,this.onErrorOut,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===H.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;let s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(a=>s.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;let s=this.hls,n=t.context;switch(t.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case L.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=ti();return}case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Re.SendAlternateToPenaltyBox;return}case L.PLAYLIST_UNCHANGED_ERROR:case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var a;let o=t.parent===H.MAIN?t.level:s.loadLevel;t.details===L.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let o=s.loadLevelObj;if(o&&(n.type===te.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===te.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Re.SendAlternateToPenaltyBox,t.errorAction.flags=Le.MoveAllAlternatesMatchingHost;return}}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingHDCP};return;case L.KEY_SYSTEM_SESSION_UPDATE_FAILED:case L.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case L.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingKey};return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case L.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=Le.ResetMediaSource|Le.SwitchToSDR;return;case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_APPEND_NO_PROGRESS:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:t.errorAction=ti();return}t.type===W.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ti())}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,s=va(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(ai(s,n,zi(e),e.response))return{action:Re.RetryRequest,flags:Le.None,retryConfig:s,retryCount:n};let o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=va(Ko(e)?a:n,e),l=t.levels.reduce((c,h)=>c+h.fragmentError,0);if(s&&(e.details!==L.FRAG_GAP&&s.fragmentError++,!qo(e)&&ai(o,l,zi(e),e.response)))return{action:Re.RetryRequest,flags:Le.None,retryConfig:o,retryCount:l};let d=this.getLevelSwitchAction(e,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let s=this.hls.levels[t];if(s){var n,a;let d=e.details;s.loadError++,s.loadErrorTime=self.performance.now(),d===L.BUFFER_APPEND_ERROR&&s.fragmentError++;let c=-1,{levels:h,loadLevel:u,minAutoLevel:f,maxAutoLevel:g}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);let m=(n=e.frag)==null?void 0:n.type,v=(m===H.AUDIO&&d===L.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&wa(e))&&h.some(({audioCodec:A})=>s.audioCodec!==A),E=e.sourceBufferName==="video"&&wa(e)&&h.some(({codecSet:A,audioCodec:x})=>s.codecSet!==A&&s.audioCodec===x),{type:S,groupId:b}=(a=e.context)!=null?a:{};for(let A=h.length;A--;){let x=(A+u)%h.length;if(x!==u&&x>=f&&x<=g&&(h[x].loadError===0||Wo(h[x],i.config.errorPenaltyExpireMs))){var o,l;let R=h[x];if(d===L.FRAG_GAP&&m===H.MAIN&&e.frag){let P=h[x].details;if(P){let I=qt(e.frag,P.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(S===te.AUDIO_TRACK&&R.hasAudioGroup(b)||S===te.SUBTITLE_TRACK&&R.hasSubtitleGroup(b))continue;if(m===H.AUDIO&&(o=s.audioGroups)!=null&&o.some(P=>R.hasAudioGroup(P))||m===H.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(P=>R.hasSubtitleGroup(P))||v&&s.audioCodec===R.audioCodec||E&&s.codecSet===R.codecSet||!v&&s.audioCodec!==R.audioCodec)continue}c=x;break}}if(c>-1&&i.loadLevel!==c)return e.levelRetry=!0,this.playlistError=0,{action:Re.SendAlternateToPenaltyBox,flags:Le.None,nextAutoLevel:c}}return{action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i,s;switch((i=t.errorAction)==null?void 0:i.action){case Re.DoNothing:break;case Re.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==L.FRAG_GAP&&t.details!==L.PLAYLIST_UNCHANGED_ERROR&&!Al(t)&&(t.fatal=!0);break;case Re.RetryRequest:break}if((((s=t.errorAction)==null?void 0:s.flags)||0)&Le.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let s=i.nextAutoLevel;if(i.flags===Le.None)this.switchLevel(e,s);else if(i.flags&Le.SwitchToSDR){let o=this.hls.levels,l=o.length;for(let d=l;d--;)o[d].videoRange!=="SDR"?(o[d].fragmentError++,o[d].loadError++):s===void 0&&(s=d)}else if(i.flags&Le.MoveAllAlternatesMatchingHDCP){let o=this.getVariantLevelIndex(e.frag),l=t.levels[o],d=l?.attrs["HDCP-LEVEL"];i.hdcpLevel=d;let c=d==="NONE";d&&!c?(t.maxHdcpLevel=bn[bn.indexOf(d)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(c&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=Le.MoveAllAlternatesMatchingKey)}if(i.flags&Le.MoveAllAlternatesMatchingKey){let o=e.decryptdata;if(o){let l=this.hls.levels,d=l.length;for(let h=d;h--;)if(this.variantHasKey(l[h],o)){var n,a;this.log(`Banned key found in level ${h} (${l[h].bitrate}bps) or audio group "${(n=l[h].audioGroups)==null?void 0:n.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${Ie(o.keyId||[])}`),l[h].fragmentError++,l[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}let c=e.frag;if(this.hls.levels.length<d)i.resolved=!0;else if(c&&c.type!==H.MAIN){let h=c.decryptdata;h&&!o.matches(h)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===L.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let i=Sn(e.mimeType),s=this.hls.levels;for(let n=s.length;n--;)s[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n))}}};function wa(r){let e=r.details;return e===L.BUFFER_ADD_CODEC_ERROR||e===L.MEDIA_SOURCE_REQUIRES_RESET||e===L.BUFFER_APPEND_ERROR&&!Al(r)}function Al(r){return r.details===L.BUFFER_APPEND_ERROR&&(r.error.name==="QuotaExceededError"||r.error.name==="InvalidStateError")}function ti(r){let e={action:Re.DoNothing,flags:Le.None};return r&&(e.resolved=!0),e}var ye={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},In=class{constructor(e){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=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e&&(e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let s=i.length;s--;){let n=i[s];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){let{fragments:s}=this,n=Object.keys(s);for(let a=n.length;a--;){let o=s[n[a]];if(o?.body.type===t&&(!i||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,s,n,a){this.timeRanges&&(this.timeRanges[e]=t);let o=n?.fragment.sn||-1;Object.keys(this.fragments).forEach(l=>{let d=this.fragments[l];if(!d||!this.hls)return;let c=d.body;if(o>=c.sn)return;if(!d.buffered&&(!d.loaded||a)){c.type===i&&this.removeFragment(c);return}let h=d.range[e];if(h){if(h.time.length===0){this.removeFragment(c);return}if(h.time.some(u=>{let f=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return f&&this.removeFragment(c),f}),s&&s!==c&&ei()){let u=s.endPTS,f=c.startPTS;if(u&&f&&d.range.video){let g=f-u;g<0&&g>-.1&&(this.removeFragment(c),this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:u+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:i,part:s,id:n}=e;if(!t||!ve(i))return;let a=Ft(i),o=this.fragments[a];if(!o||o.buffered&&i.gap)return;let l=!i.relurl;Object.keys(t).forEach(c=>{let h=i.elementaryStreams[c];if(!h)return;let u=t[c],f=l||h.partial===!0;o.range[c]=this.getBufferedTimes(i,s,f,u),this.detectEvictedFragments(c,u,n,i,s)}),o.loaded=null;let d=Object.keys(o.range);if(d.length){if(this.bufferedEnd(o,i),Di(o)||this.removeParts(i.sn-1,i.type),!s){let c=Math.min(.004,i.duration);d.some(h=>{var u;let f=(u=o.range[h])==null?void 0:u.time,g=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<c;return g&&this.addAsGap(i),g})}}else this.removeFragment(i)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=Ma(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){let i=Ft(e),s=this.fragments[i];return!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e)),s}getBufferedTimes(e,t,i,s){let n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let c=0;c<s.length;c++){let h=s.start(c)-this.bufferPadding,u=s.end(c)+this.bufferPadding;if(d>=h&&l<=u){n.time.push({startPTS:Math.max(a,s.start(c)),endPTS:Math.min(o,s.end(c))});break}else if(a<u&&o>h){let f=Math.max(a,s.start(c)),g=Math.min(o,s.end(c));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,i,s,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{let c=l[d];c&&Di(c)&&(s=c.body.start-o,n=c.body.end+o,e>=s&&e<=n&&(i=Math.min(e-s,n-e),a<=i&&(t=c.body,a=i)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Di(t))}getState(e){let t=Ft(e),i=this.fragments[t];return i?i.buffered?Di(i)?ye.PARTIAL:ye.OK:ye.APPENDING:ye.NOT_LOADED}isTimeBuffered(e,t,i){let s,n;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=s&&t<=n)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!ve(t.frag)||t.frag.bitrateTest)return;let i=t.frag,s=t.part?null:t,n=Ft(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:s,timeRanges:n}=t;if(!ve(i))return;let a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=n}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Ft(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){let n=t[i[s]];if(n?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,i){let{fragments:s}=this,n=0,a=0,o=Object.keys(s);for(let l=0;l<o.length;l++){let d=s[o[l]];if(!d||!d.buffered||d.body.type!==t)continue;let c=d.body;if(c.gap)return 0;let h=c.hasStats&&c.stats.loaded||c.byteLength||c.bitrate&&c.bitrate*8*c.duration;if(c.end<=e&&h&&(n+=h,a=Math.max(a,c.end),n>=i))return a}return a>0?a:0}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=Ft(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let s=e.sn;this.activePartLists[e.type]=Ma(i,n=>n.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}};function Di(r){var e,t,i,s;return r.buffered&&!!(r.body.gap||(e=r.range.video)!=null&&e.partial||(t=r.range.audio)!=null&&t.partial||(i=r.range.audiovideo)!=null&&i.partial||(s=r.range.subs)!=null&&s.partial)}function Ft(r){return`${r.type}_${r.level}_${r.sn}`}function Ma(r,e){return r.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var At={cbc:0,ctr:1},Ln=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case At.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case At.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function ph(r){let e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}var Rn=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,d=l[0],c=l[1],h=l[2],u=l[3],f=new Uint32Array(256),g=0,m=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let v=m^m<<1^m<<2^m<<3^m<<4;v=v>>>8^v&255^99,e[g]=v,t[v]=g;let T=f[g],E=f[T],S=f[E],b=f[v]*257^v*16843008;s[g]=b<<24|b>>>8,n[g]=b<<16|b>>>16,a[g]=b<<8|b>>>24,o[g]=b,b=S*16843009^E*65537^T*257^g*16843008,d[v]=b<<24|b>>>8,c[v]=b<<16|b>>>16,h[v]=b<<8|b>>>24,u[v]=b,g?(g=T^f[f[f[S^T]]],m^=f[f[m]]):g=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,l,d=this.keySchedule=new Uint32Array(a),c=this.invKeySchedule=new Uint32Array(a),h=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],m=f[1],p=f[2],v=f[3],T,E;for(o=0;o<a;o++){if(o<n){T=d[o]=t[o];continue}E=T,o%n===0?(E=E<<8|E>>>24,E=h[E>>>24]<<24|h[E>>>16&255]<<16|h[E>>>8&255]<<8|h[E&255],E^=u[o/n|0]<<24):n>6&&o%n===4&&(E=h[E>>>24]<<24|h[E>>>16&255]<<16|h[E>>>8&255]<<8|h[E&255]),d[o]=T=(d[o-n]^E)>>>0}for(l=0;l<a;l++)o=a-l,l&3?E=d[o]:E=d[o-4],l<4||o<=4?c[l]=E:c[l]=g[h[E>>>24]]^m[h[E>>>16&255]]^p[h[E>>>8&255]]^v[h[E&255]],c[l]=c[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){let s=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],c=o[2],h=o[3],u=this.uint8ArrayToUint32Array_(i),f=u[0],g=u[1],m=u[2],p=u[3],v=new Int32Array(e),T=new Int32Array(v.length),E,S,b,A,x,R,P,I,k,D,F,G,$,C,M=this.networkToHostOrderSwap;for(;t<v.length;){for(k=M(v[t]),D=M(v[t+1]),F=M(v[t+2]),G=M(v[t+3]),x=k^n[0],R=G^n[1],P=F^n[2],I=D^n[3],$=4,C=1;C<s;C++)E=l[x>>>24]^d[R>>16&255]^c[P>>8&255]^h[I&255]^n[$],S=l[R>>>24]^d[P>>16&255]^c[I>>8&255]^h[x&255]^n[$+1],b=l[P>>>24]^d[I>>16&255]^c[x>>8&255]^h[R&255]^n[$+2],A=l[I>>>24]^d[x>>16&255]^c[R>>8&255]^h[P&255]^n[$+3],x=E,R=S,P=b,I=A,$=$+4;E=a[x>>>24]<<24^a[R>>16&255]<<16^a[P>>8&255]<<8^a[I&255]^n[$],S=a[R>>>24]<<24^a[P>>16&255]<<16^a[I>>8&255]<<8^a[x&255]^n[$+1],b=a[P>>>24]<<24^a[I>>16&255]<<16^a[x>>8&255]<<8^a[R&255]^n[$+2],A=a[I>>>24]<<24^a[x>>16&255]<<16^a[R>>8&255]<<8^a[P&255]^n[$+3],T[t]=M(E^f),T[t+1]=M(A^g),T[t+2]=M(b^m),T[t+3]=M(S^p),f=k,g=D,m=F,p=G,t=t+4}return T.buffer}},Pn=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){let e=yh(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function yh(r){switch(r){case At.cbc:return"AES-CBC";case At.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}var vh=16,fi=class{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,t!==!0)try{let i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);this.reset();let s=this.decryptRange;return s?s.start===0&&s.end>=i.length?i:i.slice(s.start,s.end):ph(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s,n){return this.decryptRange=n,this.useSoftware||n?new Promise((a,o)=>{let l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,i,s);let d=this.flush();d?a(d.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){let{currentIV:n,currentResult:a,remainderData:o}=this;if(s!==At.cbc||t.byteLength!==16)return oe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ye(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(i=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Rn),d.expandKey(t);let c=a;return this.currentResult=d.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,c||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new Pn(this.subtle,t,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Ln(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(oe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%vh;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(oe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Oa=Math.pow(2,17),ts=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,i,s){let n=e.url;if(!n)return Promise.reject(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();let a=this.config,o=a.fLoader,l=a.loader;return new Promise((d,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){c(Na(e));return}else e.gap=!1;let h=this.loader=o?new o(a):new l(a),u=Fa(e,null,t);e.loader=h;let f=Ea(a.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Oa};h.stats.retry=e.stats.retry,e.stats=h.stats;let m={onSuccess:(p,v,T,E)=>{this.resetLoader(e,h);let S=p.data;T.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(S.slice(0,16)),S=S.slice(16)),d({frag:e,part:null,payload:S,networkDetails:E})},onError:(p,v,T,E)=>{this.resetLoader(e,h),c(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Y({url:n,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:T,stats:E}))},onAbort:(p,v,T)=>{this.resetLoader(e,h),c(new We({type:W.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:T,stats:p}))},onTimeout:(p,v,T)=>{this.resetLoader(e,h),c(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:T,stats:p}))}};if(i){let p=this.gateProgress(i,s);m.onProgress=(v,T,E,S)=>p({frag:e,part:null,payload:E,networkDetails:S})}h.load(u,g,m)})}gateProgress(e,t){let i=e;if(t){let s=[],n=!1;t.then(()=>{n=!0,s.forEach(a=>e(a)),s.length=0}).catch(()=>{}),i=a=>{n?e(a):s.push(a)}}return i}loadPart(e,t,i){this.abort();let s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Na(e,t));return}let d=this.loader=n?new n(s):new a(s),c=Fa(e,t);e.loader=d;let h=Ea(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Oa};t.stats=d.stats,d.load(c,u,{onSuccess:(f,g,m,p)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:p};i(v),o(v)},onError:(f,g,m,p)=>{this.resetLoader(e,d),l(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Y({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:p}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new We({type:W.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,d),l(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){let i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/n),l),h=(l-d)*Math.round(i.loaded/d);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);let a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Fa(r,e=null,t){let i=e||r,s={type:te.MEDIA_FRAGMENT,frag:r,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=is(r,e,t);return n.resetIV&&(s.resetIV=!0),n.byteRange&&(s.rangeStart=n.byteRange.start,s.rangeEnd=n.byteRange.end),s}function is(r,e=null,t){let i={},s=e||r,n=s.byteRangeStartOffset,a=s.byteRangeEndOffset;if(B(n)&&B(a)){var o;if((r.sn==="initSegment"||t)&&Eh((o=r.decryptdata)==null?void 0:o.method)){let l=Math.floor(n/16)*16,d=Math.ceil(a/16)*16;i.decryptRange={start:n-l,end:a-l},l>=16&&(i.resetIV=!0,l=l-16),i.byteRange={start:l,end:d}}else i.byteRange={start:n,end:a}}return i}function Na(r,e){let t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:W.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new We(i)}function Eh(r){return r==="AES-128"||r==="AES-256"}var We=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},ss=class extends Oe{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},gi=class{constructor(e,t,i,s=0,n=-1,a=!1,o,l,d){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.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=Ci(),this.buffering={audio:Ci(),video:Ci(),audiovideo:Ci()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=a,this.duration=o||0,this.decryptRange=d,this.iframe=l||!1}};function Ci(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Ba={length:0,start:()=>0,end:()=>0},J=class r{static isBuffered(e,t){if(e){let i=r.getBuffered(e);for(let s=i.length;s--;)if(t>=i.start(s)&&t<=i.end(s))return!0}return!1}static bufferedRanges(e){if(e){let t=r.getBuffered(e);return r.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let s=r.bufferedRanges(e);if(s.length)return r.bufferedInfo(s,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((c,h)=>c.start-h.start||h.end-c.end);let s=-1,n=[];if(i)for(let c=0;c<e.length;c++){t>=e[c].start&&t<=e[c].end&&(s=c);let h=n.length;if(h){let u=n[h-1].end;e[c].start-u<i?e[c].end>u&&(n[h-1].end=e[c].end):n.push(e[c])}else n.push(e[c])}else n=e;let a=0,o,l=t,d=t;for(let c=0;c<n.length;c++){let h=n[c].start,u=n[c].end;if(s===-1&&t>=h&&t<=u&&(s=c),t+i>=h&&t<u)l=h,d=u,a=d-t;else if(t+i<h){o=h;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||Ba}catch(t){return oe.log("failed to get media.buffered",t),Ba}}},xl=/\{\$([a-zA-Z0-9-_]+)\}/g;function $a(r){return xl.test(r)}function Kr(r,e){if(r.variableList!==null||r.hasVariableRefs){let t=r.variableList;return e.replace(xl,i=>{let s=i.substring(2,i.length-1),n=t?.[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return e}function Ua(r,e,t){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(s))n=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,n=e.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function Th(r,e,t){let i=e.IMPORT;if(t&&i in t){let s=r.variableList;s||(r.variableList=s={}),s[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}var Sh=/^(\d+)x(\d+)$/,Ga=/(.+?)=(".*?"|.*?)(?:,|$)/g,pe=class r{constructor(e,t){typeof e=="string"&&(e=r.parseAttrList(e,t)),ce(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((s,n)=>(s[n.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=Sh.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,s={},n='"';for(Ga.lastIndex=0;(i=Ga.exec(e))!==null;){let a=i[1].trim(),o=i[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(l||d))o=Kr(t,o);else if(!d&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")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":oe.warn(`${e}: attribute ${a} is missing quotes`)}s[a]=o}return s}},bh="com.apple.hls.interstitial";function Ah(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function xh(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}var ns=class{constructor(e,t,i=0){var s;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=t?.tagAnchor||null,this.tagOrder=(s=t?.tagOrder)!=null?s:i,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){oe.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ce(new pe({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){let n=t?.endDate||new Date(e["END-DATE"]);B(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(oe.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(B(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===bh}get isValid(){return!!this.id&&!this._badValueForSameId&&B(this.startDate.getTime())&&(this.duration===null||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)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:B(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}},Il=10,_n=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?B(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Il}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function rs(r,e){return r.length===e.length?!r.some((t,i)=>t!==e[i]):!1}function Va(r,e){return!r&&!e?!0:!r||!e?!1:rs(r,e)}function Vt(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function qr(r){switch(r){case"AES-128":case"AES-256":return At.cbc;case"AES-256-CTR":return At.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function kn(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function Ih(r){let e=kn(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Ll(r){let e=function(i,s,n){let a=i[s];i[s]=i[n],i[n]=a};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function Rl(r){let e=r.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){let n=s[0]==="base64",a=s[1];n?(i.splice(-1,1),t=Gr(a)):t=Ih(a)}}return t}var as=typeof self<"u"?self:void 0,me={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ke={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function wi(r){switch(r){case ke.FAIRPLAY:return me.FAIRPLAY;case ke.PLAYREADY:return me.PLAYREADY;case ke.WIDEVINE:return me.WIDEVINE;case ke.CLEARKEY:return me.CLEARKEY}}var Pl={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function js(r){switch(r){case me.FAIRPLAY:return ke.FAIRPLAY;case me.PLAYREADY:return ke.PLAYREADY;case me.WIDEVINE:return ke.WIDEVINE;case me.CLEARKEY:return ke.CLEARKEY}}function jt(r){let{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[me.FAIRPLAY,me.WIDEVINE,me.PLAYREADY,me.CLEARKEY].filter(s=>!!e[s]):[];return!i[me.WIDEVINE]&&t&&i.push(me.WIDEVINE),i}var _l=function(r){return as!=null&&(r=as.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Lh(r,e,t,i){let s;switch(r){case me.FAIRPLAY:s=["cenc","sinf"];break;case me.WIDEVINE:case me.PLAYREADY:s=["cenc"];break;case me.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Rh(s,e,t,i)}function Rh(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Ph(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Wr(r){let e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=et(e),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=Gr(o).subarray(0,16);return Ll(l),l}}return null}var Nt={},wt=class r{static clearKeyUriToKeyIdMap(){Nt={}}static setKeyIdForUri(e,t){Nt[e]=t}static addKeyIdForUri(e){let t=Object.keys(Nt).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Nt[e]=i,i}constructor(e,t,i,s=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Vt(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Jo(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&rs(e.keyFormatVersions,this.keyFormatVersions)&&Va(e.iv,this.iv)&&Va(e.keyId,this.keyId)}isSupported(){if(this.method){if(Vt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ke.FAIRPLAY:case ke.WIDEVINE:case ke.PLAYREADY:case ke.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var i;if(!this.encrypted||!this.uri)return null;if(Vt(this.method)){let a=this.iv;return a||(typeof e!="number"&&(oe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=kh(e)),new r(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){let a=Nt[this.uri];if(a&&!rs(this.keyId,a)&&r.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let s=Rl(this.uri);if(s)switch(this.keyFormat){case ke.WIDEVINE:if(this.pssh=s,!this.keyId){let a=cl(s.buffer).filter(o=>o.systemId===Pl.WIDEVINE);if(a.length){var n;let o=a[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=Ha(t));break;case ke.PLAYREADY:{let a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Bc(a,null,s),this.keyId=Wr(s);break}default:{let a=s.subarray(0,16);if(a.length!==16){let o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((i=this.keyId)==null?void 0:i.byteLength)!==16){let a;a=_h(t),a||(a=Ha(t),a||(a=Nt[this.uri])),a&&(this.keyId=a,r.setKeyIdForUri(this.uri,a))}return this}};function _h(r){let e=r?.[ke.WIDEVINE];return e?e.keyId:null}function Ha(r){let e=r?.[ke.PLAYREADY];if(e){let t=Rl(e.uri);if(t)return Wr(t)}return null}function kh(r){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}var Ka=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,qa=/#EXT-X-MEDIA:(.*)/g,Dh=/^#EXT(?:INF|-X-TARGETDURATION):/m,zs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ch=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|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Et=class r{static findGroup(e,t){for(let i=0;i<e.length;i++){let s=e[i];if(s.id===t)return s}}static resolve(e,t){return Nr.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Dh.test(e)}static parseMasterPlaylist(e,t){let i=$a(e),s={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(Ka.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let a;for(;(a=Ka.exec(e))!=null;)if(a[1]){let l=new pe(a[1],s),d=Wa(l,a[2],t,s,n);d&&s.levels.push(d)}else if(a[3]){let l=a[3],d=a[4];switch(l){case"I-FRAME-STREAM-INF":{let c=new pe(d,s),h=Wa(c,c.URI,t,s,n,!0);h&&s.iframeVariants.push(h)}break;case"SESSION-DATA":{let c=new pe(d,s),h=c["DATA-ID"];h&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[h]=c);break}case"SESSION-KEY":{let c=Ya(d,t,s);c.encrypted&&c.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(c)):oe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{let c=new pe(d,s);Ua(s,c,t)}break}case"CONTENT-STEERING":{let c=new pe(d,s);s.contentSteering={uri:r.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=ja(d);break}}}let o=n.length>0&&n.length<s.levels.length;return s.levels=o?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s,n={},a=i.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(qa.lastIndex=0;(s=qa.exec(e))!==null;){let d=new pe(s[1],i),c=d.TYPE;if(c){let h=o[c],u=n[c]||[];n[c]=u;let f=d.LANGUAGE,g=d["ASSOC-LANGUAGE"],m=d.CHANNELS,p=d.CHARACTERISTICS,v=d["INSTREAM-ID"],T={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:c,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?r.resolve(d.URI,t):""};if(g&&(T.assocLang=g),m&&(T.channels=m),p&&(T.characteristics=p),v&&(T.instreamId=v),h!=null&&h.length){let E=r.findGroup(h,T.groupId)||h[0];Xa(T,E,"audioCodec"),Xa(T,E,"textCodec")}u.push(T)}}return n}static parseLevelPlaylist(e,t,i,s,n,a){var o;let l={url:t},d=new _n(t),c=d.fragments,h=[],u=null,f=0,g=0,m=0,p=0,v=0,T=null,E=new Ut(s,l),S,b,A,x=-1,R=!1,P=null,I;if(zs.lastIndex=0,d.m3u8=e,d.hasVariableRefs=$a(e),((o=zs.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=zs.exec(e))!==null;){R&&(R=!1,E=new Ut(s,l),E.playlistOffset=m,E.setStart(m),E.sn=f,E.cc=p,v&&(E.bitrate=v),E.level=i,u&&(E.initSegment=u,u.rawProgramDateTime&&(E.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),P&&(E.setByteRange(P),P=null)));let $=S[1];if($){E.duration=parseFloat($);let C=(" "+S[2]).slice(1);E.title=C||null,E.tagList.push(C?["INF",$,C]:["INF",$])}else if(S[3]){if(B(E.duration)){var k;E.playlistOffset=m,E.setStart(m),A&&Za(E,A,d),E.sn=f,E.level=i,E.cc=p;let C=(" "+S[3]).slice(1);E.relurl=Kr(d,C),Dn(E,T,h),T=E,m+=E.duration,f++,g=0;let M=E.byteRange;if(M.length===2&&(E.bitrate=(M[1]-M[0])*8/E.duration|0),d.iframesOnly&&M[0]&&((k=u)==null?void 0:k.cc)!==p){let w=new Ut(s,l);w.relurl=E.relurl,w.setByteRange(`${Math.min(M[0],7*188)}@0`),w.level=i,w.sn="initSegment",A&&(w.levelkeys=A,A.identity&&(w._decryptdata=A.identity.getDecryptData(0))),u=w,E.initSegment=u}c.push(E),R=!0}}else{if(S=S[0].match(Ch),!S){oe.warn("No matches on slow regex match for level playlist!");continue}for(b=1;b<S.length&&S[b]===void 0;b++);let C=(" "+S[b]).slice(1),M=(" "+S[b+1]).slice(1),w=S[b+2]?(" "+S[b+2]).slice(1):null;switch(C){case"BYTERANGE":T?E.setByteRange(M,T):E.setByteRange(M);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=M,E.tagList.push(["PROGRAM-DATE-TIME",M]),x===-1&&(x=c.length);break;case"PLAYLIST-TYPE":d.type&&ht(d,C,S),d.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?ht(d,C,S):T!==null&&Oh(d,C,S),d.startSN=parseInt(M),f=d.startSN+d.skippedSegments;break;case"SKIP":{d.skippedSegments&&ht(d,C,S);let N=new pe(M,d),K=N.decimalInteger("SKIPPED-SEGMENTS");if(B(K)){d.skippedSegments+=K;for(let U=K;U--;)c.push(null);f+=K}let O=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(O.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&ht(d,C,S),d.targetduration=Math.max(parseInt(M),1);break;case"VERSION":d.version!==null&&ht(d,C,S),d.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":d.iframesOnly=!0;break;case"ENDLIST":d.live||ht(d,C,S),d.live=!1;break;case"#":(M||w)&&E.tagList.push(w?[M,w]:[M]);break;case"DISCONTINUITY":p++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([C]);break;case"BITRATE":E.tagList.push([C,M]),v=parseInt(M)*1e3,B(v)?E.bitrate=v:v=0;break;case"DATERANGE":{let N=new pe(M,d),K=new ns(N,d.dateRanges[N.ID],d.dateRangeTagCount);d.dateRangeTagCount++,K.isValid||d.skippedSegments?d.dateRanges[K.id]=K:oe.log(`Ignoring invalid DATERANGE tag: ${K.invalidReason}: ${M}`),E.tagList.push(["EXT-X-DATERANGE",M]);break}case"DEFINE":{{let N=new pe(M,d);"IMPORT"in N?Th(d,N,a):Ua(d,N,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0&&ht(d,C,S),d.startCC=p=parseInt(M),c.forEach(N=>N&&(N.cc=p));break;case"KEY":{let N=Ya(M,t,d);if(N.isSupported()){if(N.method==="NONE"){A=void 0;break}A||(A={});let K=A[N.keyFormat];K!=null&&K.matches(N)||(K&&(A=ce({},A)),A[N.keyFormat]=N)}else oe.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${M}"`);break}case"START":d.startTimeOffset=ja(M);break;case"MAP":{let N=new pe(M,d);if(E.duration){let K=new Ut(s,l);Qa(K,N,i,A),u=K,E.initSegment=u,u.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=u.rawProgramDateTime)}else{let K=E.byteRangeEndOffset;if(K){let O=E.byteRangeStartOffset;P=`${K-O}@${O}`}else P=null;Qa(E,N,i,A),u=E,R=!0}u.cc=p;break}case"SERVER-CONTROL":{I&&ht(d,C,S),I=new pe(M),d.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),d.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&ht(d,C,S);let N=new pe(M);d.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=d.partList;N||(N=d.partList=[]);let K=g>0?N[N.length-1]:void 0,O=g++,U=new pe(M,d),Z=new mn(U,E,l,O,K);N.push(Z),E.duration+=Z.duration;break}case"PRELOAD-HINT":{let N=new pe(M,d);d.preloadHint=N;break}case"RENDITION-REPORT":{let N=new pe(M,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(N);break}default:oe.warn(`line parsed but not handled: ${S}`);break}}}T&&!T.relurl?(c.pop(),m-=T.duration,d.partList&&(d.fragmentHint=T)):d.partList&&(Dn(E,T,h),E.cc=p,d.fragmentHint=E,A&&Za(E,A,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let D=c.length,F=c[0],G=c[D-1];if(m+=d.skippedSegments*d.targetduration,m>0&&D&&G){d.averagetargetduration=m/D;let $=G.sn;d.endSN=$!=="initSegment"?$:0,d.live||(G.endList=!0),x>0&&(Mh(c,x,x>D-1?E:null),F&&h.unshift(F))}return d.fragmentHint&&(m+=d.fragmentHint.duration),d.totalduration=m,h.length&&d.dateRangeTagCount&&F&&kl(h,d),d.endCC=p,d}};function Wa(r,e,t,i,s,n){var a;if(e===void 0)return null;let o=Kr(i,e),l={attrs:r,bitrate:r.decimalInteger("BANDWIDTH")||r.decimalInteger("AVERAGE-BANDWIDTH"),name:r.NAME,url:Et.resolve(o,t)},d=r.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),za(r.CODECS,l);let c=r["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},za(c,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||s.push(l),n&&(l.iframes=!0),l}function kl(r,e){let t=r.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];r.push(o),t++}else return;let i=r[t-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let c=t;c--;){var a;if(((a=r[c])==null?void 0:a.sn)<e.startSN)break;let h=wh(e,d,r,c,s);if(h){l.tagAnchor=h.ref;break}}}}function wh(r,e,t,i,s){let n=t[i];if(n){let o=n.programDateTime;if(e>=o||i===0){var a;let l=(((a=t[i+1])==null?void 0:a.start)||s)-n.start;if(e<=o+l*1e3){let d=n.sn-r.startSN,c=r.fragments;if(d>=0&&d<c.length){if(c.length>t.length){let h=t[i+1]||c[c.length-1],u=Math.min(h.sn-r.startSN,c.length-1);for(let f=u;f>d;f--){let g=c[f].programDateTime;if(e>=g&&e<g+c[f].duration*1e3)return c[f]}}return c[d]}}}}return null}function Ya(r,e,t){var i,s;let n=new pe(r,t),a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!l&&oe.error(`Invalid IV: ${n.IV}`);let h=o?Et.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new wt(a,h,c,u,l,n.KEYID)}function ja(r){let t=new pe(r).decimalFloatingPoint("TIME-OFFSET");return B(t)?t:null}function za(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text","image"].forEach(i=>{let s=t.filter(n=>Vr(n,i));s.length&&(e[`${i}Codec`]=s.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>s.indexOf(n)===-1))}),e.unknownCodecs=t}function Xa(r,e,t){let i=e[t];i&&(r[t]=i)}function Mh(r,e,t){if(t||(t=r[e]),!!t)for(let i=e;i--;){let s=r[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function Dn(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function Qa(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function Za(r,e,t){r.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(r)}function ht(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Oh(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Xs(r,e){let t=e.startPTS;if(B(t)){let i=0,s;e.sn>r.sn?(i=t-r.start,s=r):(i=r.start-t,s=e),s.duration!==i&&s.setDuration(i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function Dl(r,e,t,i,s,n,a,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let d=t,c=i,h=e.startPTS,u=e.endPTS;if(B(h)){let T=Math.abs(h-t);r&&T>r.totalduration?o.warn(`media timestamps and playlist times differ by ${T}s for level ${e.level} ${r.url}`):B(e.deltaPTS)?e.deltaPTS=Math.max(T,e.deltaPTS):e.deltaPTS=T,d=Math.max(t,h),t=Math.min(t,h),s=e.startDTS!==void 0?Math.min(s,e.startDTS):s,c=Math.min(i,u),i=Math.max(i,u),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}let f=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=d,e.startDTS=s,e.endPTS=i,e.minEndPTS=c,e.endDTS=n;let g=e.sn;if(!r||g<r.startSN||g>r.endSN)return 0;let m,p=g-r.startSN,v=r.fragments;for(v[p]=e,m=p;m>0;m--)Xs(v[m],v[m-1]);for(m=p;m<v.length-1;m++)Xs(v[m],v[m+1]);return r.fragmentHint&&Xs(v[v.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,f}function Fh(r,e,t){if(r===e)return;let i=null,s=r.fragments;for(let c=s.length-1;c>=0;c--){let h=s[c].initSegment;if(h){i=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;$h(r,e,(c,h,u,f)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==c.cc){let g=c.cc-h.cc;for(let m=u;m<f.length;m++)f[m].cc+=g;e.endCC=f[f.length-1].cc}B(c.startPTS)&&B(c.endPTS)&&(h.setStart(h.startPTS=c.startPTS),h.startDTS=c.startDTS,h.maxStartPTS=c.maxStartPTS,h.endPTS=c.endPTS,h.endDTS=c.endDTS,h.minEndPTS=c.minEndPTS,h.setDuration(c.endPTS-c.startPTS),h.duration&&(n=h),e.PTSKnown=e.alignedSliding=!0),c.hasStreams&&(h.elementaryStreams=c.elementaryStreams),h.loader=c.loader,c.hasStats&&(h.stats=c.stats),c.initSegment&&(h.initSegment=c.initSegment,i=c.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(c=>{var h;c&&(!c.initSegment||c.initSegment.relurl===((h=i)==null?void 0:h.relurl))&&(c.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(c=>!c),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Nh(r.dateRanges,e,t));let c=r.fragments.filter(h=>h.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&Dn(o[h],o[h-1],c);kl(c,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;let c=Ml(r,e.startSN-1);e.startCC=(l=c?.cc)!=null?l:a[0].cc}if(Bh(r.partList,e.partList,(c,h)=>{h.elementaryStreams=c.elementaryStreams,h.stats=c.stats,h.gap=c.gap||h.gap}),n){let c=e.iframesOnly&&n.type===H.MAIN;Dl(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,c,t)}else Cl(r,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let c=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=c),e.driftEndTime=d,e.driftEnd=c}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function Nh(r,e,t){let{dateRanges:i,recentlyRemovedDateranges:s}=e,n=ce({},r);s&&s.forEach(l=>{delete n[l]});let o=Object.keys(n).length;return o?(Object.keys(i).forEach(l=>{let d=n[l],c=new ns(i[l].attr,d);c.isValid?(n[l]=c,d||(c.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${fe(i[l].attr)}"`)}),n):i}function Bh(r,e,t){if(r&&e){let i=0;for(let s=0,n=r.length;s<n;s++){let a=r[s],o=e[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function $h(r,e,t){var i;let s=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,a=(r.fragmentHint?1:0)+(s?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,o=e.startSN-r.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=(i=r.fragmentHint)!=null&&i.duration?r.fragments.concat(r.fragmentHint):r.fragments;for(let c=n;c<=a;c++){let h=d[o+c],u=l[c];if(s&&!u&&h&&(u=e.fragments[c]=h),h&&u){t(h,u,c,l);let f=h.relurl,g=u.relurl;if(f&&Gh(f,g)){e.playlistParsingError=Ja(`media sequence mismatch ${u.sn}:`,r,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=Ja(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,r,e,h,u);return}}}}function Ja(r,e,t,i,s){return new Error(`${r} ${s.url}
11
+ Time to underbuffer: ${ie.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,K>f){let z=this.findBestLevel(j.levels[f].bitrate,f,K,0,ie,1,1);z===-1&&(z=f),j.nextLoadLevel=j.nextAutoLevel=z,this.firstAutoFloor=Math.min(z,j.firstLevel),this.resetEstimator(j.levels[z].bitrate)}}};p||$>N*2?Z():this.timer=self.setInterval(Z,N*1e3),a.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:c})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){let e=this.hls.config;return new vn(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(y.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:s,partCurrent:n}=this;if(i&&pn(i,s)){let a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){let h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(h,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,s){let n=e+i/t,a=s?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let i=this.hls.config,{loading:s}=t.stats,n=s.end-s.first;B(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var i;let{frag:s,part:n}=t,a=n?n.stats:s.stats;if(s.type===H.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(s)){if(this.clearTimer(),s.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(i=this.hls)!=null&&i.config.abrMaxWithRealBitrate){let o=n?n.duration:s.duration,l=this.hls.levels[s.level],d=(l.loaded?l.loaded.bytes:0)+a.loaded,c=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:d,duration:c},l.realBitrate=Math.round(8*d/c)}if(s.bitrateTest){let o={stats:a,frag:s,part:n,id:s.type};this.onFragBuffered(y.FRAG_BUFFERED,o),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}}onFragBuffered(e,t){let{frag:i,part:s}=t,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let o=((i.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==H.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{hls:e}=this;if(!e)return 0;let{maxAutoLevel:t,minAutoLevel:i}=e,s=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(s,i,t,n/2,a,1,1);if(o>-1)return o;let l=e.firstLevel,d=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,c=Math.min(Math.max(l,i),t,d);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${c}`),c}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:s,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),c=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(d){let p=this.findBestLevel(l,a,s,d,0,c,h);if(p>=0)return this.rebufferNotice=-1,p}let u=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){let p=this.bitrateTestDelay;p&&(u=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),c=h=1)}let f=this.findBestLevel(l,a,s,d,u,c,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let g=i.levels[a],m=i.loadLevelObj;return m&&g?.bitrate<m.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e?.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,i,s,n,a,o){let{hls:l,lastLoadedFragLevel:d,fragCurrent:c,partCurrent:h}=this;if(!l)return-1;let u=s+n,f=d===-1?l.firstLevel:d,{levels:g,allAudioTracks:m,loadLevel:p,latestLevelDetails:v,config:T}=l;if(g.length===1)return 0;let E=g[f],S=!!(v!=null&&v.live),b=p===-1||d===-1,A,x="SDR",R=E?.frameRate||0,{audioPreference:P,videoPreference:I}=T,k=this.audioTracksByGroup||(this.audioTracksByGroup=Sl(m)),D=-1;if(b){if(this.firstSelection!==-1)return this.firstSelection;let M=this.codecTiers||(this.codecTiers=uh(g,k,t,i)),w=hh(M,x,e,P,I),{codecSet:N,videoRanges:K,minFramerate:O,minBitrate:U,minIndex:Z,preferHDR:j}=w;D=Z,A=N,x=j?K[K.length-1]:K[0],R=O,e=Math.max(e,U),this.log(`picked start tier ${fe(w)}`)}else A=E?.codecSet,x=E?.videoRange;let F=h?h.duration:c?c.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,$=[];for(let M=i;M>=t;M--){var C;let w=g[M],N=M>f;if(!w)continue;if(T.useMediaCapabilities&&!w.supportedResult&&!w.supportedPromise){let z=navigator.mediaCapabilities;typeof z?.decodingInfo=="function"&&ih(w,k,x,R,e,P)?(w.supportedPromise=vl(w,k,z,this.supportedCache),w.supportedPromise.then(ne=>{if(!this.hls)return;w.supportedResult=ne;let ee=this.hls.levels,ae=ee.indexOf(w);ne.error?this.warn(`MediaCapabilities decodingInfo error: "${ne.error}" for level ${ae} ${fe(ne)}`):ne.supported?ne.decodingInfoResults.some(be=>be.smooth===!1||be.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ae} not smooth or powerEfficient: ${fe(ne)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ae} ${fe(ne)}`),ae>-1&&ee.length>1&&(this.log(`Removing unsupported level ${ae}`),this.hls.removeLevel(ae),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ne=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ne}`)})):w.supportedResult=pl}if((A&&w.codecSet!==A||x&&w.videoRange!==x||N&&R>w.frameRate||!N&&R>0&&R<w.frameRate||(C=w.supportedResult)!=null&&(C=C.decodingInfoResults)!=null&&C.some(z=>z.smooth===!1))&&(!b||M!==D)){$.push(M);continue}let K=w.details,O=(h?K?.partTarget:K?.averagetargetduration)||F||1,U;N?U=o*e:U=a*e;let Z=F&&s>=F*2&&n===0?w.averageBitrate:w.maxBitrate,j=this.getTimeToLoadFrag(G,U,Z*O,!K||K.live);if(U>=Z&&(M===d||w.loadError===0&&w.fragmentError===0||zo(w,T.errorPenaltyExpireMs))&&(j<=G||!B(j)||S&&!this.bitrateTestDelay||j<u)){let z=this.forcedAutoLevel;return M!==p&&(z===-1||z!==p)&&($.length&&this.trace(`Skipped level(s) ${$.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[$[0]].codecs}" ${g[$[0]].videoRange}; not compatible with "${A}" ${x}`),this.info(`switch candidate:${f}->${M} adjustedbw(${Math.round(U)})-bitrate=${Math.round(U-Z)} ttfb:${G.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${b} codecSet:${w.codecSet} videoRange:${w.videoRange} hls.loadLevel:${p}`)),b&&(this.firstSelection=M),M}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},Al={search:function(r,e){let t=0,i=r.length-1,s=null,n=null;for(;t<=i;){s=(t+i)/2|0,n=r[s];let a=e(n);if(a>0)t=s+1;else if(a<0)i=s-1;else return n}return null}};function ph(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!B(e))return null;let i=r[0].programDateTime;if(e<(i||0))return null;let s=r[r.length-1].endProgramDateTime;if(e>=(s||0))return null;for(let n=0;n<r.length;++n){let a=r[n];if(vh(e,t,a))return a}return null}function qt(r,e,t=0,i=0,s=.005){let n=null;if(r){n=e[1+r.sn-e[0].sn]||null;let o=r.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&r.level!==n.level&&n.end<=r.end&&(n=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!r||r.level===n.level)&&Oa(t,i,n)===0||yh(n,r,Math.min(s,i))))return n;let a=Al.search(e,Oa.bind(null,t,i));return a&&(a!==r||!n)?a:n}function yh(r,e,t){if(e?.start===0&&e.level<r.level&&(e.endPTS||0)>0){let i=e.tagList.reduce((s,n)=>(n[0]==="INF"&&(s+=parseFloat(n[1])),s),t);return r.start<=i}return!1}function Oa(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=r?1:t.start-i>r&&t.start?-1:0}function vh(r,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>r}function xl(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){let i=r.fragments,{fragmentHint:s}=r;s&&(i=i.concat(s));let n;return Al.search(i,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Il(r,e){return e===r.endSN&&r.fragmentHint?r.fragmentHint:r.fragments[1+e-r.startSN]||null}var Re={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Le={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},Ln=class extends Oe{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.ERROR,this.onError,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(y.ERROR,this.onError,this),e.off(y.ERROR,this.onErrorOut,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===H.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return!0;let s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(a=>s.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;let s=this.hls,n=t.context;switch(t.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case L.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=ti();return}case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Re.SendAlternateToPenaltyBox;return}case L.PLAYLIST_UNCHANGED_ERROR:case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var a;let o=t.parent===H.MAIN?t.level:s.loadLevel;t.details===L.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let o=s.loadLevelObj;if(o&&(n.type===te.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===te.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Re.SendAlternateToPenaltyBox,t.errorAction.flags=Le.MoveAllAlternatesMatchingHost;return}}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingHDCP};return;case L.KEY_SYSTEM_SESSION_UPDATE_FAILED:case L.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case L.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingKey};return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case L.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=Le.ResetMediaSource|Le.SwitchToSDR;return;case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_APPEND_NO_PROGRESS:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:t.errorAction=ti();return}t.type===W.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ti())}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,s=Sa(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(ai(s,n,zi(e),e.response))return{action:Re.RetryRequest,flags:Le.None,retryConfig:s,retryCount:n};let o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Sa(Yo(e)?a:n,e),l=t.levels.reduce((c,h)=>c+h.fragmentError,0);if(s&&(e.details!==L.FRAG_GAP&&s.fragmentError++,!jo(e)&&ai(o,l,zi(e),e.response)))return{action:Re.RetryRequest,flags:Le.None,retryConfig:o,retryCount:l};let d=this.getLevelSwitchAction(e,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let s=this.hls.levels[t];if(s){var n,a;let d=e.details;s.loadError++,s.loadErrorTime=self.performance.now(),d===L.BUFFER_APPEND_ERROR&&s.fragmentError++;let c=-1,{levels:h,loadLevel:u,minAutoLevel:f,maxAutoLevel:g}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);let m=(n=e.frag)==null?void 0:n.type,v=(m===H.AUDIO&&d===L.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&Fa(e))&&h.some(({audioCodec:A})=>s.audioCodec!==A),E=e.sourceBufferName==="video"&&Fa(e)&&h.some(({codecSet:A,audioCodec:x})=>s.codecSet!==A&&s.audioCodec===x),{type:S,groupId:b}=(a=e.context)!=null?a:{};for(let A=h.length;A--;){let x=(A+u)%h.length;if(x!==u&&x>=f&&x<=g&&(h[x].loadError===0||zo(h[x],i.config.errorPenaltyExpireMs))){var o,l;let R=h[x];if(d===L.FRAG_GAP&&m===H.MAIN&&e.frag){let P=h[x].details;if(P){let I=qt(e.frag,P.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(S===te.AUDIO_TRACK&&R.hasAudioGroup(b)||S===te.SUBTITLE_TRACK&&R.hasSubtitleGroup(b))continue;if(m===H.AUDIO&&(o=s.audioGroups)!=null&&o.some(P=>R.hasAudioGroup(P))||m===H.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(P=>R.hasSubtitleGroup(P))||v&&s.audioCodec===R.audioCodec||E&&s.codecSet===R.codecSet||!v&&s.audioCodec!==R.audioCodec)continue}c=x;break}}if(c>-1&&i.loadLevel!==c)return e.levelRetry=!0,this.playlistError=0,{action:Re.SendAlternateToPenaltyBox,flags:Le.None,nextAutoLevel:c}}return{action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i,s;switch((i=t.errorAction)==null?void 0:i.action){case Re.DoNothing:break;case Re.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==L.FRAG_GAP&&t.details!==L.PLAYLIST_UNCHANGED_ERROR&&!Ll(t)&&(t.fatal=!0);break;case Re.RetryRequest:break}if((((s=t.errorAction)==null?void 0:s.flags)||0)&Le.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let s=i.nextAutoLevel;if(i.flags===Le.None)this.switchLevel(e,s);else if(i.flags&Le.SwitchToSDR){let o=this.hls.levels,l=o.length;for(let d=l;d--;)o[d].videoRange!=="SDR"?(o[d].fragmentError++,o[d].loadError++):s===void 0&&(s=d)}else if(i.flags&Le.MoveAllAlternatesMatchingHDCP){let o=this.getVariantLevelIndex(e.frag),l=t.levels[o],d=l?.attrs["HDCP-LEVEL"];i.hdcpLevel=d;let c=d==="NONE";d&&!c?(t.maxHdcpLevel=xn[xn.indexOf(d)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(c&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=Le.MoveAllAlternatesMatchingKey)}if(i.flags&Le.MoveAllAlternatesMatchingKey){let o=e.decryptdata;if(o){let l=this.hls.levels,d=l.length;for(let h=d;h--;)if(this.variantHasKey(l[h],o)){var n,a;this.log(`Banned key found in level ${h} (${l[h].bitrate}bps) or audio group "${(n=l[h].audioGroups)==null?void 0:n.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${Ie(o.keyId||[])}`),l[h].fragmentError++,l[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}let c=e.frag;if(this.hls.levels.length<d)i.resolved=!0;else if(c&&c.type!==H.MAIN){let h=c.decryptdata;h&&!o.matches(h)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===L.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let i=An(e.mimeType),s=this.hls.levels;for(let n=s.length;n--;)s[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n))}}};function Fa(r){let e=r.details;return e===L.BUFFER_ADD_CODEC_ERROR||e===L.MEDIA_SOURCE_REQUIRES_RESET||e===L.BUFFER_APPEND_ERROR&&!Ll(r)}function Ll(r){return r.details===L.BUFFER_APPEND_ERROR&&(r.error.name==="QuotaExceededError"||r.error.name==="InvalidStateError")}function ti(r){let e={action:Re.DoNothing,flags:Le.None};return r&&(e.resolved=!0),e}var ye={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Rn=class{constructor(e){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=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e&&(e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let s=i.length;s--;){let n=i[s];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){let{fragments:s}=this,n=Object.keys(s);for(let a=n.length;a--;){let o=s[n[a]];if(o?.body.type===t&&(!i||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,s,n,a){this.timeRanges&&(this.timeRanges[e]=t);let o=n?.fragment.sn||-1;Object.keys(this.fragments).forEach(l=>{let d=this.fragments[l];if(!d||!this.hls)return;let c=d.body;if(o>=c.sn)return;if(!d.buffered&&(!d.loaded||a)){c.type===i&&this.removeFragment(c);return}let h=d.range[e];if(h){if(h.time.length===0){this.removeFragment(c);return}if(h.time.some(u=>{let f=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return f&&this.removeFragment(c),f}),s&&s!==c&&ei()){let u=s.endPTS,f=c.startPTS;if(u&&f&&d.range.video){let g=f-u;g<0&&g>-.1&&(this.removeFragment(c),this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:u+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:i,part:s,id:n}=e;if(!t||!ve(i))return;let a=Ft(i),o=this.fragments[a];if(!o||o.buffered&&i.gap)return;let l=!i.relurl;Object.keys(t).forEach(c=>{let h=i.elementaryStreams[c];if(!h)return;let u=t[c],f=l||h.partial===!0;o.range[c]=this.getBufferedTimes(i,s,f,u),this.detectEvictedFragments(c,u,n,i,s)}),o.loaded=null;let d=Object.keys(o.range);if(d.length){if(this.bufferedEnd(o,i),Di(o)||this.removeParts(i.sn-1,i.type),!s){let c=Math.min(.004,i.duration);d.some(h=>{var u;let f=(u=o.range[h])==null?void 0:u.time,g=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<c;return g&&this.addAsGap(i),g})}}else this.removeFragment(i)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=Na(i,s=>s.fragment.sn>=e))}fragBuffered(e,t){let i=Ft(e),s=this.fragments[i];return!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e)),s}getBufferedTimes(e,t,i,s){let n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let c=0;c<s.length;c++){let h=s.start(c)-this.bufferPadding,u=s.end(c)+this.bufferPadding;if(d>=h&&l<=u){n.time.push({startPTS:Math.max(a,s.start(c)),endPTS:Math.min(o,s.end(c))});break}else if(a<u&&o>h){let f=Math.max(a,s.start(c)),g=Math.min(o,s.end(c));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}else if(o<=h)break}return n}getPartialFragment(e){let t=null,i,s,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{let c=l[d];c&&Di(c)&&(s=c.body.start-o,n=c.body.end+o,e>=s&&e<=n&&(i=Math.min(e-s,n-e),a<=i&&(t=c.body,a=i)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Di(t))}getState(e){let t=Ft(e),i=this.fragments[t];return i?i.buffered?Di(i)?ye.PARTIAL:ye.OK:ye.APPENDING:ye.NOT_LOADED}isTimeBuffered(e,t,i){let s,n;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=s&&t<=n)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!ve(t.frag)||t.frag.bitrateTest)return;let i=t.frag,s=t.part?null:t,n=Ft(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:s,timeRanges:n}=t;if(!ve(i))return;let a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=n}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Ft(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){let n=t[i[s]];if(n?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,i){let{fragments:s}=this,n=0,a=0,o=Object.keys(s);for(let l=0;l<o.length;l++){let d=s[o[l]];if(!d||!d.buffered||d.body.type!==t)continue;let c=d.body;if(c.gap)return 0;let h=c.hasStats&&c.stats.loaded||c.byteLength||c.bitrate&&c.bitrate*8*c.duration;if(c.end<=e&&h&&(n+=h,a=Math.max(a,c.end),n>=i))return a}return a>0?a:0}removeFragmentsInRange(e,t,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=Ft(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let s=e.sn;this.activePartLists[e.type]=Na(i,n=>n.fragment.sn!==s)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo())}};function Di(r){var e,t,i,s;return r.buffered&&!!(r.body.gap||(e=r.range.video)!=null&&e.partial||(t=r.range.audio)!=null&&t.partial||(i=r.range.audiovideo)!=null&&i.partial||(s=r.range.subs)!=null&&s.partial)}function Ft(r){return`${r.type}_${r.level}_${r.sn}`}function Na(r,e){return r.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var At={cbc:0,ctr:1},Pn=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case At.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case At.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function Eh(r){let e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}var _n=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,d=l[0],c=l[1],h=l[2],u=l[3],f=new Uint32Array(256),g=0,m=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let v=m^m<<1^m<<2^m<<3^m<<4;v=v>>>8^v&255^99,e[g]=v,t[v]=g;let T=f[g],E=f[T],S=f[E],b=f[v]*257^v*16843008;s[g]=b<<24|b>>>8,n[g]=b<<16|b>>>16,a[g]=b<<8|b>>>24,o[g]=b,b=S*16843009^E*65537^T*257^g*16843008,d[v]=b<<24|b>>>8,c[v]=b<<16|b>>>16,h[v]=b<<8|b>>>24,u[v]=b,g?(g=T^f[f[f[S^T]]],m^=f[f[m]]):g=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,l,d=this.keySchedule=new Uint32Array(a),c=this.invKeySchedule=new Uint32Array(a),h=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],m=f[1],p=f[2],v=f[3],T,E;for(o=0;o<a;o++){if(o<n){T=d[o]=t[o];continue}E=T,o%n===0?(E=E<<8|E>>>24,E=h[E>>>24]<<24|h[E>>>16&255]<<16|h[E>>>8&255]<<8|h[E&255],E^=u[o/n|0]<<24):n>6&&o%n===4&&(E=h[E>>>24]<<24|h[E>>>16&255]<<16|h[E>>>8&255]<<8|h[E&255]),d[o]=T=(d[o-n]^E)>>>0}for(l=0;l<a;l++)o=a-l,l&3?E=d[o]:E=d[o-4],l<4||o<=4?c[l]=E:c[l]=g[h[E>>>24]]^m[h[E>>>16&255]]^p[h[E>>>8&255]]^v[h[E&255]],c[l]=c[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){let s=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],c=o[2],h=o[3],u=this.uint8ArrayToUint32Array_(i),f=u[0],g=u[1],m=u[2],p=u[3],v=new Int32Array(e),T=new Int32Array(v.length),E,S,b,A,x,R,P,I,k,D,F,G,$,C,M=this.networkToHostOrderSwap;for(;t<v.length;){for(k=M(v[t]),D=M(v[t+1]),F=M(v[t+2]),G=M(v[t+3]),x=k^n[0],R=G^n[1],P=F^n[2],I=D^n[3],$=4,C=1;C<s;C++)E=l[x>>>24]^d[R>>16&255]^c[P>>8&255]^h[I&255]^n[$],S=l[R>>>24]^d[P>>16&255]^c[I>>8&255]^h[x&255]^n[$+1],b=l[P>>>24]^d[I>>16&255]^c[x>>8&255]^h[R&255]^n[$+2],A=l[I>>>24]^d[x>>16&255]^c[R>>8&255]^h[P&255]^n[$+3],x=E,R=S,P=b,I=A,$=$+4;E=a[x>>>24]<<24^a[R>>16&255]<<16^a[P>>8&255]<<8^a[I&255]^n[$],S=a[R>>>24]<<24^a[P>>16&255]<<16^a[I>>8&255]<<8^a[x&255]^n[$+1],b=a[P>>>24]<<24^a[I>>16&255]<<16^a[x>>8&255]<<8^a[R&255]^n[$+2],A=a[I>>>24]<<24^a[x>>16&255]<<16^a[R>>8&255]<<8^a[P&255]^n[$+3],T[t]=M(E^f),T[t+1]=M(A^g),T[t+2]=M(b^m),T[t+3]=M(S^p),f=k,g=D,m=F,p=G,t=t+4}return T.buffer}},kn=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){let e=Th(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function Th(r){switch(r){case At.cbc:return"AES-CBC";case At.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}var Sh=16,fi=class{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,t!==!0)try{let i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);this.reset();let s=this.decryptRange;return s?s.start===0&&s.end>=i.length?i:i.slice(s.start,s.end):Eh(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s,n){return this.decryptRange=n,this.useSoftware||n?new Promise((a,o)=>{let l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,i,s);let d=this.flush();d?a(d.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){let{currentIV:n,currentResult:a,remainderData:o}=this;if(s!==At.cbc||t.byteLength!==16)return oe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ye(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(i=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new _n),d.expandKey(t);let c=a;return this.currentResult=d.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,c||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new kn(this.subtle,t,s)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Pn(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(oe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%Sh;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(oe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Ba=Math.pow(2,17),ts=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,i,s){let n=e.url;if(!n)return Promise.reject(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();let a=this.config,o=a.fLoader,l=a.loader;return new Promise((d,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){c(Ua(e));return}else e.gap=!1;let h=this.loader=o?new o(a):new l(a),u=$a(e,null,t);e.loader=h;let f=ba(a.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Ba};h.stats.retry=e.stats.retry,e.stats=h.stats;let m={onSuccess:(p,v,T,E)=>{this.resetLoader(e,h);let S=p.data;T.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(S.slice(0,16)),S=S.slice(16)),d({frag:e,part:null,payload:S,networkDetails:E})},onError:(p,v,T,E)=>{this.resetLoader(e,h),c(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Y({url:n,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:T,stats:E}))},onAbort:(p,v,T)=>{this.resetLoader(e,h),c(new We({type:W.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:T,stats:p}))},onTimeout:(p,v,T)=>{this.resetLoader(e,h),c(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:T,stats:p}))}};if(i){let p=this.gateProgress(i,s);m.onProgress=(v,T,E,S)=>p({frag:e,part:null,payload:E,networkDetails:S})}h.load(u,g,m)})}gateProgress(e,t){let i=e;if(t){let s=[],n=!1;t.then(()=>{n=!0,s.forEach(a=>e(a)),s.length=0}).catch(()=>{}),i=a=>{n?e(a):s.push(a)}}return i}loadPart(e,t,i){this.abort();let s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Ua(e,t));return}let d=this.loader=n?new n(s):new a(s),c=$a(e,t);e.loader=d;let h=ba(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ba};t.stats=d.stats,d.load(c,u,{onSuccess:(f,g,m,p)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:p};i(v),o(v)},onError:(f,g,m,p)=>{this.resetLoader(e,d),l(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Y({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:p}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new We({type:W.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,d),l(new We({type:W.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){let i=e.stats,s=t.stats,n=s.total;if(i.loaded+=s.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/n),l),h=(l-d)*Math.round(i.loaded/d);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);let a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function $a(r,e=null,t){let i=e||r,s={type:te.MEDIA_FRAGMENT,frag:r,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=is(r,e,t);return n.resetIV&&(s.resetIV=!0),n.byteRange&&(s.rangeStart=n.byteRange.start,s.rangeEnd=n.byteRange.end),s}function is(r,e=null,t){let i={},s=e||r,n=s.byteRangeStartOffset,a=s.byteRangeEndOffset;if(B(n)&&B(a)){var o;if((r.sn==="initSegment"||t)&&bh((o=r.decryptdata)==null?void 0:o.method)){let l=Math.floor(n/16)*16,d=Math.ceil(a/16)*16;i.decryptRange={start:n-l,end:a-l},l>=16&&(i.resetIV=!0,l=l-16),i.byteRange={start:l,end:d}}else i.byteRange={start:n,end:a}}return i}function Ua(r,e){let t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:W.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(i.part=e),(e||r).stats.aborted=!0,new We(i)}function bh(r){return r==="AES-128"||r==="AES-256"}var We=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},ss=class extends Oe{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},gi=class{constructor(e,t,i,s=0,n=-1,a=!1,o,l,d){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.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=Ci(),this.buffering={audio:Ci(),video:Ci(),audiovideo:Ci()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=n,this.partial=a,this.duration=o||0,this.decryptRange=d,this.iframe=l||!1}};function Ci(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Ga={length:0,start:()=>0,end:()=>0},J=class r{static isBuffered(e,t){if(e){let i=r.getBuffered(e);for(let s=i.length;s--;)if(t>=i.start(s)&&t<=i.end(s))return!0}return!1}static bufferedRanges(e){if(e){let t=r.getBuffered(e);return r.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let s=r.bufferedRanges(e);if(s.length)return r.bufferedInfo(s,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((c,h)=>c.start-h.start||h.end-c.end);let s=-1,n=[];if(i)for(let c=0;c<e.length;c++){t>=e[c].start&&t<=e[c].end&&(s=c);let h=n.length;if(h){let u=n[h-1].end;e[c].start-u<i?e[c].end>u&&(n[h-1].end=e[c].end):n.push(e[c])}else n.push(e[c])}else n=e;let a=0,o,l=t,d=t;for(let c=0;c<n.length;c++){let h=n[c].start,u=n[c].end;if(s===-1&&t>=h&&t<=u&&(s=c),t+i>=h&&t<u)l=h,d=u,a=d-t;else if(t+i<h){o=h;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||Ga}catch(t){return oe.log("failed to get media.buffered",t),Ga}}},Rl=/\{\$([a-zA-Z0-9-_]+)\}/g;function Va(r){return Rl.test(r)}function Wr(r,e){if(r.variableList!==null||r.hasVariableRefs){let t=r.variableList;return e.replace(Rl,i=>{let s=i.substring(2,i.length-1),n=t?.[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return e}function Ha(r,e,t){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(s))n=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,n=e.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function Ah(r,e,t){let i=e.IMPORT;if(t&&i in t){let s=r.variableList;s||(r.variableList=s={}),s[i]=t[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}var xh=/^(\d+)x(\d+)$/,Ka=/(.+?)=(".*?"|.*?)(?:,|$)/g,pe=class r{constructor(e,t){typeof e=="string"&&(e=r.parseAttrList(e,t)),ce(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((s,n)=>(s[n.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=xh.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,s={},n='"';for(Ka.lastIndex=0;(i=Ka.exec(e))!==null;){let a=i[1].trim(),o=i[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(l||d))o=Wr(t,o);else if(!d&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")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":oe.warn(`${e}: attribute ${a} is missing quotes`)}s[a]=o}return s}},Ih="com.apple.hls.interstitial";function Lh(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function Rh(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}var ns=class{constructor(e,t,i=0){var s;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=t?.tagAnchor||null,this.tagOrder=(s=t?.tagOrder)!=null?s:i,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){oe.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ce(new pe({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){let n=t?.endDate||new Date(e["END-DATE"]);B(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(oe.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(B(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Ih}get isValid(){return!!this.id&&!this._badValueForSameId&&B(this.startDate.getTime())&&(this.duration===null||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)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:B(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}},Pl=10,Dn=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?B(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Pl}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function rs(r,e){return r.length===e.length?!r.some((t,i)=>t!==e[i]):!1}function qa(r,e){return!r&&!e?!0:!r||!e?!1:rs(r,e)}function Vt(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function Yr(r){switch(r){case"AES-128":case"AES-256":return At.cbc;case"AES-256-CTR":return At.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function Cn(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function Ph(r){let e=Cn(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function _l(r){let e=function(i,s,n){let a=i[s];i[s]=i[n],i[n]=a};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function kl(r){let e=r.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){let n=s[0]==="base64",a=s[1];n?(i.splice(-1,1),t=Hr(a)):t=Ph(a)}}return t}var as=typeof self<"u"?self:void 0,me={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ke={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function wi(r){switch(r){case ke.FAIRPLAY:return me.FAIRPLAY;case ke.PLAYREADY:return me.PLAYREADY;case ke.WIDEVINE:return me.WIDEVINE;case ke.CLEARKEY:return me.CLEARKEY}}var Dl={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Xs(r){switch(r){case me.FAIRPLAY:return ke.FAIRPLAY;case me.PLAYREADY:return ke.PLAYREADY;case me.WIDEVINE:return ke.WIDEVINE;case me.CLEARKEY:return ke.CLEARKEY}}function jt(r){let{drmSystems:e,widevineLicenseUrl:t}=r,i=e?[me.FAIRPLAY,me.WIDEVINE,me.PLAYREADY,me.CLEARKEY].filter(s=>!!e[s]):[];return!i[me.WIDEVINE]&&t&&i.push(me.WIDEVINE),i}var Cl=function(r){return as!=null&&(r=as.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function _h(r,e,t,i){let s;switch(r){case me.FAIRPLAY:s=["cenc","sinf"];break;case me.WIDEVINE:case me.PLAYREADY:s=["cenc"];break;case me.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return kh(s,e,t,i)}function kh(r,e,t,i){return[{initDataTypes:r,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function Dh(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function jr(r){let e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=et(e),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=Hr(o).subarray(0,16);return _l(l),l}}return null}var Nt={},wt=class r{static clearKeyUriToKeyIdMap(){Nt={}}static setKeyIdForUri(e,t){Nt[e]=t}static addKeyIdForUri(e){let t=Object.keys(Nt).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),Nt[e]=i,i}constructor(e,t,i,s=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Vt(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(il(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&rs(e.keyFormatVersions,this.keyFormatVersions)&&qa(e.iv,this.iv)&&qa(e.keyId,this.keyId)}isSupported(){if(this.method){if(Vt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ke.FAIRPLAY:case ke.WIDEVINE:case ke.PLAYREADY:case ke.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var i;if(!this.encrypted||!this.uri)return null;if(Vt(this.method)){let a=this.iv;return a||(typeof e!="number"&&(oe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=wh(e)),new r(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){let a=Nt[this.uri];if(a&&!rs(this.keyId,a)&&r.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let s=kl(this.uri);if(s)switch(this.keyFormat){case ke.WIDEVINE:if(this.pssh=s,!this.keyId){let a=fl(s.buffer).filter(o=>o.systemId===Dl.WIDEVINE);if(a.length){var n;let o=a[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=Wa(t));break;case ke.PLAYREADY:{let a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Gc(a,null,s),this.keyId=jr(s);break}default:{let a=s.subarray(0,16);if(a.length!==16){let o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((i=this.keyId)==null?void 0:i.byteLength)!==16){let a;a=Ch(t),a||(a=Wa(t),a||(a=Nt[this.uri])),a&&(this.keyId=a,r.setKeyIdForUri(this.uri,a))}return this}};function Ch(r){let e=r?.[ke.WIDEVINE];return e?e.keyId:null}function Wa(r){let e=r?.[ke.PLAYREADY];if(e){let t=kl(e.uri);if(t)return jr(t)}return null}function wh(r){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}var Ya=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,ja=/#EXT-X-MEDIA:(.*)/g,Mh=/^#EXT(?:INF|-X-TARGETDURATION):/m,Qs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Oh=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|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Et=class r{static findGroup(e,t){for(let i=0;i<e.length;i++){let s=e[i];if(s.id===t)return s}}static resolve(e,t){return $r.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Mh.test(e)}static parseMasterPlaylist(e,t){let i=Va(e),s={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(Ya.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let a;for(;(a=Ya.exec(e))!=null;)if(a[1]){let l=new pe(a[1],s),d=za(l,a[2],t,s,n);d&&s.levels.push(d)}else if(a[3]){let l=a[3],d=a[4];switch(l){case"I-FRAME-STREAM-INF":{let c=new pe(d,s),h=za(c,c.URI,t,s,n,!0);h&&s.iframeVariants.push(h)}break;case"SESSION-DATA":{let c=new pe(d,s),h=c["DATA-ID"];h&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[h]=c);break}case"SESSION-KEY":{let c=Xa(d,t,s);c.encrypted&&c.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(c)):oe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{let c=new pe(d,s);Ha(s,c,t)}break}case"CONTENT-STEERING":{let c=new pe(d,s);s.contentSteering={uri:r.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=Qa(d);break}}}let o=n.length>0&&n.length<s.levels.length;return s.levels=o?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s,n={},a=i.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(ja.lastIndex=0;(s=ja.exec(e))!==null;){let d=new pe(s[1],i),c=d.TYPE;if(c){let h=o[c],u=n[c]||[];n[c]=u;let f=d.LANGUAGE,g=d["ASSOC-LANGUAGE"],m=d.CHANNELS,p=d.CHARACTERISTICS,v=d["INSTREAM-ID"],T={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:c,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?r.resolve(d.URI,t):""};if(g&&(T.assocLang=g),m&&(T.channels=m),p&&(T.characteristics=p),v&&(T.instreamId=v),h!=null&&h.length){let E=r.findGroup(h,T.groupId)||h[0];Ja(T,E,"audioCodec"),Ja(T,E,"textCodec")}u.push(T)}}return n}static parseLevelPlaylist(e,t,i,s,n,a){var o;let l={url:t},d=new Dn(t),c=d.fragments,h=[],u=null,f=0,g=0,m=0,p=0,v=0,T=null,E=new Ut(s,l),S,b,A,x=-1,R=!1,P=null,I;if(Qs.lastIndex=0,d.m3u8=e,d.hasVariableRefs=Va(e),((o=Qs.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=Qs.exec(e))!==null;){R&&(R=!1,E=new Ut(s,l),E.playlistOffset=m,E.setStart(m),E.sn=f,E.cc=p,v&&(E.bitrate=v),E.level=i,u&&(E.initSegment=u,u.rawProgramDateTime&&(E.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),P&&(E.setByteRange(P),P=null)));let $=S[1];if($){E.duration=parseFloat($);let C=(" "+S[2]).slice(1);E.title=C||null,E.tagList.push(C?["INF",$,C]:["INF",$])}else if(S[3]){if(B(E.duration)){var k;E.playlistOffset=m,E.setStart(m),A&&to(E,A,d),E.sn=f,E.level=i,E.cc=p;let C=(" "+S[3]).slice(1);E.relurl=Wr(d,C),wn(E,T,h),T=E,m+=E.duration,f++,g=0;let M=E.byteRange;if(M.length===2&&(E.bitrate=(M[1]-M[0])*8/E.duration|0),d.iframesOnly&&M[0]&&((k=u)==null?void 0:k.cc)!==p){let w=new Ut(s,l);w.relurl=E.relurl,w.setByteRange(`${Math.min(M[0],7*188)}@0`),w.level=i,w.sn="initSegment",A&&(w.levelkeys=A,A.identity&&(w._decryptdata=A.identity.getDecryptData(0))),u=w,E.initSegment=u}c.push(E),R=!0}}else{if(S=S[0].match(Oh),!S){oe.warn("No matches on slow regex match for level playlist!");continue}for(b=1;b<S.length&&S[b]===void 0;b++);let C=(" "+S[b]).slice(1),M=(" "+S[b+1]).slice(1),w=S[b+2]?(" "+S[b+2]).slice(1):null;switch(C){case"BYTERANGE":T?E.setByteRange(M,T):E.setByteRange(M);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=M,E.tagList.push(["PROGRAM-DATE-TIME",M]),x===-1&&(x=c.length);break;case"PLAYLIST-TYPE":d.type&&ht(d,C,S),d.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?ht(d,C,S):T!==null&&Bh(d,C,S),d.startSN=parseInt(M),f=d.startSN+d.skippedSegments;break;case"SKIP":{d.skippedSegments&&ht(d,C,S);let N=new pe(M,d),K=N.decimalInteger("SKIPPED-SEGMENTS");if(B(K)){d.skippedSegments+=K;for(let U=K;U--;)c.push(null);f+=K}let O=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(O.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&ht(d,C,S),d.targetduration=Math.max(parseInt(M),1);break;case"VERSION":d.version!==null&&ht(d,C,S),d.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":d.iframesOnly=!0;break;case"ENDLIST":d.live||ht(d,C,S),d.live=!1;break;case"#":(M||w)&&E.tagList.push(w?[M,w]:[M]);break;case"DISCONTINUITY":p++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([C]);break;case"BITRATE":E.tagList.push([C,M]),v=parseInt(M)*1e3,B(v)?E.bitrate=v:v=0;break;case"DATERANGE":{let N=new pe(M,d),K=new ns(N,d.dateRanges[N.ID],d.dateRangeTagCount);d.dateRangeTagCount++,K.isValid||d.skippedSegments?d.dateRanges[K.id]=K:oe.log(`Ignoring invalid DATERANGE tag: ${K.invalidReason}: ${M}`),E.tagList.push(["EXT-X-DATERANGE",M]);break}case"DEFINE":{{let N=new pe(M,d);"IMPORT"in N?Ah(d,N,a):Ha(d,N,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0&&ht(d,C,S),d.startCC=p=parseInt(M),c.forEach(N=>N&&(N.cc=p));break;case"KEY":{let N=Xa(M,t,d);if(N.isSupported()){if(N.method==="NONE"){A=void 0;break}A||(A={});let K=A[N.keyFormat];K!=null&&K.matches(N)||(K&&(A=ce({},A)),A[N.keyFormat]=N)}else oe.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${M}"`);break}case"START":d.startTimeOffset=Qa(M);break;case"MAP":{let N=new pe(M,d);if(E.duration){let K=new Ut(s,l);eo(K,N,i,A),u=K,E.initSegment=u,u.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=u.rawProgramDateTime)}else{let K=E.byteRangeEndOffset;if(K){let O=E.byteRangeStartOffset;P=`${K-O}@${O}`}else P=null;eo(E,N,i,A),u=E,R=!0}u.cc=p;break}case"SERVER-CONTROL":{I&&ht(d,C,S),I=new pe(M),d.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),d.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&ht(d,C,S);let N=new pe(M);d.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=d.partList;N||(N=d.partList=[]);let K=g>0?N[N.length-1]:void 0,O=g++,U=new pe(M,d),Z=new yn(U,E,l,O,K);N.push(Z),E.duration+=Z.duration;break}case"PRELOAD-HINT":{let N=new pe(M,d);d.preloadHint=N;break}case"RENDITION-REPORT":{let N=new pe(M,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(N);break}default:oe.warn(`line parsed but not handled: ${S}`);break}}}T&&!T.relurl?(c.pop(),m-=T.duration,d.partList&&(d.fragmentHint=T)):d.partList&&(wn(E,T,h),E.cc=p,d.fragmentHint=E,A&&to(E,A,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let D=c.length,F=c[0],G=c[D-1];if(m+=d.skippedSegments*d.targetduration,m>0&&D&&G){d.averagetargetduration=m/D;let $=G.sn;d.endSN=$!=="initSegment"?$:0,d.live||(G.endList=!0),x>0&&(Nh(c,x,x>D-1?E:null),F&&h.unshift(F))}return d.fragmentHint&&(m+=d.fragmentHint.duration),d.totalduration=m,h.length&&d.dateRangeTagCount&&F&&wl(h,d),d.endCC=p,d}};function za(r,e,t,i,s,n){var a;if(e===void 0)return null;let o=Wr(i,e),l={attrs:r,bitrate:r.decimalInteger("BANDWIDTH")||r.decimalInteger("AVERAGE-BANDWIDTH"),name:r.NAME,url:Et.resolve(o,t)},d=r.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),Za(r.CODECS,l);let c=r["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},Za(c,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||s.push(l),n&&(l.iframes=!0),l}function wl(r,e){let t=r.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];r.push(o),t++}else return;let i=r[t-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let c=t;c--;){var a;if(((a=r[c])==null?void 0:a.sn)<e.startSN)break;let h=Fh(e,d,r,c,s);if(h){l.tagAnchor=h.ref;break}}}}function Fh(r,e,t,i,s){let n=t[i];if(n){let o=n.programDateTime;if(e>=o||i===0){var a;let l=(((a=t[i+1])==null?void 0:a.start)||s)-n.start;if(e<=o+l*1e3){let d=n.sn-r.startSN,c=r.fragments;if(d>=0&&d<c.length){if(c.length>t.length){let h=t[i+1]||c[c.length-1],u=Math.min(h.sn-r.startSN,c.length-1);for(let f=u;f>d;f--){let g=c[f].programDateTime;if(e>=g&&e<g+c[f].duration*1e3)return c[f]}}return c[d]}}}}return null}function Xa(r,e,t){var i,s;let n=new pe(r,t),a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!l&&oe.error(`Invalid IV: ${n.IV}`);let h=o?Et.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new wt(a,h,c,u,l,n.KEYID)}function Qa(r){let t=new pe(r).decimalFloatingPoint("TIME-OFFSET");return B(t)?t:null}function Za(r,e){let t=(r||"").split(/[ ,]+/).filter(i=>i);["video","audio","text","image"].forEach(i=>{let s=t.filter(n=>Kr(n,i));s.length&&(e[`${i}Codec`]=s.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>s.indexOf(n)===-1))}),e.unknownCodecs=t}function Ja(r,e,t){let i=e[t];i&&(r[t]=i)}function Nh(r,e,t){if(t||(t=r[e]),!!t)for(let i=e;i--;){let s=r[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function wn(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function eo(r,e,t,i){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function to(r,e,t){r.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(r)}function ht(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Bh(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Zs(r,e){let t=e.startPTS;if(B(t)){let i=0,s;e.sn>r.sn?(i=t-r.start,s=r):(i=r.start-t,s=e),s.duration!==i&&s.setDuration(i)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function Ml(r,e,t,i,s,n,a,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,n=s+e.duration);let d=t,c=i,h=e.startPTS,u=e.endPTS;if(B(h)){let T=Math.abs(h-t);r&&T>r.totalduration?o.warn(`media timestamps and playlist times differ by ${T}s for level ${e.level} ${r.url}`):B(e.deltaPTS)?e.deltaPTS=Math.max(T,e.deltaPTS):e.deltaPTS=T,d=Math.max(t,h),t=Math.min(t,h),s=e.startDTS!==void 0?Math.min(s,e.startDTS):s,c=Math.min(i,u),i=Math.max(i,u),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}let f=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=d,e.startDTS=s,e.endPTS=i,e.minEndPTS=c,e.endDTS=n;let g=e.sn;if(!r||g<r.startSN||g>r.endSN)return 0;let m,p=g-r.startSN,v=r.fragments;for(v[p]=e,m=p;m>0;m--)Zs(v[m],v[m-1]);for(m=p;m<v.length-1;m++)Zs(v[m],v[m+1]);return r.fragmentHint&&Zs(v[v.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,f}function $h(r,e,t){if(r===e)return;let i=null,s=r.fragments;for(let c=s.length-1;c>=0;c--){let h=s[c].initSegment;if(h){i=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let n;Vh(r,e,(c,h,u,f)=>{if((!e.startCC||e.skippedSegments)&&h.cc!==c.cc){let g=c.cc-h.cc;for(let m=u;m<f.length;m++)f[m].cc+=g;e.endCC=f[f.length-1].cc}B(c.startPTS)&&B(c.endPTS)&&(h.setStart(h.startPTS=c.startPTS),h.startDTS=c.startDTS,h.maxStartPTS=c.maxStartPTS,h.endPTS=c.endPTS,h.endDTS=c.endDTS,h.minEndPTS=c.minEndPTS,h.setDuration(c.endPTS-c.startPTS),h.duration&&(n=h),e.PTSKnown=e.alignedSliding=!0),c.hasStreams&&(h.elementaryStreams=c.elementaryStreams),h.loader=c.loader,c.hasStats&&(h.stats=c.stats),c.initSegment&&(h.initSegment=c.initSegment,i=c.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(c=>{var h;c&&(!c.initSegment||c.initSegment.relurl===((h=i)==null?void 0:h.relurl))&&(c.initSegment=i)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(c=>!c),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Uh(r.dateRanges,e,t));let c=r.fragments.filter(h=>h.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let h=1;h<o.length;h++)o[h].programDateTime===null&&wn(o[h],o[h-1],c);wl(c,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;let c=Nl(r,e.startSN-1);e.startCC=(l=c?.cc)!=null?l:a[0].cc}if(Gh(r.partList,e.partList,(c,h)=>{h.elementaryStreams=c.elementaryStreams,h.stats=c.stats,h.gap=c.gap||h.gap}),n){let c=e.iframesOnly&&n.type===H.MAIN;Ml(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,c,t)}else Ol(r,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let c=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=c),e.driftEndTime=d,e.driftEnd=c}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function Uh(r,e,t){let{dateRanges:i,recentlyRemovedDateranges:s}=e,n=ce({},r);s&&s.forEach(l=>{delete n[l]});let o=Object.keys(n).length;return o?(Object.keys(i).forEach(l=>{let d=n[l],c=new ns(i[l].attr,d);c.isValid?(n[l]=c,d||(c.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${fe(i[l].attr)}"`)}),n):i}function Gh(r,e,t){if(r&&e){let i=0;for(let s=0,n=r.length;s<n;s++){let a=r[s],o=e[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function Vh(r,e,t){var i;let s=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,a=(r.fragmentHint?1:0)+(s?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,o=e.startSN-r.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=(i=r.fragmentHint)!=null&&i.duration?r.fragments.concat(r.fragmentHint):r.fragments;for(let c=n;c<=a;c++){let h=d[o+c],u=l[c];if(s&&!u&&h&&(u=e.fragments[c]=h),h&&u){t(h,u,c,l);let f=h.relurl,g=u.relurl;if(f&&Kh(f,g)){e.playlistParsingError=io(`media sequence mismatch ${u.sn}:`,r,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=io(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,r,e,h,u);return}}}}function io(r,e,t,i,s){return new Error(`${r} ${s.url}
12
12
  Playlist starting @${e.startSN}
13
13
  ${e.m3u8}
14
14
 
15
15
  Playlist starting @${t.startSN}
16
- ${t.m3u8}`)}function Cl(r,e,t=!0,i){let s=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,a=s>=0,o=0;if(a&&s<n.length)o=n[s].start,i?.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===r.endSN+1)o=r.fragmentEnd,i?.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=r.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=r.fragmentStart,i?.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return Uh(e,o),o}function Uh(r,e){if(e){let t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function wl(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){let i=r.fragments;if(i.length&&t*4>e){let n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Ml(r,e,t){var i;if(!r)return null;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,((i=s)==null?void 0:i.sn)===e)?s:t&&e<r.startSN&&t.sn===e?t:null}function eo(r,e,t){return r?Ol(r.partList,e,t):null}function Ol(r,e,t){if(r)for(let i=r.length;i--;){let s=r[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function Fl(r){r.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(s=>{s.level=t,s.initSegment&&(s.initSegment.level=t)})})}function Gh(r,e){return r!==e&&e?to(r)!==to(e):!1}function to(r){return r.replace(/\?[^?]*$/,"")}function ii(r,e){for(let i=0,s=r.length;i<s;i++){var t;if(((t=r[i])==null?void 0:t.cc)===e)return r[i]}return null}function Vh(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function io(r,e){let t=r.start+e;r.setStart(t)}function Nl(r,e){let t=e.fragments;for(let i=0,s=t.length;i<s;i++)io(t[i],r);e.fragmentHint&&io(e.fragmentHint,r),e.alignedSliding=!0}function os(r,e,t){r&&(Hh(e,r,t),e.alignedSliding||Kh(e,r,t),!e.alignedSliding&&!e.skippedSegments&&Cl(r,e,!1,t))}function Hh(r,e,t){if(!Vh(e,r))return;let i=Math.min(e.endCC,r.endCC),s=ii(e.fragments,i),n=ii(r.fragments,i);if(!s||!n)return;let a=s.start-n.start;t.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),Nl(a,r)}function Kh(r,e,t){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;let i=r.fragments,s=e.fragments;if(!i.length||!s.length)return;let n,a,o=Math.min(e.endCC,r.endCC);e.startCC<o&&r.startCC<o&&(n=ii(s,o),a=ii(i,o)),(!n||!a)&&(n=s[Math.floor(s.length/2)]||s.filter(u=>!!u)[0],a=ii(i,n.cc)||i[Math.floor(i.length/2)]);let l=n.programDateTime,d=a.programDateTime;if(!l||!d)return;let c=(d-l)/1e3;if(Math.abs(c)>Math.max(60,r.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(c)} > ${r.totalduration})`);return}let h=c-(a.start-n.start);t.log(`Aligning playlists using PDT (diff: ${h})`),Nl(h,r)}function de(r,e,t){le(r,e,t),r.addEventListener(e,t)}function le(r,e,t){r.removeEventListener(e,t)}function ls(r){let e="",t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return e}var _={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},mi=class extends ss{constructor(e,t,i,s,n){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=_.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:d,state:c}=this,h=l?l.currentTime:0,u=J.bufferInfo(d||l,h,a.maxBufferHole),f=u.len;if(this.log(`Media seeking to ${h}, state: ${c}, ${f?"in":"out of"} buffer`),this.state===_.ENDED)this.resetLoadingState();else if(o){let m=a.maxFragLookUpTolerance,p=o.start-m,v=o.start+o.duration+m;if(!f||v<u.start||p>u.end){let T=h<p,E=h>v;(T||E)&&(o.loader&&(E||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${T?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);let m=this.lastCurrentTime;if(h>m&&(this.lastCurrentTime=h),!this.loadingParts){let p=Math.max(u.end,h),v=this.shouldLoadParts(this.getLevelDetails(),p);v&&(this.log(`LL-Part loading ON after seeking to ${h} with buffer @${p}`),this.loadingParts=v)}}let g=!J.isBuffered(l,h);(!this.hls.hasEnoughToStart||g)&&(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,g&&(this.startPosition=h)),f<1&&this.state===_.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new ts(e.config),this.initFragmentLoader=new ts(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new fi(e.config)}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===_.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=_.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let i=this.getLevelDetails();return i!=null&&i.live?(this.hls.liveSyncPosition||i.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=J.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>s&&a<t.edge||this.media.currentTime<e.start)return!1;let l=t.partList;if(l!=null&&l.length){let c=l[l.length-1];return J.isBuffered(this.media,c.start+c.duration/2)}let d=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(d.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;de(i,"seeking",this.onMediaSeeking),de(i,"ended",this.onMediaEnded);let s=this.config;this.levels&&s.autoStartLoad&&this.state===_.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let i=!!t.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),le(s,"seeking",this.onMediaSeeking),le(s,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=_.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){let s=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)} was dropped during download.`),this.fragmentTracker.removeFragment(a);return}let o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)} chunk: ${o}`),this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,s).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===_.FRAG_LOADING||!this.fragCurrent&&a===_.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=_.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(y.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===_.STOPPED||this.state===_.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${n?.message||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===ye.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===ye.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,i=e.fragments[e.fragments.length-1];if(i.endList&&!t.isEndListAppended(this.playlistType)){let s=t.getPartialFragment(i.end);s&&(t.removeFragment(s),t.fragBuffered(i,!0))}t.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let s={startOffset:e,endOffset:t,type:i};this.hls.trigger(y.BUFFER_FLUSHING,s)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(i=>{var s;let n=i.frag;if(!this.levels||!gn(n,(s=this.fragCurrent)==null?void 0:s.initSegment))throw new We({type:W.NETWORK_ERROR,details:L.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:n,networkDetails:null});return i}).then(i=>{let{frag:s,payload:n}=i,a=s.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&Vt(a.method)){let o=self.performance.now(),{decryptRange:l}=is(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,qr(a.method),l).catch(d=>{throw t.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:s}),this.fragmentLoader.abort(),d}).then(d=>{let c=self.performance.now();return t.trigger(y.FRAG_DECRYPTED,{frag:s,part:null,payload:d,stats:{tstart:o,tdecrypt:c}}),i.payload=d,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)})}completeInitSegmentLoad(e){let t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){let{initSegment:t}=e;if(!this.bitrateTest&&ve(e)&&t&&!t.data){var i;return(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(n=>{throw this.state===_.STOPPED||this.state===_.ERROR||("data"in n&&(n.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(n)),this.resetFragmentLoading(e)),n})}}unhandledEncryptionError(e,t){var i,s;let n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(s=n.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(y.ERROR,{type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!gn(e,t)}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?ls(J.getBuffered(i)):"(detached)"})`),ve(e)){var s;if(e.type!==H.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=_.IDLE;return}}let n=(s=this.levels)==null?void 0:s[e.level];n!=null&&n.fragmentError&&(t||this.fragmentTracker.getState(e)!==ye.PARTIAL)&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0,e.stats.retry=0)}this.state=_.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let i=e.frag,{part:s,partsLoaded:n}=e,a=!n||n.length===0||n.some(d=>!d),{decryptRange:o}=is(i,s),l=new gi(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a,i.duration,this.iframesOnly,o);this.log(`load complete ${i.type} sn: ${i.sn}${s?" part: "+s.index:""} of ${this.fragInfo(i,!1,s)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,i){var s;let n=null;return e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=_.KEY_LOADING,n=this.keyLoader.load(e,i).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(y.KEY_LOADED,a),this.state===_.KEY_LOADING&&(this.state=_.IDLE),a}),this.hls.trigger(y.KEY_LOADING,{frag:e})):e.encrypted||(n=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),n&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),n}_doFragLoad(e,t,i=null,s){this.fragCurrent=e;let n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=this.fragPrevious;if(!Zt(e,a)){let f=this.shouldLoadParts(t.details,e.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${a?.sn}->${e.sn}`),this.loadingParts=f)}if(i=Math.max(e.start,i||0),this.loadingParts){let f=n.partList;if(f&&s){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);let g=this.getNextPart(f,e,i);if(g>-1){let m=f[g];if(e=this.fragCurrent=m.fragment,!Zt(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,m)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(m,t.details))return Promise.resolve(null);let p=this.loadKeyFor(e,n);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${g}/${f.length-1}) of ${this.fragInfo(e,!1,m)} cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${i}${m.byteRange.length?` range:${m.byteRange.join("-")}`:""}`),this.nextLoadPosition=m.start+m.duration,this.state=_.FRAG_LOADING;let v,T=this.loadInitSegmentIfNeeded(e);if(p||T){let E=!!p;v=Promise.all([p,T]).then(([S])=>E&&(!S||this.fragContextChanged(S.frag))?null:this.doFragPartsLoad(e,m,t,s)).catch(S=>this.handleFragLoadError(S))}else v=this.doFragPartsLoad(e,m,t,s).catch(E=>this.handleFragLoadError(E));return this.hls.trigger(y.FRAG_LOADING,{frag:e,part:m,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):v}else if(!e.url||this.loadedEndOfParts(f,i))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${e.sn} loaded parts: ${(o=n.partList)==null?void 0:o.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let l=this.loadInitSegmentIfNeeded(e),d=this.loadKeyFor(e,n,l);if(this.fragContextChanged(e)){var c;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(c=this.fragCurrent)==null?void 0:c.relurl}`),l?.catch(()=>null),d?.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${i}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),B(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=_.FRAG_LOADING;let h=this.config.progressive&&e.type!==H.SUBTITLE,u;return h&&d?u=d.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,s,l)).catch(f=>this.handleFragLoadError(f)):u=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,h?s:void 0,h?l:void 0),d,l]).then(([f])=>(!h&&s&&s(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([u,l]).then(([f])=>f)}doFragPartsLoad(e,t,i,s){return new Promise((n,a)=>{var o;let l=[],d=(o=i.details)==null?void 0:o.partList,c=h=>{this.fragmentLoader.loadPart(e,h,s).then(u=>{l[h.index]=u;let f=u.part;this.hls.trigger(y.FRAG_LOADED,u);let g=eo(i.details,e.sn,h.index+1)||Ol(d,e.sn,h.index+1);if(g)c(g);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};c(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===W.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==_.PARSING){!this.fragCurrent&&this.state!==_.STOPPED&&this.state!==_.ERROR&&(this.state=_.IDLE);return}let{frag:i,part:s,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a);let o=this.getLevelDetails(),d=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=d),this.updateLevelTiming(i,s,n,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var i;let s=e.partList[0],n=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=n&&this.playhead>s.start-s.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:a}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;let o=t[s],l=o.details,d=a>-1?eo(l,n,a):null,c=d?d.fragment:Ml(l,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:d,level:o}):null}bufferFragmentData(e,t,i,s,n){if(this.state!==_.PARSING)return;ve(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:o}=e,l=a;if(o&&(l=Ye(a,o)),!l.length)return;let d=this.initPTS[t.cc],c=d?-d.baseTime/d.timescale:void 0,h={type:e.type,frag:t,part:i,chunkMeta:s,offset:c,parent:t.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!J.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,s=J.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,s.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;let s=this.playhead,a=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,a)}getFwdBufferInfoAtPos(e,t,i,s){let n=J.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,s);return J.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){let s=e.nextStart;if(s&&i.start>s){let n=e.buffered;if(n){let a=e.len,o=e.bufferedIndex;for(let l=n.length-1;l>o;l--)n[l].start<i.start&&(a+=n[l].end-n[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){let i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t/2),n=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return n>=s?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e){let t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){let i=t.fragments,s=i.length;if(!s)return null;let{config:n}=this,a=t.fragmentStart,o=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let h=n.initialLiveManifestSize;if(s<h)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var d;l=this.getInitialLiveFragment(t);let u=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,m=((d=l)==null?void 0:d.start)||0,p,v;if(f!==-1&&f>=a?(p=f,v=f===u?"config":"next load start"):g?(p=g,v="live edge"):(p=e,v="buffer pos"),p<m&&(p=m,v="live frag start"),p<a&&(p=a,v="playlist start"),this.startPosition!=p||this.nextLoadPosition!=p){let E=t.live&&!this.filterReplacedPrimary(l,t)?-1:p;this.log(`Setting startPosition to ${E} next load ${p} ${f===-1?"":`(from ${u}) `}based on ${v}. live edge: ${g} live frag start: ${m} playlist start: ${a} buffer pos: ${e}`),this.startPosition=E,this.nextLoadPosition=p}}}else e<=a&&(l=i[0]);if(!l){let h=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,h,t)}let c=this.filterReplacedPrimary(l,t);return!c&&l&&(c=bl(t,l.sn),c&&(this.nextLoadPosition=c.start)),c}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let i=this.fragmentTracker.getState(e);return!!(i===ye.OK||i===ye.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,i,s,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(o!==null&&i.len+o.len>=n){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(ds(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(ds(this.config)&&("type"in e?e:e.fragment).type!==H.SUBTITLE){let i=this.hls.interstitialsManager,s=i?.bufferingItem;if(s){let n=s.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-s.start)>1||s.start===0))return null}else if(e.end<=s.start&&t?.live===!1||e.start>=s.end&&s.nextEvent&&(s.nextEvent.appendInPlace&&!s.nextEvent.hasPlayed||e.start-s.end>1))return null}if(Bl(e,i?.playerQueue,this.playhead))return null}return e}getNextPart(e,t,i){let s=-1,n=!1,a=!0;for(let l=0,d=e.length;l<d;l++){let c=e[l];if(a=a&&!c.independent,s>-1&&i<c.start)break;let h=c.loaded||c.gap;h?s=-1:(n||(c.independent||a)&&c.fragment===t)&&(s=l),n=h&&!c.gap}let o=e[s];return o&&o.fragment!==t&&this.log(`Need buffer at ${i} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,s=null;if(i){if(e.hasProgramDateTime&&(s=fh(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!s){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Sl(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){let{config:s}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:d}=s,c=i.partList,h=!!(this.loadingParts&&c!=null&&c.length&&l);h&&!this.bitrateTest&&c[c.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),n&&this.fragmentTracker.getState(n)===ye.NOT_LOADED&&(n=null);let u;if(e<t){var f;let m=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;u=qt(n,a,e,m)}else u=a[a.length-1];if(u){let g=u.sn-i.startSN,m=this.fragmentTracker.getState(u);if((m===ye.OK||m===ye.PARTIAL&&u.gap)&&(n=u),Zt(u,n)&&(!h||c[0].fragment.sn>u.sn||!i.live)){let p=a[g+1];u.sn<o&&this.fragmentTracker.getState(p)!==ye.OK?u=p:u=null}}return u}alignPlaylists(e,t,i){let s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&B(n);if(a||!o&&!n){os(i,e,this);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);let s=this.timelineOffset;if(i===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;if(a!==null&&B(a))i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i;else if(e.live){let o=this.hls.liveSyncPosition;i=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;let{media:t}=this,i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;let i=(t=this.media)==null?void 0:t.currentTime;return B(i)?i:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==H.MAIN)return!1;let t=this.getLevelDetails();return t?t.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ve(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==_.FRAG_LOADING_WAITING_RETRY)&&(this.state=_.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let T=this.getCurrentContext(t.chunkMeta);T&&(t.frag=T.frag)}let{frag:i,part:s}=t;if(!i||!this.levels||i.type!==e)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${(n=this.fragCurrent)==null?void 0:n.relurl}`);return}let a=t.details===L.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);let o=t.errorAction;if(!o){this.state=_.ERROR;return}let{action:l,flags:d,retryCount:c=0,retryConfig:h}=o,u=!!h,f=u&&l===Re.RetryRequest,g=u&&!o.resolved&&d&Le.MoveAllAlternatesMatchingHost,m=this.hls.latestLevelDetails,p=m?.live;if(!f&&g&&ve(i)&&p&&i.sn<m.endSN&&!qo(t))this.resetFragmentErrors(e),s?s.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((f||g)&&c<h.maxNumRetry){var v;let T=oi((v=t.response)==null?void 0:v.code),E=Br(h,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=_.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,T){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${c+1}/${h.maxNumRetry} in ${E}ms`)}else if(h)if(this.resetFragmentErrors(e),c<h.maxNumRetry)!a&&l!==Re.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${c})`);return}else l===Re.SendAlternateToPenaltyBox?this.state=_.WAITING_LEVEL:this.state=_.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!oi(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=_.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===_.PARSING||this.state===_.PARSED){let t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,t?.duration||10);let a=!n;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):s.nextStart&&t&&s.nextStart>t.start&&this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,i===H.AUDIO?i:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===H.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==_.STOPPED&&(this.state=_.IDLE)}afterBufferFlushed(e,t){if(!e)return;let i=J.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,this.playlistType),this.state===_.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==_.STOPPED&&(this.state=_.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){let n=i.details;if(!n){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((h,u)=>{let f=e.elementaryStreams[u];if(f){let g=f.endPTS-f.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${u} duration reliably (${g})`),h||!1;let m=s.partial?0:Dl(n,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this.iframesOnly,this);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:i,drift:m,type:u,frag:e,start:f.startPTS,end:f.endPTS}),!0}return h},!1)){var o,l,d,c;let h=((o=this.transmuxer)==null?void 0:o.error)===null,u=((l=this.transmuxer)==null?void 0:l.error)!=null,f=((d=(c=this.levels)==null?void 0:c.length)!=null?d:0)>1;if((i.fragmentError===0||h&&(i.fragmentError<2||e.endList)||u&&f)&&this.treatAsGap(e,i),h){let g=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(g.message),this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:g,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=_.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,i){var s,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN}-${(n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;let i=(t=e.loader)==null?void 0:t.stats;if(!i)return!1;let s=i.loading.first>0,a=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&a<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let i=0,{hls:s,media:n,config:a,levels:o,playlistType:l}=this,d=this.getLevelDetails();if(n&&!n.paused&&o){var c;let f=l===H.AUDIO?pl(e.audioCodec,128e3):e.maxBitrate,g=1+s.ttfbEstimate/1e3,m=s.bandwidthEstimate*a.abrBandWidthUpFactor,p=d&&(this.loadingParts?d.partTarget:d.averagetargetduration)||((c=this.fragCurrent)==null?void 0:c.duration)||6;i=g+f*p/m,e.details||(i+=g)}let h=this.playhead,u=!(d!=null&&d.live)||t.end-h>i*1.5;return{fetchdelay:i,okToFlushForwardBuffer:u}}scheduleTrackSwitch(e,t,i){let{media:s,playlistType:n}=this;if(!s||!e)return;let a=i?this.getBufferedFrag(this.playhead+t):null;if(a){let l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();let d=l.maxStartPTS?l.maxStartPTS:l.start,c=l.duration,h=Math.max(a.end,d+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>h)return;let f=n===H.MAIN?null:"audio";this.flushMainBuffer(h,Number.POSITIVE_INFINITY,f),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){let s=t===H.AUDIO;this.flushMainBuffer(0,i.start-(s?0:1),s?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case _.KEY_LOADING:case _.FRAG_LOADING:case _.FRAG_LOADING_WAITING_RETRY:case _.PARSING:case _.PARSED:this.state=_.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(J.isBuffered(e,i)?t=this.getAppendedFrag(i):J.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t&&(this.backtrackFragment=void 0,!Zt(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:i,config:s,playlistType:n}=this;if(t!=null&&t.readyState&&e&&i&&s){let a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,n);if(!o)return;let l=n===H.AUDIO?i.nextAudioTrack:i.nextLoadLevel,d=e[l],{fetchdelay:c,okToFlushForwardBuffer:h}=this.calculateOptimalSwitchPoint(d,o);this.scheduleTrackSwitch(o,c,h)}this.tickImmediate()}};function Bl(r,e,t){if(e)for(let i=e.length;i--;){let s=e[i].interstitial,n=s.startTime,a=Math.min(n+s.duration,s.resumeTime);if(s.appendInPlace&&(r.start>=n&&r.end<=a||t>r.start&&r.end>n&&r.start<a))return!0}return!1}function ds(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}var cs=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=qh(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}};function qh(r,e){let t=new Uint8Array(e),i=0;for(let s=0;s<r.length;s++){let n=r[s];t.set(n,i),i+=n.length}return t}var Qs={exports:{}},so;function Wh(){return so||(so=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,d,c){this.fn=l,this.context=d,this.once=c||!1}function n(l,d,c,h,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new s(c,h||l,u),g=t?t+d:d;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var u=0,f=h.length,g=new Array(f);u<f;u++)g[u]=h[u].fn;return g},o.prototype.listenerCount=function(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,u,f,g){var m=t?t+d:d;if(!this._events[m])return!1;var p=this._events[m],v=arguments.length,T,E;if(p.fn){switch(p.once&&this.removeListener(d,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,c),!0;case 3:return p.fn.call(p.context,c,h),!0;case 4:return p.fn.call(p.context,c,h,u),!0;case 5:return p.fn.call(p.context,c,h,u,f),!0;case 6:return p.fn.call(p.context,c,h,u,f,g),!0}for(E=1,T=new Array(v-1);E<v;E++)T[E-1]=arguments[E];p.fn.apply(p.context,T)}else{var S=p.length,b;for(E=0;E<S;E++)switch(p[E].once&&this.removeListener(d,p[E].fn,void 0,!0),v){case 1:p[E].fn.call(p[E].context);break;case 2:p[E].fn.call(p[E].context,c);break;case 3:p[E].fn.call(p[E].context,c,h);break;case 4:p[E].fn.call(p[E].context,c,h,u);break;default:if(!T)for(b=1,T=new Array(v-1);b<v;b++)T[b-1]=arguments[b];p[E].fn.apply(p[E].context,T)}}return!0},o.prototype.on=function(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,u){var f=t?t+d:d;if(!this._events[f])return this;if(!c)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!u||g.once)&&(!h||g.context===h)&&a(this,f);else{for(var m=0,p=[],v=g.length;m<v;m++)(g[m].fn!==c||u&&!g[m].once||h&&g[m].context!==h)&&p.push(g[m]);p.length?this._events[f]=p.length===1?p[0]:p:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}(Qs)),Qs.exports}var Yh=Wh(),Yr=Wd(Yh),pi="1.7.1",Wt={};function jh(){return typeof __HLS_WORKER_BUNDLE__=="function"}function zh(){let r=Wt[pi];if(r)return r.clientCount++,r;let 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"}),t=self.URL.createObjectURL(e),s={worker:new self.Worker(t),objectURL:t,clientCount:1};return Wt[pi]=s,s}function Xh(r){let e=Wt[r];if(e)return e.clientCount++,e;let t=new self.URL(r,self.location.href).href,s={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Wt[r]=s,s}function Qh(r){let e=Wt[r||pi];if(e&&e.clientCount--===1){let{worker:i,objectURL:s}=e;delete Wt[r||pi],s&&self.URL.revokeObjectURL(s),i.terminate()}}function Zh(r,e,t,i){let s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let p=new Error(`invalid ADTS sampling index:${a}`);r.emit(y.ERROR,y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d=s[a],c=a;(o===5||o===29)&&(c-=3);let h,u=(c&14)>>1,f=(c&1)<<7|l<<3,g=0;if(o===1&&a>=6){g=5;let p=a-3;h=[g<<3|u,f|(p&14)>>1,(p&1)<<7|8,0]}else h=[o<<3|u,f];let m="mp4a.40."+(g||o);return oe.log(`manifest codec:${i}, parsed codec:${m}, channels:${l}, rate:${d} (ADTS object type:${o} sampling index:${a} esds config:[${h.join(",")}])`),{config:h,samplerate:d,channelCount:l,codec:m,parsedCodec:m,manifestCodec:i}}function $l(r,e){return r[e]===255&&(r[e+1]&246)===240}function Ul(r,e){return r[e+1]&1?7:9}function jr(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function Jh(r,e){return e+5<r.length}function hs(r,e){return e+1<r.length&&$l(r,e)}function eu(r,e){return Jh(r,e)&&$l(r,e)&&jr(r,e)<=r.length-e}function tu(r,e){if(hs(r,e)){let t=Ul(r,e);if(e+t>=r.length)return!1;let i=jr(r,e);if(i<=t)return!1;let s=e+i;return s===r.length||hs(r,s)}return!1}function Gl(r,e,t,i,s){if(!r.samplerate){let n=Zh(e,t,i,s);if(!n)return;ce(r,n)}}function Vl(r){return 1024*9e4/r}function iu(r,e){let t=Ul(r,e);if(e+t<=r.length){let i=jr(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Hl(r,e,t,i,s){let n=Vl(r.samplerate),a=i+s*n,o=iu(e,t),l;if(o){let{frameLength:h,headerLength:u}=o,f=u+h,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-u),l.set(e.subarray(t+u,e.length),0)):l=e.subarray(t+u,t+f);let m={unit:l,pts:a};return g||r.samples.push(m),{sample:m,length:f,missing:g}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}var Me=function(r){return r.audioId3="org.id3",r.dateRange="com.apple.quicktime.HLS",r.emsg="https://aomedia.org/emsg/ID3",r.misbklv="urn:misb:KLV:bin:1910.1",r}({});function at(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var yi=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Ye(this.cachedData,e),this.cachedData=null);let i=li(e,0),s=i?i.length:0,n,a=this._audioTrack,o=this._id3Track,l=i?Ur(i):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&B(l))&&(this.basePTS=su(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Me.audioId3,duration:Number.POSITIVE_INFINITY});s<d;){if(this.canParse(e,s)){let c=this.appendFrame(a,e,s);c?(this.frameIndex++,this.lastPTS=c.sample.pts,s+=c.length,n=s):s=d}else dc(e,s)?(i=li(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Me.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===d&&n!==d){let c=e.slice(n);this.cachedData?this.cachedData=Ye(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:at(),id3Track:o,textTrack:at()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:at(),id3Track:this._id3Track,textTrack:at()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},su=(r,e,t)=>{if(B(r))return r*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},nu=[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],ru=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],au=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ou=[0,1,1,4];function Kl(r,e,t,i,s){if(t+24>e.length)return;let n=ql(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function ql(r,e){let t=r[e+1]>>3&3,i=r[e+1]>>1&3,s=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){let a=r[e+2]>>1&1,o=r[e+3]>>6,l=t===3?3-i:i===3?3:4,d=nu[l*14+s-1]*1e3,h=ru[(t===3?0:t===2?1:2)*3+n],u=o===3?1:2,f=au[t][i],g=ou[i],m=f*8*g,p=Math.floor(f*d/h+a)*g,v=ei();return!!v&&v<=87&&i===2&&d>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:u,frameLength:p,samplesPerFrame:m}}}function zr(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function Wl(r,e){return e+1<r.length&&zr(r,e)}function lu(r,e){return zr(r,e)&&4<=r.length-e}function Yl(r,e){if(e+1<r.length&&zr(r,e)){let i=ql(r,e),s=4;i!=null&&i.frameLength&&(s=i.frameLength);let n=e+s;return n===r.length||Wl(r,n)}return!1}var us=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new fi(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,At.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,i){let s=e[t].unit;if(s.length<=16)return;let n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),s=0;for(let n=32;n<e.length-16;n+=160,s+=16)i.set(e.subarray(n,n+16),s);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),s=0;for(let n=32;n<e.length-16;n+=160,s+=16)e.set(i.subarray(s,s+16),n);return e}decryptAvcSample(e,t,i,s,n){let a=dl(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}let n=e[t].units;for(;!(i>=n.length);i++){let a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,s,a),!this.decrypter.isSync()))return}}}},Cn=class extends yi{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let i=li(e,0),s=i?.length||0;if(Yl(e,s))return!1;for(let n=e.length;s<n;s++)if(tu(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return eu(e,t)}appendFrame(e,t,i){Gl(e,this.observer,t,i,e.manifestCodec);let s=Hl(e,t,i,this.basePTS,this.frameIndex);if(s?.missing===0)return s}demuxSampleAes(e,t,i){let s=this.demux(e,i),n=this.sampleAes=new us(this.observer,this.config,t);return new Promise(a=>{n.decryptAacSamples(s.audioTrack.samples,0,()=>{a(s)})})}},jl=(r,e)=>{let t=0,i=5;e+=i;let s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=r[e];let o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t},wn=class extends yi{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let s=zl(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;let t=li(e,0);if(!t)return!1;let i=t.length;if(e[i]===11&&e[i+1]===119&&Ur(t)!==void 0){if(jl(e,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}};function zl(r,e,t,i,s){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let n=e[t+4]>>6;if(n>=3)return-1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,c=[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][l*3+n]*2;if(t+c>e.length)return-1;let h=e[t+6]>>5,u=0;h===2?u+=2:(h&1&&h!==1&&(u+=2),h&4&&(u+=2));let f=(e[t+6]<<8|e[t+7])>>12-u&1,m=[2,1,2,3,3,4,4,5][h]+f,p=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|p<<1|v>>2,(v&3)<<6|h<<3|f<<2|l>>4,l<<4&224]),E=1536/o*9e4,S=i+s*E,b=e.subarray(t,t+c);return r.config=T,r.channelCount=m,r.samplerate=o,r.samples.push({unit:b,pts:S}),c}var Mn=class extends yi{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=li(e,0),i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Ur(t)!==void 0&&jl(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(Yl(e,i))return oe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return lu(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Kl(e,t,i,this.basePTS,this.frameIndex)}},du=/\/emsg[-/]ID3/i,On=class{constructor(e,t,i,s=oe){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.initData=void 0,this.logger=void 0,this.config=t,this.logger=s}resetTimeStamp(){}resetInitSegment(e,t,i,s){let n=this.videoTrack=at("video",1),a=this.audioTrack=at("audio",1),o=this.txtTrack=at("text",1);if(this.id3Track=at("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=this.initData=nl(e);if(l.video){let{id:d,timescale:c,codec:h,supplemental:u}=l.video;n.id=d,n.timescale=o.timescale=c,n.codec=h,n.supplemental=u}if(l.audio){let{id:d,timescale:c,codec:h}=l.audio;a.id=d,a.timescale=c,a.codec=h}o.id=el.text,n.sampleDuration=0,n.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return xc(e,"moof")}demux(e,t,i){this.timeOffset=t;let s=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Ye(this.remainderData,e));let d=Mc(s);this.remainderData=d.remainder,n.samples=d.valid||new Uint8Array}else n.samples=s;let o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,i);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let i=this.timeOffset,s=this.videoTrack,n=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;let a=this.extractID3Track(s,this.timeOffset),o=this.parseFragment(s,n,i,t);return{videoTrack:s,audioTrack:at(),id3Track:a,textTrack:at(),initData:this.initData,sampleData:o}}parseFragment(e,t,i,s){let n=this.initData;if(n&&s){let{samples:a,sampleData:o}=wc(i,e,n,this.logger,s.iframe);return t.samples=a,o}t.samples=Oc(i,e)}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let s=Q(e.samples,["emsg"]);s&&s.forEach(n=>{let a=Fc(n);if(du.test(a.schemeIdUri)){let o=no(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=a.payload;i.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:Me.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let o=this.config.emsgKLVSchemaUri||Me.misbklv;if(a.schemeIdUri.startsWith(o)){let l=no(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:Me.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(e,t,i){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,this.initData=void 0}};function no(r,e){return B(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}var cu=1,hu=2,zt=-1,fs=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,s=i.length;if(s){let n=i[s-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){let s=t.byteLength;if(s===0)return[];let n=e.naluState||0,a=n===zt?0:n,o=[],l=0,d=0,c=-1,h=0;for(n===zt&&(c=0,h=this.getNALuType(t,0),d=1);d<s;){let u=t.indexOf(cu,d);if(u===-1)break;d=u+1;let f=u;for(;f>0&&t[f-1]===0;)f--;if(!(u-f+(f===0?a:0)<hu)){if(c>=0)o.push({data:t.subarray(c,f),type:h});else{let m=this.getLastNalUnit(e.samples);m&&(f>0?m.data=Ye(m.data,t.subarray(0,f)):a>0&&(m.data=m.data.subarray(0,m.data.byteLength-a)),m.state=0)}if(d<s)c=d,h=this.getNALuType(t,d);else{l=zt,c=-1;break}}}if(l!==zt){let u=s;for(;u>0&&t[u-1]===0;)u--;l=s-u+(u===0?a:0)}if(c>=0)o.push({data:t.subarray(c),type:h,state:l});else if(o.length===0&&l!==zt){let u=this.getLastNalUnit(e.samples);u&&(u.data=Ye(u.data,t),u.state=l)}return e.naluState=l,o}},Dt=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&oe.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}},Fn=class extends fs{parsePES(e,t,i,s,n){let a=n.iframe,o=this.parseNALu(e,i.data,s),l=this.VideoSample,d,c=!1;i.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.forEach(h=>{var u,f;switch(h.type){case 1:{if(a)break;let v=!1;d=!0;let T=h.data;if(c&&T.length>4){let E=this.readSliceType(T);(E===2||E===4||E===7||E===9)&&(v=!0)}if(v){var g;(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.frame=!0,l.key=v;break}case 5:d=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;d=!0,di(h.data,1,i.pts,t.samples);break}case 7:{var m,p;d=!0,c=!0;let v=h.data,T=this.readSPS(v);if(!e.sps||e.width!==T.width||e.height!==T.height||((m=e.pixelRatio)==null?void 0:m[0])!==T.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==T.pixelRatio[1]){e.width=T.width,e.height=T.height,e.pixelRatio=T.pixelRatio,e.sps=[v];let E=v.subarray(1,4),S="avc1.";for(let b=0;b<3;b++){let A=E[b].toString(16);A.length<2&&(A="0"+A),S+=A}e.codec=S}break}case 8:d=!0,e.pps=[h.data];break;case 9:d=!0,e.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:d=!0;break;default:d=!1;break}l&&d&&l.units.push(h)}),s&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Dt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8,n;for(let a=0;a<e;a++)s!==0&&(n=t.readEG(),s=(i+n+256)%256),i=s===0?i:s}readSPS(e){let t=new Dt(e),i=0,s=0,n=0,a=0,o,l,d,c=t.readUByte.bind(t),h=t.readBits.bind(t),u=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),m=t.skipEG.bind(t),p=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);c();let T=c();if(h(5),g(3),c(),p(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){let R=u();if(R===3&&g(1),p(),p(),g(1),f())for(l=R!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t))}p();let E=u();if(E===0)u();else if(E===1)for(g(1),m(),m(),o=u(),d=0;d<o;d++)m();p(),g(1);let S=u(),b=u(),A=h(1);A===0&&g(1),g(1),f()&&(i=u(),s=u(),n=u(),a=u());let x=[1,1];if(f()&&f())switch(c()){case 1:x=[1,1];break;case 2:x=[12,11];break;case 3:x=[10,11];break;case 4:x=[16,11];break;case 5:x=[40,33];break;case 6:x=[24,11];break;case 7:x=[20,11];break;case 8:x=[32,11];break;case 9:x=[80,33];break;case 10:x=[18,11];break;case 11:x=[15,11];break;case 12:x=[64,33];break;case 13:x=[160,99];break;case 14:x=[4,3];break;case 15:x=[3,2];break;case 16:x=[2,1];break;case 255:{x=[c()<<8|c(),c()<<8|c()];break}}return{width:Math.ceil((S+1)*16-i*2-s*2),height:(2-A)*(b+1)*16-(A?2:4)*(n+a),pixelRatio:x}}},Nn=class extends fs{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){let n=this.parseNALu(e,i.data,s),a=this.VideoSample,o,l=!1;i.data=null;let d=c=>(a=this.VideoSample=this.createVideoSample(c,i.pts,i.dts),a);n.forEach((c,h)=>{var u,f;if(this.startsNewAccessUnit(a,e,c,h)){this.pushAccessUnit(a,e);let m=c.type>=16&&c.type<=23;a=d(m),l=!1}switch(c.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=d(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var g;(g=a)!=null&&g.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=d(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=d(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,di(c.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ce(e.params,this.readVPS(c.data)),this.initVPS=c.data),e.vps=[c.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],c.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let m=this.readSPS(c.data);e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.codec=m.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let p in m.params)e.params[p]=m.params[p]}this.pushParameterSet(e.sps,c.data,e.vps),a||(a=d(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let m=this.readPPS(c.data);for(let p in m)e.params[p]=m[p]}this.pushParameterSet(e.pps,c.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=d(!1));break;default:o=!1;break}a&&o&&a.units.push(c)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,i,s){if(!e)return!1;if(!t.audFound&&s===0)return!0;if(!e.frame)return!1;let{type:n,data:a}=i;return n>=32&&n<=35||n===39||n>=41&&n<=44||n>=48&&n<=55?!0:n<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new Dt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){let t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let s=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),v=t.readUByte(),T=[],E=[];for(let q=0;q<i;q++)T.push(t.readBoolean()),E.push(t.readBoolean());if(i>0)for(let q=i;q<8;q++)t.readBits(2);for(let q=0;q<i;q++)T[q]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[q]&&t.readUByte();t.readUEG();let S=t.readUEG();S==3&&t.skipBits(1);let b=t.readUEG(),A=t.readUEG(),x=t.readBoolean(),R=0,P=0,I=0,k=0;x&&(R+=t.readUEG(),P+=t.readUEG(),I+=t.readUEG(),k+=t.readUEG());let D=t.readUEG(),F=t.readUEG(),G=t.readUEG(),$=t.readBoolean();for(let q=$?0:i;q<=i;q++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let se=0;se<4;se++)for(let re=0;re<(se===3?2:6);re++)if(!t.readBoolean())t.readUEG();else{let Te=Math.min(64,1<<4+(se<<1));se>1&&t.readEG();for(let Ce=0;Ce<Te;Ce++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let w=t.readUEG(),N=0;for(let q=0;q<w;q++){let se=!1;if(q!==0&&(se=t.readBoolean()),se){q===w&&t.readUEG(),t.readBoolean(),t.readUEG();let re=0;for(let Ae=0;Ae<=N;Ae++){let Te=t.readBoolean(),Ce=!1;Te||(Ce=t.readBoolean()),(Te||Ce)&&re++}N=re}else{let re=t.readUEG(),Ae=t.readUEG();N=re+Ae;for(let Te=0;Te<re;Te++)t.readUEG(),t.readBoolean();for(let Te=0;Te<Ae;Te++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let q=t.readUEG();for(let se=0;se<q;se++){for(let re=0;re<G+4;re++)t.readBits(1);t.readBits(1)}}let O=0,U=1,Z=1,j=!0,ie=1,z=0;t.readBoolean(),t.readBoolean();let ne=!1;if(t.readBoolean()){if(t.readBoolean()){let je=t.readUByte(),It=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Pe=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];je>0&&je<16?(U=It[je-1],Z=Pe[je-1]):je===255&&(U=t.readBits(16),Z=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ne=t.readBoolean(),ne&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Pe=t.readBoolean(),we=t.readBoolean(),qe=!1;(Pe||we)&&(qe=t.readBoolean(),qe&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),qe&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let $e=0;$e<=i;$e++){j=t.readBoolean();let De=j||t.readBoolean(),gt=!1;De?t.readEG():gt=t.readBoolean();let ct=gt?1:t.readUEG()+1;if(Pe)for(let ze=0;ze<ct;ze++)t.readUEG(),t.readUEG(),qe&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(we)for(let ze=0;ze<ct;ze++)t.readUEG(),t.readUEG(),qe&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),O=t.readUEG())}let ae=b,be=A;if(x){let q=1,se=1;S===1?q=se=2:S==2&&(q=2),ae=b-q*P-q*R,be=A-se*k-se*I}let Fe=s?["A","B","C"][s]:"",dt=o<<24|l<<16|d<<8|c,ge=0;for(let q=0;q<32;q++)ge=(ge|(dt>>q&1)<<31-q)>>>0;let Ke=ge.toString(16);return a===1&&Ke==="2"&&(Ke="6"),{codecString:`hvc1.${Fe}${a}.${Ke}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[o,l,d,c],general_constraint_indicator_flags:[h,u,f,g,m,p],general_level_idc:v,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:F,min_spatial_segmentation_idc:O,chroma_format_idc:S,frame_rate:{fixed:j,fps:z/ie}},width:ae,height:be,pixelRatio:[U,Z]}}readPPS(e){let t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let s=t.readBoolean(),n=t.readBoolean(),a=1;return n&&s?a=0:n?a=3:s&&(a=2),{parallelismType:a}}matchSPS(e,t){return et(e).substring(3)===et(t).substring(3)}},xe=188,gs=class r{constructor(e,t,i,s){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._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){let i=r.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){let t=e.length,i=Math.min(xe*5,t-xe)+1,s=0;for(;s<i;){let n=!1,a=-1,o=0;for(let l=s;l<t;l+=xe)if(e[l]===71&&(t-l===xe||e[l+xe]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+xe*99,e.length-xe)+1)),n||(n=ms(e,l)===0),n&&o>1&&(a===0&&o>2||l+xe>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:el[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=r.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new $n(this.logger):null,this._audioTrack=r.createTrack("audio",s),this._id3Track=r.createTrack("id3"),this._txtTrack=r.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,e&&this.demux(e,0,a,n?.method==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i,s=!1,n=!1){s||(this.sampleAes=null);let a,o=this._videoTrack,l=this.videoIntegrityChecker,d=this._audioTrack,c=this._id3Track,h=this._txtTrack,u=i.iframe,f=o.pid,g=o.pesData,m=d.pid,p=c.pid,v=this._klvPid,T=d.pesData,E=c.pesData,S=null,b=null,A=this.pmtParsed,x=this._pmtId,R=e.length;if(this.remainderData&&(e=Ye(this.remainderData,e),R=e.length,this.remainderData=null),R<xe&&!n)return this.remainderData=e,{audioTrack:d,videoTrack:o,id3Track:c,textTrack:h};let P=Math.max(0,r.syncOffset(e));R-=(R-P)%xe,R<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,R,e.buffer.byteLength-R));let I=0;for(let D=P;D<R;D+=xe)if(e[D]===71){let F=!!(e[D+1]&64),G=ms(e,D),$=(e[D+3]&48)>>4,C;if($>1){if(C=D+5+e[D+4],C===D+xe)continue}else C=D+4;switch(G){case f:F&&(g&&!(l!=null&&l.isCorrupted)&&(a=Lt(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,h,a,!1,i)),g={data:[],size:0},l?.reset(f)),l?.handlePacket(e.subarray(D)),g&&(g.data.push(e.subarray(C,D+xe)),g.size+=D+xe-C);break;case m:if(u)break;if(F){if(T&&(a=Lt(T,this.logger)))switch(d.segmentCodec){case"aac":this.parseAACPES(d,a,i);break;case"mp3":this.parseMPEGPES(d,a);break;case"ac3":this.parseAC3PES(d,a);break}T={data:[],size:0}}T&&(T.data.push(e.subarray(C,D+xe)),T.size+=D+xe-C);break;case p:if(u)break;F&&(E&&(a=Lt(E,this.logger))&&this.parseID3PES(c,a),E={data:[],size:0}),E&&(E.data.push(e.subarray(C,D+xe)),E.size+=D+xe-C);break;case v:if(u)break;F&&(S&&(a=Lt(S,this.logger))&&this.parseKlvPES(c,a),S={data:[],size:0}),S&&(S.data.push(e.subarray(C,D+xe)),S.size+=D+xe-C);break;case 0:F&&(C+=e[C]+1),x=this._pmtId=uu(e,C);break;case x:{F&&(C+=e[C]+1);let M=fu(e,C,this.typeSupported,s,this.observer,this.logger,this.config,i);f=M.videoPid,f>0&&(o.pid=f,o.segmentCodec=M.segmentVideoCodec),m=M.audioPid,m>0&&(d.pid=m,d.segmentCodec=M.segmentAudioCodec),p=M.id3Pid,p>0&&(c.pid=p),v=M.klvPid,v>0&&(this._klvPid=v),b!==null&&!A&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${b}'. Backtracking to sync byte @${P} to parse all TS packets.`),b=null,D=P-188),A=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=G;break}}else I++;I>0&&Bn(this.observer,new Error(`Found ${I} TS packet/s that do not start with 0x47`),i,void 0,this.logger),o.pesData=g,d.pesData=T,c.pesData=E;let k={audioTrack:d,videoTrack:o,id3Track:c,textTrack:h};return n&&this.extractRemainingSamples(k,i),k}flush(e,t){let{remainderData:i}=this;this.remainderData=null;let s;return i?s=this.demux(i,0,t,!1,!0):s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s,t),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(e,t){let{audioTrack:i,videoTrack:s,id3Track:n,textTrack:a}=e,o=s.pesData,l=i.pesData,d=n.pesData,c=this.videoIntegrityChecker,h;if(o&&!(c!=null&&c.isCorrupted)&&(h=Lt(o,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,a,h,!0,t),s.pesData=null)):s.pesData=o,l&&(h=Lt(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,h,t);break;case"mp3":this.parseMPEGPES(i,h);break;case"ac3":this.parseAC3PES(i,h);break}i.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;d&&(h=Lt(d,this.logger))?(this.parseID3PES(n,h),n.pesData=null):n.pesData=d}demuxSampleAes(e,t,i,s){let n=this.demux(e,i,s,!0,!this.config.progressive),a=this.sampleAes=new us(this.observer,this.config,t);return this.decrypt(n,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Fn:e==="hevc"&&(this.videoParser=new Nn))}decrypt(e,t){return new Promise(i=>{let{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,i){let s=0,n=this.aacOverFlow,a=t.data;if(n){this.aacOverFlow=null;let u=n.missing,f=n.sample.unit.byteLength;if(u===-1)a=Ye(n.sample.unit,a);else{let g=f-u;n.sample.unit.set(a.subarray(0,u),g),e.samples.push(n.sample),s=n.missing}}let o,l;for(o=s,l=a.length;o<l-1&&!hs(a,o);o++);if(o!==s){let u,f=o<l-1;if(f?u=`AAC PES did not start with ADTS header,offset:${o}`:u="No ADTS header found in AAC PES",Bn(this.observer,new Error(u),i,f,this.logger),!f)return}Gl(e,this.observer,a,o,this.audioCodec);let d;if(t.pts!==void 0)d=t.pts;else if(n){let u=Vl(e.samplerate);d=n.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;o<l;)if(h=Hl(e,a,o,d,c),o+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;o<l-1&&!hs(a,o);o++);}parseMPEGPES(e,t){let i=t.data,s=i.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(Wl(i,a)){let l=Kl(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{let i=t.data,s=t.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=i.length,a=0,o=0,l;for(;o<n&&(l=zl(e,i,o,s,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=ce({},t,{type:this._videoTrack?Me.emsg:Me.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}parseKlvPES(e,t){var i;let s=(i=t.pts)!=null?i:t.dts;if(s===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}let n=t.data;if(n.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<n.length;){var o;if(a+16>n.length)break;let l=a;if(a+=16,a>=n.length)break;let d=n[a];a+=1;let c=0;if(d&128){let g=d&127;if(g===0||g>4||a+g>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let m=0;m<g;m++)c=c<<8|n[a+m];a+=g}else c=d;if(a+c>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let h=a+c,u=n.subarray(l,h),f={data:u,len:u.byteLength,pts:s,dts:(o=t.dts)!=null?o:s,type:Me.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(f),a=h}}};function ms(r,e){return((r[e+1]&31)<<8)+r[e+2]}function uu(r,e){return(r[e+10]&31)<<8|r[e+11]}function fu(r,e,t,i,s,n,a,o){let l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=(r[e+1]&15)<<8|r[e+2],c=e+3+d-4,h=(r[e+10]&15)<<8|r[e+11];for(e+=12+h;e<c;){let u=ms(r,e),f=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){Zs("ADTS AAC",n);break}case 15:l.audioPid===-1&&(l.audioPid=u);break;case 21:l.id3Pid===-1&&(l.id3Pid=u);break;case 219:if(!i){Zs("H.264",n);break}case 27:l.videoPid===-1&&(l.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=u,l.segmentAudioCodec="mp3");break;case 193:if(!i){Zs("AC-3",n);break}case 129:t.ac3?l.audioPid===-1&&(l.audioPid=u,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(f>0){let g=e+5,m=f;for(;m>2;){switch(r[g]){case 106:l.audioPid===-1&&(t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=u,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=u,n.log(`KLV metadata PID found: ${u}`));break}let v=r[g+1]+2;g+=v,m-=v}}break;case 194:case 135:return Bn(s,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:l.videoPid===-1&&(l.videoPid=u,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=f+5}return l}function Bn(r,e,t,i,s){s.warn(`parsing error: ${e.message}`),r.emit(y.ERROR,y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:t,error:e,reason:e.message})}function Zs(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Lt(r,e){let t=0,i,s,n,a,o,l=r.data;if(!r||r.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ye(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(s=(i[4]<<8)+i[5],s&&s>r.size-6)return null;let c=i[7];c&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,c&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let h=n+9;if(r.size<=h)return null;r.size-=h;let u=new Uint8Array(r.size);for(let f=0,g=l.length;f<g;f++){i=l[f];let m=i.byteLength;if(h)if(h>m){h-=m;continue}else i=i.subarray(h),m-=h,h=0;u.set(i,t),t+=m}return s&&(s-=n+3),{data:u,pts:a,dts:o,len:s}}return null}var $n=class{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;let t=ms(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let i=(e[3]&48)>>4;if(i===0)return;let s=e[3]&15,n=this.lastContinuityCounter;this.lastContinuityCounter=s;let a=(i&1)!=0;if((i&2)!=0&&e[4]!=0&&(e[5]&128)!=0||n<0)return;let d=a?n+1&15:n;if(s!==d){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${s}, Expected-CC=${d} Last-CC=${n}`),this.integrityState="cc-failed";return}if(e[1]&128){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}},Un=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)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(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)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(t===2)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(t===3)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]);break}}},ps,gu={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Js=new Uint8Array([0,0,0,0,0,0,0,0]),mu=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),pu=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),yu=new Uint8Array([0,0,0,0,0,0,0,0]),Xt=new Uint8Array([0,0,0,0,0,0,0,1]),ro=new Uint8Array([105,115,111,109]),vu=new Uint8Array([97,118,99,49]),Eu=new Uint8Array([0,0,0,1]),ft=class r{static box(e,...t){let i=8,s=t.length,n=s;for(;s--;)i+=t[s].byteLength;let a=new Uint8Array(i);for(Se(a,0,i),Se(a,4,e),s=0,i=8;s<n;s++)a.set(t[s],i),i+=t[s].byteLength;return a}static hdlr(e){return r.box(X.hdlr,gu[e])}static mdat(e){return r.box(X.mdat,e)}static mdhd(e,t){t*=e;let i=Math.floor(t/(nt+1)),s=Math.floor(t%(nt+1));return r.box(X.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return r.box(X.mdia,r.mdhd(e.timescale||0,e.duration||0),r.hdlr(e.type),r.minf(e))}static mfhd(e){return r.box(X.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?r.box(X.minf,r.box(X.smhd,yu),r.DINF,r.stbl(e)):r.box(X.minf,r.box(X.vmhd,pu),r.DINF,r.stbl(e))}static moof(e,t,i){return r.box(X.moof,r.mfhd(e),r.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=r.trak(e[t]);return r.box.apply(null,[X.moov,r.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(r.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=r.trex(e[t]);return r.box.apply(null,[X.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(nt+1)),s=Math.floor(t%(nt+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,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 r.box(X.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),s,n;for(s=0;s<t.length;s++)n=t[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return r.box(X.sdtp,i)}static stbl(e){return r.box(X.stbl,r.stsd(e),r.box(X.stts,Js),r.box(X.stsc,Js),r.box(X.stsz,mu),r.box(X.stco,Js))}static avc1(e){let t=[],i=[],s,n,a;for(s=0;s<e.sps.length;s++)n=e.sps[s],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s<e.pps.length;s++)n=e.pps[s],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));let o=r.box(X.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,d=e.height,c=e.pixelRatio[0],h=e.pixelRatio[1];return r.box(X.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,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,r.box(X.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r.box(X.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){let t=e.config,i=t.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return r.box(X.mp4a,r.audioStsd(e),r.box(X.esds,r.esds(e)))}static mp3(e){return r.box(X[".mp3"],r.audioStsd(e))}static ac3(e){return r.box(X["ac-3"],r.audioStsd(e),r.box(X.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return r.box(X.stsd,Xt,r.mp4a(e));if(t==="ac3"&&e.config)return r.box(X.stsd,Xt,r.ac3(e));if(t==="mp3"&&e.codec==="mp3")return r.box(X.stsd,Xt,r.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return r.box(X.stsd,Xt,r.avc1(e));if(t==="hevc"&&e.vps)return r.box(X.stsd,Xt,r.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,a=Math.floor(i/(nt+1)),o=Math.floor(i%(nt+1));return r.box(X.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,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,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=r.sdtp(e),s=e.id,n=Math.floor(t/(nt+1)),a=Math.floor(t%(nt+1));return r.box(X.traf,r.box(X.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),r.box(X.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),r.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,r.box(X.trak,r.tkhd(e),r.mdia(e))}static trex(e){let t=e.id;return r.box(X.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i=e.samples||[],s=i.length,n=12+16*s,a=new Uint8Array(n),o,l,d,c,h,u;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)l=i[o],d=l.duration,c=l.size,h=l.flags,u=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return r.box(X.trun,a)}static initSegment(e){let t=r.moov(e);return Ye(r.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],s=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),s-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),a=n.length;for(let g=0;g<i.length;g+=1){a+=3;for(let m=0;m<i[g].length;m+=1)a+=2+i[g][m].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=i.length-1;for(let g=0;g<i.length;g+=1){o.set(new Uint8Array([32+g|(g===l?128:0),0,i[g].length]),a),a+=3;for(let m=0;m<i[g].length;m+=1)o.set(new Uint8Array([i[g][m].length>>8,i[g][m].length&255]),a),a+=2,o.set(i[g][m],a),a+=i[g][m].length}let d=r.box(X.hvcC,o),c=e.width,h=e.height,u=e.pixelRatio[0],f=e.pixelRatio[1];return r.box(X.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,c>>8&255,c&255,h>>8&255,h&255,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]),d,r.box(X.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r.box(X.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,f>>24,f>>16&255,f>>8&255,f&255])))}};ps=ft;ft.FTYP=ps.box(X.ftyp,ro,Eu,ro,vu);ft.DINF=ps.box(X.dinf,ps.box(X.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var Xl=9e4;function Xr(r,e,t=1,i=!1){let s=r*e*t;return i?Math.round(s):s}function Tu(r,e,t=1,i=!1){return Xr(r,e,1/t,i)}function Qt(r,e=!1){return Xr(r,1e3,1/Xl,e)}function Su(r,e=1){return Xr(r,Xl,1/e)}function ao(r){let{baseTime:e,timescale:t,trackId:i}=r;return`${e/t} (${e}/${t}) trackId: ${i}`}var bu=10*1e3,Au=1024,xu=1152,Iu=1536,Gn=8589934592;function oo(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1,paddingValue:0}}}var Ht=class extends Oe{constructor(e,t,i,s){super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&ao(t)} > ${e&&ao(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e[0].pts,s=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=Ve(o,i),l=o-n),l>0?n:o},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,n,a,o,l,d){let c,h,u,f,g,m,p=n,v=n,E=!d.iframe&&e.pid>-1,S=t.pid>-1,b=t.samples.length,A=e.samples.length>0,x=o&&b>0||b>1;if((!E||A)&&(!S||x)||this.ISGenerated||o){if(this.ISGenerated){var P,I,k,D;let C=this.videoTrackConfig;(C&&(t.width!==C.width||t.height!==C.height||((P=t.pixelRatio)==null?void 0:P[0])!==((I=C.pixelRatio)==null?void 0:I[0])||((k=t.pixelRatio)==null?void 0:k[1])!==((D=C.pixelRatio)==null?void 0:D[1]))||!C&&x||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,n,a));let F=this.isVideoContiguous,G=-1,$;if(x&&(G=Lu(t.samples),!F&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,G>0){this.warn(`Dropped ${G} out of ${b} video samples due to a missing keyframe`);let C=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(G),t.dropped+=G,v+=(t.samples[0].pts-C)/t.inputTimeScale,$=v}else G===-1&&(this.warn(`No keyframe found out of ${b} video samples`),m=!1);if(this.ISGenerated){if(A&&x&&n){let C=this.getVideoStartPts(t.samples),w=(Ve(e.samples[0].pts,C)-C)/t.inputTimeScale;p+=Math.max(0,w),v+=Math.max(0,-w)}if(A){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,a)),h=this.remuxAudio(e,p,this.isAudioContiguous,a,S||x||l===H.AUDIO?v:void 0,d),x){let C=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,a)),c=this.remuxVideo(t,v,F,C,d)}}else x&&(c=this.remuxVideo(t,v,F,0,d));c&&(c.firstKeyFrame=G,c.independent=G!==-1,c.firstKeyFramePTS=$)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(g=Ql(i,n,this._initPTS,this._initDTS)),s.samples.length&&(f=Zl(s,n,this._initPTS))),{audio:h,video:c,initSegment:u,independent:m,text:f,id3:g}}computeInitPts(e,t,i,s){let n=Math.round(i*t),a=Ve(e,n);if(a<n)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${s}`);a<n;)a+=Gn;return a-n}generateIS(e,t,i,s){let n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS,c=!d||s,h="audio/mp4",u,f,g,m=-1;if(c&&(u=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):ft.initSegment([e]),metadata:{channelCount:e.channelCount}},c){m=e.id,g=e.inputTimeScale;let p=this.computeInitPts(n[0].pts,g,i,"audio");(!d||g!==d.timescale||i===0&&p<d.baseTime)&&(u=f=p)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:ft.initSegment([t]),metadata:{width:t.width,height:t.height}},c){m=t.id,g=t.inputTimeScale;let p=this.getVideoStartPts(a),v=Ve(a[0].dts,p),T=this.computeInitPts(v,g,i,"video"),E=this.computeInitPts(p,g,i,"video");(!d||g!==d.timescale||B(u)||i===0&&E<d.baseTime)&&(f=Math.min(f,T),u=Math.min(u,T))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,c&&B(u)?(d&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${u/g} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${u/g} (${u}/${g}) trackId: ${m}`),this._initPTS={baseTime:u,timescale:g,trackId:m},this._initDTS={baseTime:f,timescale:g,trackId:m}):u=g=void 0,{tracks:l,initPTS:u,timescale:g,trackId:m}}remuxVideo(e,t,i,s,n){let a=e.inputTimeScale,o=e.samples,l=[],d=o.length,c=this._initPTS,h=c.baseTime*a/c.timescale,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m,p,v=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,E=!1;if(!i||u===null){let O=h+t*a,U=o[0].pts-Ve(o[0].dts,o[0].pts);ei()&&u!==null&&Math.abs(O-U-(u+h))<15e3?i=!0:u=O-U-h}let S=u+h;for(let O=0;O<d;O++){let U=o[O];U.pts=Ve(U.pts,S),U.dts=Ve(U.dts,S),U.dts<o[O>0?O-1:O].dts&&(E=!0)}E&&o.sort(function(O,U){let Z=O.dts-U.dts,j=O.pts-U.pts;return Z||j}),m=o[0].dts,p=o[o.length-1].dts;let b=p-m,A=b?Math.round(b/(d-1)):g||e.inputTimeScale/30;if(i){let O=m-S,U=O>A,Z=O<-1;if((U||Z)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Qt(O,!0)} ms (${O}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Qt(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Z||S>=o[0].pts||ei())){m=S;let j=o[0].pts-O;if(U)o[0].dts=m,o[0].pts=j;else{let ie=!0;for(let z=0;z<o.length&&!(o[z].dts>j&&ie);z++){let ne=o[z].pts;if(o[z].dts-=O,o[z].pts-=O,z<o.length-1){let ee=o[z+1].pts,ae=o[z].pts,be=ee<=ae,Fe=ee<=ne;ie=be==Fe}}}this.log(`Video: Initial PTS/DTS adjusted: ${Qt(j,!0)}/${Qt(m,!0)}, delta: ${Qt(O,!0)} ms`)}}m=Math.max(0,m);let x=0,R=0,P=m;for(let O=0;O<d;O++){let U=o[O],Z=U.units,j=Z.length,ie=0;for(let z=0;z<j;z++)ie+=Z[z].data.length;R+=ie,x+=j,U.length=ie,U.dts<P?(U.dts=P,P+=A/4|0||1):P=U.dts,v=Math.min(U.pts,v),T=Math.max(U.pts,T)}p=o[d-1].dts;let I=R+4*x+8,k;try{k=new Uint8Array(I)}catch(O){this.observer.emit(y.ERROR,y.ERROR,{type:W.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:O,bytes:I,reason:`fail allocating video mdat ${I}`});return}Se(k,0,I),Se(k,4,X.mdat);let D=!1,F=Number.POSITIVE_INFINITY,G=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let O=0;O<d;O++){let U=o[O],Z=U.units,j=0;for(let ne=0,ee=Z.length;ne<ee;ne++){let ae=Z[ne],be=ae.data,Fe=ae.data.byteLength;Se(k,f,Fe),f+=4,k.set(be,f),f+=Fe,j+=4+Fe}let ie;if(O<d-1)g=o[O+1].dts-U.dts,ie=o[O+1].pts-U.pts;else{let ne=this.config,ee=O>0?U.dts-o[O-1].dts:A;if(ie=O>0?U.pts-o[O-1].pts:A,ne.stretchShortVideoTrack&&this.nextAudioTs!==null){let ae=Math.floor(ne.maxBufferHole*a),be=(s?v+s*a:this.nextAudioTs+h)-U.pts;be>ae?(g=be-ee,g<0?g=ee:D=!0,this.log(`It is approximately ${be/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=ee}else g=ee}let z=Math.round(U.pts-U.dts);if(F=Math.min(F,g),$=Math.max($,g),G=Math.min(G,ie),C=Math.max(C,ie),!i&&O===0&&z>g){let ne=Math.round(z/A)*A;ne-z===1&&(this.log(`pad first CTS ${z} -> ${ne} of sn: ${n.sn}`),z=ne)}l.push(oo(U.key,g,j,z))}if(l.length){let O=ei();if(O){if(O<70){let U=l[0].flags;U.dependsOn=2,U.isNonSync=0}}else if(Vc()&&C-G<$-F&&A/$<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let U=m;for(let Z=0,j=l.length;Z<j;Z++){let ie=U+l[Z].duration,z=U+l[Z].cts;if(Z<j-1){let ne=ie+l[Z+1].cts;l[Z].duration=ne-z}else l[Z].duration=Z?l[Z-1].duration:A;l[Z].cts=0,U=ie}}}g=D||!g?A:g;let M=p+g;this.nextVideoTs=u=M-h,this.videoSampleDuration=g,this.isVideoContiguous=!0,n.iframe&&(l.length===1?(l[0].duration=g=n.duration*a,this.nextVideoTs=u=m+g-h):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));let K={data1:ft.moof(n.sn,m,ce(e,{samples:l})),data2:k,startPTS:(v-h)/a,endPTS:(T+g-h)/a,startDTS:(m-h)/a,endDTS:u/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,K}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return xu;case"ac3":return Iu;default:return Au}}remuxAudio(e,t,i,s,n,a){let o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,d=o/l,c=this.getSamplesPerFrame(e),h=c*d,u=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],m=n!==void 0,p=e.samples,v=f?0:8,T=this.nextAudioTs||-1,E=u.baseTime*o/u.timescale,S=E+t*o;if(this.isAudioContiguous=i=i||p.length&&T>0&&(s&&Math.abs(S-(T+E))<9e3||Math.abs(Ve(p[0].pts,S)-(T+E))<20*h),p.forEach(function(M){M.pts=Ve(M.pts,S)}),!i||T<0){let M=p.length;if(p=p.filter(w=>w.pts>=0),M!==p.length&&this.warn(`Removed ${p.length-M} of ${M} samples (initPTS ${E} / ${o})`),!p.length)return;n===0?T=0:s&&!m?T=Math.max(0,S-E):T=p[0].pts-E}if(e.segmentCodec==="aac"){let M=this.config.maxAudioFramesDrift;for(let w=0,N=T+E;w<p.length;w++){let K=p[w],O=K.pts,U=O-N,Z=Math.abs(1e3*U/o);if(U<=-M*h&&m)w===0&&(this.warn(`Audio frame @ ${(O/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*U/o)} ms.`),this.nextAudioTs=T=O-E,N=O);else if(U>=M*h&&Z<bu&&m){let j=Math.round(U/h);for(N=O-j*h;N<0&&j&&h;)j--,N+=h;w===0&&(this.nextAudioTs=T=N-E),this.warn(`Injecting ${j} audio frames @ ${((N-E)/o).toFixed(3)}s due to ${Math.round(1e3*U/o)} ms gap.`);for(let ie=0;ie<j;ie++){let z=Un.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);z||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),z=K.unit.subarray()),p.splice(w,0,{unit:z,pts:N}),N+=h,w++}}K.pts=N,N+=h}}let b=null,A=null,x,R=0,P=p.length;for(;P--;)R+=p[P].unit.byteLength;for(let M=0,w=p.length;M<w;M++){let N=p[M],K=N.unit,O=N.pts;if(A!==null){let Z=g[M-1];Z.duration=Math.round((O-A)/d)}else if(i&&e.segmentCodec==="aac"&&(O=T+E),b=O,R>0){R+=v;try{x=new Uint8Array(R)}catch(Z){this.observer.emit(y.ERROR,y.ERROR,{type:W.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:Z,bytes:R,reason:`fail allocating audio mdat ${R}`});return}f||(Se(x,0,R),Se(x,4,X.mdat))}else return;x&&x.set(K,v);let U=K.byteLength;v+=U,g.push(oo(!0,c,U,0)),A=O}let I=g.length;if(!I)return;let k=g[g.length-1];T=A-E,this.nextAudioTs=T+d*k.duration;let D=f?new Uint8Array(0):ft.moof(e.sequenceNumber++,b/d,ce({},e,{samples:g}));e.samples=[];let F=(b-E)/o,G=this.nextAudioTs/o,C={data1:D,data2:x,startPTS:F,endPTS:G,startDTS:F,endDTS:G,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,C}};function Ve(r,e){let t;if(e===null)return r;for(e<r?t=-Gn:t=Gn;Math.abs(r-e)>4294967296;)r+=t;return r}function Lu(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function Ql(r,e,t,i){let s=r.samples.length;if(!s)return;let n=r.inputTimeScale;for(let o=0;o<s;o++){let l=r.samples[o];l.pts=Ve(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=Ve(l.dts-i.baseTime*n/i.timescale,e*n)/n}let a=r.samples;return r.samples=[],{samples:a}}function Zl(r,e,t){let i=r.samples.length;if(!i)return;let s=r.inputTimeScale;for(let a=0;a<i;a++){let o=r.samples[a];o.pts=Ve(o.pts-t.baseTime*s/t.timescale,e*s)/s}r.samples.sort((a,o)=>a.pts-o.pts);let n=r.samples;return r.samples=[],{samples:n}}var Vn=class extends Oe{constructor(e,t,i,s){super("passthrough-remuxer",s),this.observer=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.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.decryptdata=s,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,i){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:a,video:o}=this.initData=i||nl(e);if(t)Pc(e,t);else{let d=a||o;d!=null&&d.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${d.codec}")!`)}a&&(s=lo(a,he.AUDIO,this)),o&&(n=lo(o,he.VIDEO,this));let l={};a&&o?l.audiovideo={container:"video/mp4",codec:s+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:s,encrypted:a.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,i,s,n,a,o,l,d,c,h){var u,f;let{initPTS:g,lastEndTime:m}=this,p={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};B(m)||(m=this.lastEndTime=n||0);let v=t.samples;if(!v.length)return p;let T=this.pendingInitSegment;T&&(this.pendingInitSegment=void 0,this.generateInitSegment(T,this.decryptdata,c));let E={initPTS:void 0,timescale:void 0,trackId:void 0},S=this.initData;if((u=S)!=null&&u.length||(this.generateInitSegment(v),S=this.initData),!((f=S)!=null&&f.length))return this.warn("Failed to generate initSegment."),p;if(d.iframe&&S.audio&&S.video){var b;let q=(b=this.initTracks)==null||(b=b.audiovideo)==null?void 0:b.initSegment,se=q?bc(q):null;if(se){var A;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(se,this.decryptdata),(A=this.initData)!=null&&A.length&&(S=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(E.tracks=this.initTracks,p.initSegment=E,this.emitInitSegment=!1);let x=d.iframe,R=h&&(!x||h.includeSampleDetails)?h.tracks:Cc(v,S,d,this,x),P=S.audio?R[S.audio.id]:null,I=S.video?R[S.video.id]:null,k=!!S.audio,D=!!S.video,F="";k&&(F+="audio"),D&&(F+="video");let G=Mi(I,1/0),$=Mi(P,1/0),C=Mi(I,0,!0),M=Mi(P,0,!0),w=n,N=0;I&&P&&S.audio&&($>C||G>M)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${G}-${C} a: ${$}-${M}}`,I,P);let K=!!P&&(!I||!g&&$<G||!!g&&g.trackId===S.audio.id),O=K?P:I;if(!O)return this.log(`No media samples found in ${l} ${d.level} ${d.part===-1?"":`part: ${d.part} of`} sn: ${d.sn} at playlist time: ${n}`),p;let U=v,Z,j;if(I&&I.sampleCount>=1&&S.video&&d.iframe){let{trun:q,start:se}=I,re=q.length===1,Ae=q.length?re?q[0].samples:q[0].samples.concat(...q.slice(1).map(Te=>Te.samples)):[];if(Ae.length){let Te=q[0],Ce=Te;for(let $e=q.length;$e--;)if(q[$e].samples.length){Ce=q[$e];break}let je=Ce.lastSampleDurationOffset,{defaultSampleDurationOffset:It}=Te,Pe=Math.abs(d.duration-(C-G))>.05,we=Ae.length<I.sampleCount;if(!(Pe||we||this.videoOnlyRemux||!re))N=C-G;else{let $e=we?Ce.sampleOffset+Ce.samples.reduce((ze,ma)=>ze+ma.size,0):void 0,De=Pe?d.duration:C-G,gt=Pu(Ae,De*S.video.timescale,je,It),ct=Ac(v,S.video.id,Ae.length,$e,gt);ct?(U=ct,j=Ru(se,Ae)):this.warn(`IFrame remux skipped (sn ${d.sn}); using native sample duration`),N=ct&&gt?De:C-G}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${q.length})`),N=C-G}else N=K?M-$:C-G;if(this.videoOnlyRemux&&U===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${d.sn})`),p;let ie=O.timescale,z=O.start-n*ie,ne=K?S.audio.id:S.video.id;if(w=O.start/ie,(a||!g)&&(_u(g,w,n,N)||ie!==g.timescale)){let q=!1,se=K?"audio":"video";if(g){let re=n!==0?w/n:1+w/1;q=w>=0&&Math.abs(1-re)<.001,this.log(`${se} timestamps in track ${ne} at playlist time: ${a?"":"~"}${n} maps to ${w} with initPTS: ${g.baseTime/g.timescale} (${z/ie-g.baseTime/g.timescale}s diff) (${F}) drift estimate: ${re} ${q?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}q||(this.log(`Found initPTS in ${se} track ${ne} at playlist time: ${n} offset: ${w-n} (${z}/${ie})`),g=null,E.initPTS=z,E.timescale=ie,E.trackId=ne)}g?(E.initPTS=g.baseTime,E.timescale=g.timescale,E.trackId=g.trackId):((!E.timescale||E.trackId===void 0||E.initPTS===void 0)&&(this.warn("Could not set initPTS"),E.initPTS=w,E.timescale=1,E.trackId=-1),this.initPTS=g={baseTime:E.initPTS,timescale:E.timescale,trackId:E.trackId});let ee=w-g.baseTime/g.timescale,ae=ee+N,be=D&&O?.ptsMin!==void 0?O.ptsMin/O.timescale-g.baseTime/g.timescale:ee,Fe=j!==void 0&&I?j/I.timescale-g.baseTime/g.timescale:D&&O!=null&&O.ptsMax?O.ptsMax/O.timescale-g.baseTime/g.timescale:ae;N>0?this.lastEndTime=ae:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let dt=(S.audio?S.audio.encrypted:!1)||(S.video?S.video.encrypted:!1),ge={data1:U,data2:Z,startPTS:be,startDTS:ee,endPTS:Fe,endDTS:ae,type:F,hasAudio:k,hasVideo:D,nb:1,dropped:0,encrypted:dt};p.audio=k&&!D?ge:void 0,p.video=D?ge:void 0;let Ke=this.isVideoContiguous,tt=I?.sampleCount;if(tt){let q=I.keyFrameIndex,se=q!==-1;ge.nb=tt,ge.dropped=q===0||Ke?0:se?q:tt,ge.independent=se,ge.firstKeyFrame=q,se&&I.keyFrameStart&&(ge.firstKeyFramePTS=(I.keyFrameStart-g.baseTime)/g.timescale),Ke||(p.independent=se),this.isVideoContiguous||(this.isVideoContiguous=se),ge.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${q}/${tt} dropped: ${ge.dropped} start: ${ge.firstKeyFramePTS||"NA"}`)}return p.initSegment=E,p.id3=Ql(i,n,g,g),s.samples.length&&(p.text=Zl(s,n,g)),p}};function Mi(r,e,t=!1){return r?.start!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function Ru(r,e){let t=r,i=r;for(let s=0;s<e.length;s++){let{cts:n,duration:a}=e[s];i=Math.max(i,t+(n||0)+a),t+=a}return i}function Pu(r,e,t,i){if(t!==void 0){let n=r[r.length-1],a=e;for(let o=0;o<r.length-1;o++)a-=r[o].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:t,value:a}}if(i===void 0)return;let s=Math.round(e/r.length);for(let n=0;n<r.length;n++)r[n].duration=s;return{durationOffset:i,value:s}}function _u(r,e,t,i){if(r===null)return!0;let s=Math.max(i,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>=s}function lo(r,e,t){let i=r.codec;return i&&i.length>4?i:e===he.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Qi(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):i==="mjpg"?i:(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var vt;try{vt=self.performance.now.bind(self.performance)}catch{vt=Date.now}var qi=[{demux:On,remux:Vn},{demux:gs,remux:Ht},{demux:Cn,remux:Ht},{demux:Mn,remux:Ht}];qi.splice(2,0,{demux:wn,remux:Ht});var ys=class{constructor(e,t,i,s,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){if(!this.observer)return Oi(i);let n=i.transmuxing;n.executeStart=vt();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);let{contiguous:d,discontinuity:c,trackSwitch:h,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:m,videoCodec:p,defaultInitPts:v,duration:T,initSegmentData:E}=l,S=ku(a,t);if(S&&Vt(S.method)){let R=this.getDecrypter(),P=qr(S.method);return this.asyncResult=!0,this.decryptionPromise=R.decrypt(a,S.key.buffer,S.iv.buffer,P,i.decryptRange).then(I=>{let k=this.push(I,null,i);return this.decryptionPromise=null,k}),this.decryptionPromise}let b=this.needsProbing(c,h);if(b){let R=i.iframe&&E&&gs.probe(E,this.logger)?E:a,P=this.configureTransmuxer(R);if(P)return this.logger.warn(`[transmuxer] ${P.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:P,reason:P.message}),n.executeEnd=vt(),Oi(i)}(c||h||g||b)&&this.resetInitSegment(E,m,p,T,t,i),(c||g||b)&&this.resetInitialTimestamp(v),d||this.resetContiguity();let A=this.transmux(a,S,f,u,i);this.asyncResult=vi(A);let x=this.currentTransmuxState;return x.contiguous=!0,x.discontinuity=!1,x.trackSwitch=!1,n.executeEnd=vt(),A}flush(e){let t=e.transmuxing;t.executeStart=vt();let{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=s;if(i){let h=i.flush();h&&a.push(this.push(h.buffer,null,e))}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=vt();let h=[Oi(e)];return this.asyncResult?Promise.resolve(h):h}let c=l.flush(o,e);return vi(c)?(this.asyncResult=!0,c.then(h=>(this.flushRemux(a,h,e),a))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){if(!this.remuxer)return;let{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);let c=this.remuxer.remux(s,n,a,o,d,l,!0,this.id,i,t.initData,t.sampleData);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=vt()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n,a){let{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,i,s,n,a),l.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,i,s,n){let a;return t?.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,s,n):a=this.transmuxUnencrypted(e,i,s,n),a}transmuxUnencrypted(e,t,i,s){let{demuxer:n,remuxer:a}=this;if(!n||!a)return Oi(s);let o=n.demux(e,t,s,!1,!this.config.progressive),{audioTrack:l,videoTrack:d,id3Track:c,textTrack:h}=o;return{remuxResult:a.remux(l,d,c,h,t,i,!1,this.id,s,o.initData,o.sampleData),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer?this.demuxer.demuxSampleAes(e,t,i,n).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id,n,a.initData,a.sampleData),chunkMeta:n})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:s}=this;if(!i)return;let n;try{for(let h=0,u=qi.length;h<u;h++){var a;if((a=qi[h].demux)!=null&&a.probe(e,this.logger)){n=qi[h];break}}}catch(h){return h}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,d=n.demux,c=n.remux;(!o||!(o instanceof d))&&(this.logger.log(`Using ${d.name}`),this.demuxer=new d(i,t,s,this.logger),this.probe=d.probe),(!l||!(l instanceof c))&&(this.logger.log(`Using ${c.name}`),this.remuxer=new c(i,t,s,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new fi(this.config)),e}};function ku(r,e){let t=null;return r.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var Oi=r=>({remuxResult:{},chunkMeta:r});function vi(r){return"then"in r&&r.then instanceof Function}var Hn=class{constructor(e,t,i,s,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}},Kn=class{constructor(e,t,i,s,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=a}},co=0,vs=class{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=co++,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=l=>{let d=l.data,c=this.hls;if(!(!c||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var h;let u=(h=this.workerContext)==null?void 0:h.objectURL;u&&self.URL.revokeObjectURL(u);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{c.logger[d.data.logType]&&c.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,c.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;let a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===y.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d)};this.observer=new Yr,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);let o=Ra(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(n.workerPath||jh()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Xh(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=zh());let{worker:c}=this.workerContext;c.addEventListener("message",this.onWorkerMessage),c.addEventListener("error",this.onWorkerError),c.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:fe(n)})}catch(c){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,c),this.terminateWorker(),this.error=null,this.transmuxer=new ys(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new ys(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=co++;let t=this.hls.config,i=Ra(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:fe(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Qh(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,n,a,o,l,d,c){var h,u;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:g}=this,m=a?a.start:n.start,p=n.decryptdata,v=this.frag,T=v?n.cc!==v.cc:!0,E=v?d.level!==v.level:!0,S=v?d.sn-v.sn:-1,b=this.part?d.part-this.part.index:-1,A=S===0&&d.id>1&&d.id===v?.stats.chunkCount,x=!E&&(S===1||S===0&&(b===1||A&&b<=0)),R=self.performance.now();(E||S||n.stats.parsing.start===0)&&(n.stats.parsing.start=R),a&&(b||!x)&&(a.stats.parsing.start=R);let P=!(v&&((h=n.initSegment)==null?void 0:h.url)===((u=v.initSegment)==null?void 0:u.url)),I=new Kn(T,x,l,E,m,P);if(!x||T||P){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id} playlist: ${d.level} id: ${d.id}
16
+ ${t.m3u8}`)}function Ol(r,e,t=!0,i){let s=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,a=s>=0,o=0;if(a&&s<n.length)o=n[s].start,i?.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===r.endSN+1)o=r.fragmentEnd,i?.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=r.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=r.fragmentStart,i?.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return Hh(e,o),o}function Hh(r,e){if(e){let t=r.fragments;for(let i=r.skippedSegments;i<t.length;i++)t[i].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function Fl(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){let i=r.fragments;if(i.length&&t*4>e){let n=i[i.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Nl(r,e,t){var i;if(!r)return null;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,((i=s)==null?void 0:i.sn)===e)?s:t&&e<r.startSN&&t.sn===e?t:null}function so(r,e,t){return r?Bl(r.partList,e,t):null}function Bl(r,e,t){if(r)for(let i=r.length;i--;){let s=r[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function $l(r){r.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(s=>{s.level=t,s.initSegment&&(s.initSegment.level=t)})})}function Kh(r,e){return r!==e&&e?no(r)!==no(e):!1}function no(r){return r.replace(/\?[^?]*$/,"")}function ii(r,e){for(let i=0,s=r.length;i<s;i++){var t;if(((t=r[i])==null?void 0:t.cc)===e)return r[i]}return null}function qh(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function ro(r,e){let t=r.start+e;r.setStart(t)}function Ul(r,e){let t=e.fragments;for(let i=0,s=t.length;i<s;i++)ro(t[i],r);e.fragmentHint&&ro(e.fragmentHint,r),e.alignedSliding=!0}function os(r,e,t){r&&(Wh(e,r,t),e.alignedSliding||Yh(e,r,t),!e.alignedSliding&&!e.skippedSegments&&Ol(r,e,!1,t))}function Wh(r,e,t){if(!qh(e,r))return;let i=Math.min(e.endCC,r.endCC),s=ii(e.fragments,i),n=ii(r.fragments,i);if(!s||!n)return;let a=s.start-n.start;t.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),Ul(a,r)}function Yh(r,e,t){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;let i=r.fragments,s=e.fragments;if(!i.length||!s.length)return;let n,a,o=Math.min(e.endCC,r.endCC);e.startCC<o&&r.startCC<o&&(n=ii(s,o),a=ii(i,o)),(!n||!a)&&(n=s[Math.floor(s.length/2)]||s.filter(u=>!!u)[0],a=ii(i,n.cc)||i[Math.floor(i.length/2)]);let l=n.programDateTime,d=a.programDateTime;if(!l||!d)return;let c=(d-l)/1e3;if(Math.abs(c)>Math.max(60,r.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(c)} > ${r.totalduration})`);return}let h=c-(a.start-n.start);t.log(`Aligning playlists using PDT (diff: ${h})`),Ul(h,r)}function de(r,e,t){le(r,e,t),r.addEventListener(e,t)}function le(r,e,t){r.removeEventListener(e,t)}function ls(r){let e="",t=r.length;for(let i=0;i<t;i++)e+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return e}var _={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},mi=class extends ss{constructor(e,t,i,s,n){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=_.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:d,state:c}=this,h=l?l.currentTime:0,u=J.bufferInfo(d||l,h,a.maxBufferHole),f=u.len;if(this.log(`Media seeking to ${h}, state: ${c}, ${f?"in":"out of"} buffer`),this.state===_.ENDED)this.resetLoadingState();else if(o){let m=a.maxFragLookUpTolerance,p=o.start-m,v=o.start+o.duration+m;if(!f||v<u.start||p>u.end){let T=h<p,E=h>v;(T||E)&&(o.loader&&(E||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${T?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);let m=this.lastCurrentTime;if(h>m&&(this.lastCurrentTime=h),!this.loadingParts){let p=Math.max(u.end,h),v=this.shouldLoadParts(this.getLevelDetails(),p);v&&(this.log(`LL-Part loading ON after seeking to ${h} with buffer @${p}`),this.loadingParts=v)}}let g=!J.isBuffered(l,h);(!this.hls.hasEnoughToStart||g)&&(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,g&&(this.startPosition=h)),f<1&&this.state===_.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new ts(e.config),this.initFragmentLoader=new ts(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new fi(e.config)}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===_.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=_.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let i=this.getLevelDetails();return i!=null&&i.live?(this.hls.liveSyncPosition||i.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=J.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>s&&a<t.edge||this.media.currentTime<e.start)return!1;let l=t.partList;if(l!=null&&l.length){let c=l[l.length-1];return J.isBuffered(this.media,c.start+c.duration/2)}let d=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(d.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;de(i,"seeking",this.onMediaSeeking),de(i,"ended",this.onMediaEnded);let s=this.config;this.levels&&s.autoStartLoad&&this.state===_.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let i=!!t.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),le(s,"seeking",this.onMediaSeeking),le(s,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=_.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){let s=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)} was dropped during download.`),this.fragmentTracker.removeFragment(a);return}let o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)} chunk: ${o}`),this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,i,s).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===_.FRAG_LOADING||!this.fragCurrent&&a===_.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=_.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(y.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===_.STOPPED||this.state===_.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${n?.message||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===ye.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===ye.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,i=e.fragments[e.fragments.length-1];if(i.endList&&!t.isEndListAppended(this.playlistType)){let s=t.getPartialFragment(i.end);s&&(t.removeFragment(s),t.fragBuffered(i,!0))}t.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let s={startOffset:e,endOffset:t,type:i};this.hls.trigger(y.BUFFER_FLUSHING,s)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(i=>{var s;let n=i.frag;if(!this.levels||!pn(n,(s=this.fragCurrent)==null?void 0:s.initSegment))throw new We({type:W.NETWORK_ERROR,details:L.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:n,networkDetails:null});return i}).then(i=>{let{frag:s,payload:n}=i,a=s.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&Vt(a.method)){let o=self.performance.now(),{decryptRange:l}=is(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Yr(a.method),l).catch(d=>{throw t.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:s}),this.fragmentLoader.abort(),d}).then(d=>{let c=self.performance.now();return t.trigger(y.FRAG_DECRYPTED,{frag:s,part:null,payload:d,stats:{tstart:o,tdecrypt:c}}),i.payload=d,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)})}completeInitSegmentLoad(e){let t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){let{initSegment:t}=e;if(!this.bitrateTest&&ve(e)&&t&&!t.data){var i;return(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(n=>{throw this.state===_.STOPPED||this.state===_.ERROR||("data"in n&&(n.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(n)),this.resetFragmentLoading(e)),n})}}unhandledEncryptionError(e,t){var i,s;let n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(s=n.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(y.ERROR,{type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!pn(e,t)}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?ls(J.getBuffered(i)):"(detached)"})`),ve(e)){var s;if(e.type!==H.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=_.IDLE;return}}let n=(s=this.levels)==null?void 0:s[e.level];n!=null&&n.fragmentError&&(t||this.fragmentTracker.getState(e)!==ye.PARTIAL)&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0,e.stats.retry=0)}this.state=_.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let i=e.frag,{part:s,partsLoaded:n}=e,a=!n||n.length===0||n.some(d=>!d),{decryptRange:o}=is(i,s),l=new gi(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a,i.duration,this.iframesOnly,o);this.log(`load complete ${i.type} sn: ${i.sn}${s?" part: "+s.index:""} of ${this.fragInfo(i,!1,s)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,i){var s;let n=null;return e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=_.KEY_LOADING,n=this.keyLoader.load(e,i).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(y.KEY_LOADED,a),this.state===_.KEY_LOADING&&(this.state=_.IDLE),a}),this.hls.trigger(y.KEY_LOADING,{frag:e})):e.encrypted||(n=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),n&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),n}_doFragLoad(e,t,i=null,s){this.fragCurrent=e;let n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=this.fragPrevious;if(!Zt(e,a)){let f=this.shouldLoadParts(t.details,e.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${a?.sn}->${e.sn}`),this.loadingParts=f)}if(i=Math.max(e.start,i||0),this.loadingParts){let f=n.partList;if(f&&s){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);let g=this.getNextPart(f,e,i);if(g>-1){let m=f[g];if(e=this.fragCurrent=m.fragment,!Zt(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,m)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(m,t.details))return Promise.resolve(null);let p=this.loadKeyFor(e,n);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${g}/${f.length-1}) of ${this.fragInfo(e,!1,m)} cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${i}${m.byteRange.length?` range:${m.byteRange.join("-")}`:""}`),this.nextLoadPosition=m.start+m.duration,this.state=_.FRAG_LOADING;let v,T=this.loadInitSegmentIfNeeded(e);if(p||T){let E=!!p;v=Promise.all([p,T]).then(([S])=>E&&(!S||this.fragContextChanged(S.frag))?null:this.doFragPartsLoad(e,m,t,s)).catch(S=>this.handleFragLoadError(S))}else v=this.doFragPartsLoad(e,m,t,s).catch(E=>this.handleFragLoadError(E));return this.hls.trigger(y.FRAG_LOADING,{frag:e,part:m,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):v}else if(!e.url||this.loadedEndOfParts(f,i))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${e.sn} loaded parts: ${(o=n.partList)==null?void 0:o.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let l=this.loadInitSegmentIfNeeded(e),d=this.loadKeyFor(e,n,l);if(this.fragContextChanged(e)){var c;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(c=this.fragCurrent)==null?void 0:c.relurl}`),l?.catch(()=>null),d?.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${i}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),B(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=_.FRAG_LOADING;let h=this.config.progressive&&e.type!==H.SUBTITLE,u;return h&&d?u=d.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,s,l)).catch(f=>this.handleFragLoadError(f)):u=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,h?s:void 0,h?l:void 0),d,l]).then(([f])=>(!h&&s&&s(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([u,l]).then(([f])=>f)}doFragPartsLoad(e,t,i,s){return new Promise((n,a)=>{var o;let l=[],d=(o=i.details)==null?void 0:o.partList,c=h=>{this.fragmentLoader.loadPart(e,h,s).then(u=>{l[h.index]=u;let f=u.part;this.hls.trigger(y.FRAG_LOADED,u);let g=so(i.details,e.sn,h.index+1)||Bl(d,e.sn,h.index+1);if(g)c(g);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};c(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===W.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==_.PARSING){!this.fragCurrent&&this.state!==_.STOPPED&&this.state!==_.ERROR&&(this.state=_.IDLE);return}let{frag:i,part:s,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a);let o=this.getLevelDetails(),d=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=d),this.updateLevelTiming(i,s,n,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var i;let s=e.partList[0],n=s.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=n&&this.playhead>s.start-s.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:s,sn:n,part:a}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;let o=t[s],l=o.details,d=a>-1?so(l,n,a):null,c=d?d.fragment:Nl(l,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:d,level:o}):null}bufferFragmentData(e,t,i,s,n){if(this.state!==_.PARSING)return;ve(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:o}=e,l=a;if(o&&(l=Ye(a,o)),!l.length)return;let d=this.initPTS[t.cc],c=d?-d.baseTime/d.timescale:void 0,h={type:e.type,frag:t,part:i,chunkMeta:s,offset:c,parent:t.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!J.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,s=J.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,s.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var i;let s=this.playhead,a=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,a)}getFwdBufferInfoAtPos(e,t,i,s){let n=J.bufferInfo(e,t,s);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,s);return J.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){let s=e.nextStart;if(s&&i.start>s){let n=e.buffered;if(n){let a=e.len,o=e.bufferedIndex;for(let l=n.length-1;l>o;l--)n[l].start<i.start&&(a+=n[l].end-n[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){let i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t/2),n=Math.max(e-t*3,i.maxMaxBufferLength/2,s);return n>=s?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e){let t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){let i=t.fragments,s=i.length;if(!s)return null;let{config:n}=this,a=t.fragmentStart,o=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let h=n.initialLiveManifestSize;if(s<h)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${h})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var d;l=this.getInitialLiveFragment(t);let u=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,m=((d=l)==null?void 0:d.start)||0,p,v;if(f!==-1&&f>=a?(p=f,v=f===u?"config":"next load start"):g?(p=g,v="live edge"):(p=e,v="buffer pos"),p<m&&(p=m,v="live frag start"),p<a&&(p=a,v="playlist start"),this.startPosition!=p||this.nextLoadPosition!=p){let E=t.live&&!this.filterReplacedPrimary(l,t)?-1:p;this.log(`Setting startPosition to ${E} next load ${p} ${f===-1?"":`(from ${u}) `}based on ${v}. live edge: ${g} live frag start: ${m} playlist start: ${a} buffer pos: ${e}`),this.startPosition=E,this.nextLoadPosition=p}}}else e<=a&&(l=i[0]);if(!l){let h=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,h,t)}let c=this.filterReplacedPrimary(l,t);return!c&&l&&(c=Il(t,l.sn),c&&(this.nextLoadPosition=c.start)),c}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let i=this.fragmentTracker.getState(e);return!!(i===ye.OK||i===ye.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,i,s,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(o!==null&&i.len+o.len>=n){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(ds(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(ds(this.config)&&("type"in e?e:e.fragment).type!==H.SUBTITLE){let i=this.hls.interstitialsManager,s=i?.bufferingItem;if(s){let n=s.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-s.start)>1||s.start===0))return null}else if(e.end<=s.start&&t?.live===!1||e.start>=s.end&&s.nextEvent&&(s.nextEvent.appendInPlace&&!s.nextEvent.hasPlayed||e.start-s.end>1))return null}if(Gl(e,i?.playerQueue,this.playhead))return null}return e}getNextPart(e,t,i){let s=-1,n=!1,a=!0;for(let l=0,d=e.length;l<d;l++){let c=e[l];if(a=a&&!c.independent,s>-1&&i<c.start)break;let h=c.loaded||c.gap;h?s=-1:(n||(c.independent||a)&&c.fragment===t)&&(s=l),n=h&&!c.gap}let o=e[s];return o&&o.fragment!==t&&this.log(`Need buffer at ${i} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,s=null;if(i){if(e.hasProgramDateTime&&(s=ph(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!s){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=xl(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){let{config:s}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:d}=s,c=i.partList,h=!!(this.loadingParts&&c!=null&&c.length&&l);h&&!this.bitrateTest&&c[c.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),n&&this.fragmentTracker.getState(n)===ye.NOT_LOADED&&(n=null);let u;if(e<t){var f;let m=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;u=qt(n,a,e,m)}else u=a[a.length-1];if(u){let g=u.sn-i.startSN,m=this.fragmentTracker.getState(u);if((m===ye.OK||m===ye.PARTIAL&&u.gap)&&(n=u),Zt(u,n)&&(!h||c[0].fragment.sn>u.sn||!i.live)){let p=a[g+1];u.sn<o&&this.fragmentTracker.getState(p)!==ye.OK?u=p:u=null}}return u}alignPlaylists(e,t,i){let s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&B(n);if(a||!o&&!n){os(i,e,this);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);let s=this.timelineOffset;if(i===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;if(a!==null&&B(a))i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i;else if(e.live){let o=this.hls.liveSyncPosition;i=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;let{media:t}=this,i=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;let i=(t=this.media)==null?void 0:t.currentTime;return B(i)?i:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==H.MAIN)return!1;let t=this.getLevelDetails();return t?t.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ve(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==_.FRAG_LOADING_WAITING_RETRY)&&(this.state=_.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let T=this.getCurrentContext(t.chunkMeta);T&&(t.frag=T.frag)}let{frag:i,part:s}=t;if(!i||!this.levels||i.type!==e)return;if(this.fragContextChanged(i)){var n;this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${(n=this.fragCurrent)==null?void 0:n.relurl}`);return}let a=t.details===L.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);let o=t.errorAction;if(!o){this.state=_.ERROR;return}let{action:l,flags:d,retryCount:c=0,retryConfig:h}=o,u=!!h,f=u&&l===Re.RetryRequest,g=u&&!o.resolved&&d&Le.MoveAllAlternatesMatchingHost,m=this.hls.latestLevelDetails,p=m?.live;if(!f&&g&&ve(i)&&p&&i.sn<m.endSN&&!jo(t))this.resetFragmentErrors(e),s?s.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((f||g)&&c<h.maxNumRetry){var v;let T=oi((v=t.response)==null?void 0:v.code),E=Ur(h,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=_.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,T){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${c+1}/${h.maxNumRetry} in ${E}ms`)}else if(h)if(this.resetFragmentErrors(e),c<h.maxNumRetry)!a&&l!==Re.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${c})`);return}else l===Re.SendAlternateToPenaltyBox?this.state=_.WAITING_LEVEL:this.state=_.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!oi(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=_.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===_.PARSING||this.state===_.PARSED){let t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,t?.duration||10);let a=!n;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):s.nextStart&&t&&s.nextStart>t.start&&this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,i===H.AUDIO?i:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===H.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==_.STOPPED&&(this.state=_.IDLE)}afterBufferFlushed(e,t){if(!e)return;let i=J.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,this.playlistType),this.state===_.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==_.STOPPED&&(this.state=_.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){let n=i.details;if(!n){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((h,u)=>{let f=e.elementaryStreams[u];if(f){let g=f.endPTS-f.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${u} duration reliably (${g})`),h||!1;let m=s.partial?0:Ml(n,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this.iframesOnly,this);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:n,level:i,drift:m,type:u,frag:e,start:f.startPTS,end:f.endPTS}),!0}return h},!1)){var o,l,d,c;let h=((o=this.transmuxer)==null?void 0:o.error)===null,u=((l=this.transmuxer)==null?void 0:l.error)!=null,f=((d=(c=this.levels)==null?void 0:c.length)!=null?d:0)>1;if((i.fragmentError===0||h&&(i.fragmentError<2||e.endList)||u&&f)&&this.treatAsGap(e,i),h){let g=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(g.message),this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:g,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=_.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,i){var s,n;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(s=t&&!i?e.startPTS:(i||e).start)!=null?s:NaN}-${(n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;let i=(t=e.loader)==null?void 0:t.stats;if(!i)return!1;let s=i.loading.first>0,a=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&a<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let i=0,{hls:s,media:n,config:a,levels:o,playlistType:l}=this,d=this.getLevelDetails();if(n&&!n.paused&&o){var c;let f=l===H.AUDIO?El(e.audioCodec,128e3):e.maxBitrate,g=1+s.ttfbEstimate/1e3,m=s.bandwidthEstimate*a.abrBandWidthUpFactor,p=d&&(this.loadingParts?d.partTarget:d.averagetargetduration)||((c=this.fragCurrent)==null?void 0:c.duration)||6;i=g+f*p/m,e.details||(i+=g)}let h=this.playhead,u=!(d!=null&&d.live)||t.end-h>i*1.5;return{fetchdelay:i,okToFlushForwardBuffer:u}}scheduleTrackSwitch(e,t,i){let{media:s,playlistType:n}=this;if(!s||!e)return;let a=i?this.getBufferedFrag(this.playhead+t):null;if(a){let l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();let d=l.maxStartPTS?l.maxStartPTS:l.start,c=l.duration,h=Math.max(a.end,d+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>h)return;let f=n===H.MAIN?null:"audio";this.flushMainBuffer(h,Number.POSITIVE_INFINITY,f),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){let s=t===H.AUDIO;this.flushMainBuffer(0,i.start-(s?0:1),s?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case _.KEY_LOADING:case _.FRAG_LOADING:case _.FRAG_LOADING_WAITING_RETRY:case _.PARSING:case _.PARSED:this.state=_.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let i=e.currentTime;if(J.isBuffered(e,i)?t=this.getAppendedFrag(i):J.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t&&(this.backtrackFragment=void 0,!Zt(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:i,config:s,playlistType:n}=this;if(t!=null&&t.readyState&&e&&i&&s){let a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,n);if(!o)return;let l=n===H.AUDIO?i.nextAudioTrack:i.nextLoadLevel,d=e[l],{fetchdelay:c,okToFlushForwardBuffer:h}=this.calculateOptimalSwitchPoint(d,o);this.scheduleTrackSwitch(o,c,h)}this.tickImmediate()}};function Gl(r,e,t){if(e)for(let i=e.length;i--;){let s=e[i].interstitial,n=s.startTime,a=Math.min(n+s.duration,s.resumeTime);if(s.appendInPlace&&(r.start>=n&&r.end<=a||t>r.start&&r.end>n&&r.start<a))return!0}return!1}function ds(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}var cs=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=jh(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}};function jh(r,e){let t=new Uint8Array(e),i=0;for(let s=0;s<r.length;s++){let n=r[s];t.set(n,i),i+=n.length}return t}var Js={exports:{}},ao;function zh(){return ao||(ao=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,d,c){this.fn=l,this.context=d,this.once=c||!1}function n(l,d,c,h,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new s(c,h||l,u),g=t?t+d:d;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var u=0,f=h.length,g=new Array(f);u<f;u++)g[u]=h[u].fn;return g},o.prototype.listenerCount=function(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,u,f,g){var m=t?t+d:d;if(!this._events[m])return!1;var p=this._events[m],v=arguments.length,T,E;if(p.fn){switch(p.once&&this.removeListener(d,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,c),!0;case 3:return p.fn.call(p.context,c,h),!0;case 4:return p.fn.call(p.context,c,h,u),!0;case 5:return p.fn.call(p.context,c,h,u,f),!0;case 6:return p.fn.call(p.context,c,h,u,f,g),!0}for(E=1,T=new Array(v-1);E<v;E++)T[E-1]=arguments[E];p.fn.apply(p.context,T)}else{var S=p.length,b;for(E=0;E<S;E++)switch(p[E].once&&this.removeListener(d,p[E].fn,void 0,!0),v){case 1:p[E].fn.call(p[E].context);break;case 2:p[E].fn.call(p[E].context,c);break;case 3:p[E].fn.call(p[E].context,c,h);break;case 4:p[E].fn.call(p[E].context,c,h,u);break;default:if(!T)for(b=1,T=new Array(v-1);b<v;b++)T[b-1]=arguments[b];p[E].fn.apply(p[E].context,T)}}return!0},o.prototype.on=function(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,u){var f=t?t+d:d;if(!this._events[f])return this;if(!c)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!u||g.once)&&(!h||g.context===h)&&a(this,f);else{for(var m=0,p=[],v=g.length;m<v;m++)(g[m].fn!==c||u&&!g[m].once||h&&g[m].context!==h)&&p.push(g[m]);p.length?this._events[f]=p.length===1?p[0]:p:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}(Js)),Js.exports}var Xh=zh(),zr=zd(Xh),pi="1.7.1",Wt={};function Qh(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Zh(){let r=Wt[pi];if(r)return r.clientCount++,r;let 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"}),t=self.URL.createObjectURL(e),s={worker:new self.Worker(t),objectURL:t,clientCount:1};return Wt[pi]=s,s}function Jh(r){let e=Wt[r];if(e)return e.clientCount++,e;let t=new self.URL(r,self.location.href).href,s={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Wt[r]=s,s}function eu(r){let e=Wt[r||pi];if(e&&e.clientCount--===1){let{worker:i,objectURL:s}=e;delete Wt[r||pi],s&&self.URL.revokeObjectURL(s),i.terminate()}}function tu(r,e,t,i){let s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let p=new Error(`invalid ADTS sampling index:${a}`);r.emit(y.ERROR,y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d=s[a],c=a;(o===5||o===29)&&(c-=3);let h,u=(c&14)>>1,f=(c&1)<<7|l<<3,g=0;if(o===1&&a>=6){g=5;let p=a-3;h=[g<<3|u,f|(p&14)>>1,(p&1)<<7|8,0]}else h=[o<<3|u,f];let m="mp4a.40."+(g||o);return oe.log(`manifest codec:${i}, parsed codec:${m}, channels:${l}, rate:${d} (ADTS object type:${o} sampling index:${a} esds config:[${h.join(",")}])`),{config:h,samplerate:d,channelCount:l,codec:m,parsedCodec:m,manifestCodec:i}}function Vl(r,e){return r[e]===255&&(r[e+1]&246)===240}function Hl(r,e){return r[e+1]&1?7:9}function Xr(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function iu(r,e){return e+5<r.length}function hs(r,e){return e+1<r.length&&Vl(r,e)}function su(r,e){return iu(r,e)&&Vl(r,e)&&Xr(r,e)<=r.length-e}function nu(r,e){if(hs(r,e)){let t=Hl(r,e);if(e+t>=r.length)return!1;let i=Xr(r,e);if(i<=t)return!1;let s=e+i;return s===r.length||hs(r,s)}return!1}function Kl(r,e,t,i,s){if(!r.samplerate){let n=tu(e,t,i,s);if(!n)return;ce(r,n)}}function ql(r){return 1024*9e4/r}function ru(r,e){let t=Hl(r,e);if(e+t<=r.length){let i=Xr(r,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Wl(r,e,t,i,s){let n=ql(r.samplerate),a=i+s*n,o=ru(e,t),l;if(o){let{frameLength:h,headerLength:u}=o,f=u+h,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-u),l.set(e.subarray(t+u,e.length),0)):l=e.subarray(t+u,t+f);let m={unit:l,pts:a};return g||r.samples.push(m),{sample:m,length:f,missing:g}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}var Me=function(r){return r.audioId3="org.id3",r.dateRange="com.apple.quicktime.HLS",r.emsg="https://aomedia.org/emsg/ID3",r.misbklv="urn:misb:KLV:bin:1910.1",r}({});function at(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var yi=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Ye(this.cachedData,e),this.cachedData=null);let i=li(e,0),s=i?i.length:0,n,a=this._audioTrack,o=this._id3Track,l=i?Vr(i):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&B(l))&&(this.basePTS=au(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Me.audioId3,duration:Number.POSITIVE_INFINITY});s<d;){if(this.canParse(e,s)){let c=this.appendFrame(a,e,s);c?(this.frameIndex++,this.lastPTS=c.sample.pts,s+=c.length,n=s):s=d}else uc(e,s)?(i=li(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Me.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===d&&n!==d){let c=e.slice(n);this.cachedData?this.cachedData=Ye(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:at(),id3Track:o,textTrack:at()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:at(),id3Track:this._id3Track,textTrack:at()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},au=(r,e,t)=>{if(B(r))return r*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},ou=[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],lu=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],du=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cu=[0,1,1,4];function Yl(r,e,t,i,s){if(t+24>e.length)return;let n=jl(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function jl(r,e){let t=r[e+1]>>3&3,i=r[e+1]>>1&3,s=r[e+2]>>4&15,n=r[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&n!==3){let a=r[e+2]>>1&1,o=r[e+3]>>6,l=t===3?3-i:i===3?3:4,d=ou[l*14+s-1]*1e3,h=lu[(t===3?0:t===2?1:2)*3+n],u=o===3?1:2,f=du[t][i],g=cu[i],m=f*8*g,p=Math.floor(f*d/h+a)*g,v=ei();return!!v&&v<=87&&i===2&&d>=224e3&&o===0&&(r[e+3]=r[e+3]|128),{sampleRate:h,channelCount:u,frameLength:p,samplesPerFrame:m}}}function Qr(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function zl(r,e){return e+1<r.length&&Qr(r,e)}function hu(r,e){return Qr(r,e)&&4<=r.length-e}function Xl(r,e){if(e+1<r.length&&Qr(r,e)){let i=jl(r,e),s=4;i!=null&&i.frameLength&&(s=i.frameLength);let n=e+s;return n===r.length||zl(r,n)}return!1}var us=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new fi(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,At.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,i){let s=e[t].unit;if(s.length<=16)return;let n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),s=0;for(let n=32;n<e.length-16;n+=160,s+=16)i.set(e.subarray(n,n+16),s);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),s=0;for(let n=32;n<e.length-16;n+=160,s+=16)e.set(i.subarray(s,s+16),n);return e}decryptAvcSample(e,t,i,s,n){let a=ul(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}let n=e[t].units;for(;!(i>=n.length);i++){let a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,s,a),!this.decrypter.isSync()))return}}}},Mn=class extends yi{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let i=li(e,0),s=i?.length||0;if(Xl(e,s))return!1;for(let n=e.length;s<n;s++)if(nu(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return su(e,t)}appendFrame(e,t,i){Kl(e,this.observer,t,i,e.manifestCodec);let s=Wl(e,t,i,this.basePTS,this.frameIndex);if(s?.missing===0)return s}demuxSampleAes(e,t,i){let s=this.demux(e,i),n=this.sampleAes=new us(this.observer,this.config,t);return new Promise(a=>{n.decryptAacSamples(s.audioTrack.samples,0,()=>{a(s)})})}},Ql=(r,e)=>{let t=0,i=5;e+=i;let s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=r[e];let o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t},On=class extends yi{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let s=Zl(e,t,i,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;let t=li(e,0);if(!t)return!1;let i=t.length;if(e[i]===11&&e[i+1]===119&&Vr(t)!==void 0){if(Ql(e,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}};function Zl(r,e,t,i,s){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let n=e[t+4]>>6;if(n>=3)return-1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,c=[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][l*3+n]*2;if(t+c>e.length)return-1;let h=e[t+6]>>5,u=0;h===2?u+=2:(h&1&&h!==1&&(u+=2),h&4&&(u+=2));let f=(e[t+6]<<8|e[t+7])>>12-u&1,m=[2,1,2,3,3,4,4,5][h]+f,p=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|p<<1|v>>2,(v&3)<<6|h<<3|f<<2|l>>4,l<<4&224]),E=1536/o*9e4,S=i+s*E,b=e.subarray(t,t+c);return r.config=T,r.channelCount=m,r.samplerate=o,r.samples.push({unit:b,pts:S}),c}var Fn=class extends yi{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=li(e,0),i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Vr(t)!==void 0&&Ql(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(Xl(e,i))return oe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return hu(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Yl(e,t,i,this.basePTS,this.frameIndex)}},uu=/\/emsg[-/]ID3/i,Nn=class{constructor(e,t,i,s=oe){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.initData=void 0,this.logger=void 0,this.config=t,this.logger=s}resetTimeStamp(){}resetInitSegment(e,t,i,s){let n=this.videoTrack=at("video",1),a=this.audioTrack=at("audio",1),o=this.txtTrack=at("text",1);if(this.id3Track=at("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=this.initData=ol(e);if(l.video){let{id:d,timescale:c,codec:h,supplemental:u}=l.video;n.id=d,n.timescale=o.timescale=c,n.codec=h,n.supplemental=u}if(l.audio){let{id:d,timescale:c,codec:h}=l.audio;a.id=d,a.timescale=c,a.codec=h}o.id=sl.text,n.sampleDuration=0,n.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return Rc(e,"moof")}demux(e,t,i){this.timeOffset=t;let s=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Ye(this.remainderData,e));let d=Nc(s);this.remainderData=d.remainder,n.samples=d.valid||new Uint8Array}else n.samples=s;let o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,i);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let i=this.timeOffset,s=this.videoTrack,n=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;let a=this.extractID3Track(s,this.timeOffset),o=this.parseFragment(s,n,i,t);return{videoTrack:s,audioTrack:at(),id3Track:a,textTrack:at(),initData:this.initData,sampleData:o}}parseFragment(e,t,i,s){let n=this.initData;if(n&&s){let{samples:a,sampleData:o}=Fc(i,e,n,this.logger,s.iframe);return t.samples=a,o}t.samples=Bc(i,e)}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let s=Q(e.samples,["emsg"]);s&&s.forEach(n=>{let a=$c(n);if(uu.test(a.schemeIdUri)){let o=oo(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=a.payload;i.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:Me.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let o=this.config.emsgKLVSchemaUri||Me.misbklv;if(a.schemeIdUri.startsWith(o)){let l=oo(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:Me.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(e,t,i){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,this.initData=void 0}};function oo(r,e){return B(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}var fu=1,gu=2,zt=-1,fs=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,s=i.length;if(s){let n=i[s-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){let s=t.byteLength;if(s===0)return[];let n=e.naluState||0,a=n===zt?0:n,o=[],l=0,d=0,c=-1,h=0;for(n===zt&&(c=0,h=this.getNALuType(t,0),d=1);d<s;){let u=t.indexOf(fu,d);if(u===-1)break;d=u+1;let f=u;for(;f>0&&t[f-1]===0;)f--;if(!(u-f+(f===0?a:0)<gu)){if(c>=0)o.push({data:t.subarray(c,f),type:h});else{let m=this.getLastNalUnit(e.samples);m&&(f>0?m.data=Ye(m.data,t.subarray(0,f)):a>0&&(m.data=m.data.subarray(0,m.data.byteLength-a)),m.state=0)}if(d<s)c=d,h=this.getNALuType(t,d);else{l=zt,c=-1;break}}}if(l!==zt){let u=s;for(;u>0&&t[u-1]===0;)u--;l=s-u+(u===0?a:0)}if(c>=0)o.push({data:t.subarray(c),type:h,state:l});else if(o.length===0&&l!==zt){let u=this.getLastNalUnit(e.samples);u&&(u.data=Ye(u.data,t),u.state=l)}return e.naluState=l,o}},Dt=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");s.set(e.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&oe.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}},Bn=class extends fs{parsePES(e,t,i,s,n){let a=n.iframe,o=this.parseNALu(e,i.data,s),l=this.VideoSample,d,c=!1;i.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),o.forEach(h=>{var u,f;switch(h.type){case 1:{if(a)break;let v=!1;d=!0;let T=h.data;if(c&&T.length>4){let E=this.readSliceType(T);(E===2||E===4||E===7||E===9)&&(v=!0)}if(v){var g;(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.frame=!0,l.key=v;break}case 5:d=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;d=!0,di(h.data,1,i.pts,t.samples);break}case 7:{var m,p;d=!0,c=!0;let v=h.data,T=this.readSPS(v);if(!e.sps||e.width!==T.width||e.height!==T.height||((m=e.pixelRatio)==null?void 0:m[0])!==T.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==T.pixelRatio[1]){e.width=T.width,e.height=T.height,e.pixelRatio=T.pixelRatio,e.sps=[v];let E=v.subarray(1,4),S="avc1.";for(let b=0;b<3;b++){let A=E[b].toString(16);A.length<2&&(A="0"+A),S+=A}e.codec=S}break}case 8:d=!0,e.pps=[h.data];break;case 9:d=!0,e.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:d=!0;break;default:d=!1;break}l&&d&&l.units.push(h)}),s&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Dt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,s=8,n;for(let a=0;a<e;a++)s!==0&&(n=t.readEG(),s=(i+n+256)%256),i=s===0?i:s}readSPS(e){let t=new Dt(e),i=0,s=0,n=0,a=0,o,l,d,c=t.readUByte.bind(t),h=t.readBits.bind(t),u=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),m=t.skipEG.bind(t),p=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);c();let T=c();if(h(5),g(3),c(),p(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){let R=u();if(R===3&&g(1),p(),p(),g(1),f())for(l=R!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t))}p();let E=u();if(E===0)u();else if(E===1)for(g(1),m(),m(),o=u(),d=0;d<o;d++)m();p(),g(1);let S=u(),b=u(),A=h(1);A===0&&g(1),g(1),f()&&(i=u(),s=u(),n=u(),a=u());let x=[1,1];if(f()&&f())switch(c()){case 1:x=[1,1];break;case 2:x=[12,11];break;case 3:x=[10,11];break;case 4:x=[16,11];break;case 5:x=[40,33];break;case 6:x=[24,11];break;case 7:x=[20,11];break;case 8:x=[32,11];break;case 9:x=[80,33];break;case 10:x=[18,11];break;case 11:x=[15,11];break;case 12:x=[64,33];break;case 13:x=[160,99];break;case 14:x=[4,3];break;case 15:x=[3,2];break;case 16:x=[2,1];break;case 255:{x=[c()<<8|c(),c()<<8|c()];break}}return{width:Math.ceil((S+1)*16-i*2-s*2),height:(2-A)*(b+1)*16-(A?2:4)*(n+a),pixelRatio:x}}},$n=class extends fs{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){let n=this.parseNALu(e,i.data,s),a=this.VideoSample,o,l=!1;i.data=null;let d=c=>(a=this.VideoSample=this.createVideoSample(c,i.pts,i.dts),a);n.forEach((c,h)=>{var u,f;if(this.startsNewAccessUnit(a,e,c,h)){this.pushAccessUnit(a,e);let m=c.type>=16&&c.type<=23;a=d(m),l=!1}switch(c.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=d(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var g;(g=a)!=null&&g.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=d(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=d(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,di(c.data,2,i.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ce(e.params,this.readVPS(c.data)),this.initVPS=c.data),e.vps=[c.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],c.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let m=this.readSPS(c.data);e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.codec=m.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let p in m.params)e.params[p]=m.params[p]}this.pushParameterSet(e.sps,c.data,e.vps),a||(a=d(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let m=this.readPPS(c.data);for(let p in m)e.params[p]=m[p]}this.pushParameterSet(e.pps,c.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=d(!1));break;default:o=!1;break}a&&o&&a.units.push(c)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,i,s){if(!e)return!1;if(!t.audFound&&s===0)return!0;if(!e.frame)return!1;let{type:n,data:a}=i;return n>=32&&n<=35||n===39||n>=41&&n<=44||n>=48&&n<=55?!0:n<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new Dt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let i=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:i+1,temporalIdNested:s}}readSPS(e){let t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let s=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),v=t.readUByte(),T=[],E=[];for(let q=0;q<i;q++)T.push(t.readBoolean()),E.push(t.readBoolean());if(i>0)for(let q=i;q<8;q++)t.readBits(2);for(let q=0;q<i;q++)T[q]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[q]&&t.readUByte();t.readUEG();let S=t.readUEG();S==3&&t.skipBits(1);let b=t.readUEG(),A=t.readUEG(),x=t.readBoolean(),R=0,P=0,I=0,k=0;x&&(R+=t.readUEG(),P+=t.readUEG(),I+=t.readUEG(),k+=t.readUEG());let D=t.readUEG(),F=t.readUEG(),G=t.readUEG(),$=t.readBoolean();for(let q=$?0:i;q<=i;q++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let se=0;se<4;se++)for(let re=0;re<(se===3?2:6);re++)if(!t.readBoolean())t.readUEG();else{let Te=Math.min(64,1<<4+(se<<1));se>1&&t.readEG();for(let Ce=0;Ce<Te;Ce++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let w=t.readUEG(),N=0;for(let q=0;q<w;q++){let se=!1;if(q!==0&&(se=t.readBoolean()),se){q===w&&t.readUEG(),t.readBoolean(),t.readUEG();let re=0;for(let Ae=0;Ae<=N;Ae++){let Te=t.readBoolean(),Ce=!1;Te||(Ce=t.readBoolean()),(Te||Ce)&&re++}N=re}else{let re=t.readUEG(),Ae=t.readUEG();N=re+Ae;for(let Te=0;Te<re;Te++)t.readUEG(),t.readBoolean();for(let Te=0;Te<Ae;Te++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let q=t.readUEG();for(let se=0;se<q;se++){for(let re=0;re<G+4;re++)t.readBits(1);t.readBits(1)}}let O=0,U=1,Z=1,j=!0,ie=1,z=0;t.readBoolean(),t.readBoolean();let ne=!1;if(t.readBoolean()){if(t.readBoolean()){let je=t.readUByte(),It=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Pe=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];je>0&&je<16?(U=It[je-1],Z=Pe[je-1]):je===255&&(U=t.readBits(16),Z=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ne=t.readBoolean(),ne&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Pe=t.readBoolean(),we=t.readBoolean(),qe=!1;(Pe||we)&&(qe=t.readBoolean(),qe&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),qe&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let $e=0;$e<=i;$e++){j=t.readBoolean();let De=j||t.readBoolean(),gt=!1;De?t.readEG():gt=t.readBoolean();let ct=gt?1:t.readUEG()+1;if(Pe)for(let ze=0;ze<ct;ze++)t.readUEG(),t.readUEG(),qe&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(we)for(let ze=0;ze<ct;ze++)t.readUEG(),t.readUEG(),qe&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),O=t.readUEG())}let ae=b,be=A;if(x){let q=1,se=1;S===1?q=se=2:S==2&&(q=2),ae=b-q*P-q*R,be=A-se*k-se*I}let Fe=s?["A","B","C"][s]:"",dt=o<<24|l<<16|d<<8|c,ge=0;for(let q=0;q<32;q++)ge=(ge|(dt>>q&1)<<31-q)>>>0;let Ke=ge.toString(16);return a===1&&Ke==="2"&&(Ke="6"),{codecString:`hvc1.${Fe}${a}.${Ke}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[o,l,d,c],general_constraint_indicator_flags:[h,u,f,g,m,p],general_level_idc:v,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:F,min_spatial_segmentation_idc:O,chroma_format_idc:S,frame_rate:{fixed:j,fps:z/ie}},width:ae,height:be,pixelRatio:[U,Z]}}readPPS(e){let t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let s=t.readBoolean(),n=t.readBoolean(),a=1;return n&&s?a=0:n?a=3:s&&(a=2),{parallelismType:a}}matchSPS(e,t){return et(e).substring(3)===et(t).substring(3)}},xe=188,gs=class r{constructor(e,t,i,s){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._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){let i=r.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){let t=e.length,i=Math.min(xe*5,t-xe)+1,s=0;for(;s<i;){let n=!1,a=-1,o=0;for(let l=s;l<t;l+=xe)if(e[l]===71&&(t-l===xe||e[l+xe]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+xe*99,e.length-xe)+1)),n||(n=ms(e,l)===0),n&&o>1&&(a===0&&o>2||l+xe>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:sl[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=r.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new Gn(this.logger):null,this._audioTrack=r.createTrack("audio",s),this._id3Track=r.createTrack("id3"),this._txtTrack=r.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,e&&this.demux(e,0,a,n?.method==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i,s=!1,n=!1){s||(this.sampleAes=null);let a,o=this._videoTrack,l=this.videoIntegrityChecker,d=this._audioTrack,c=this._id3Track,h=this._txtTrack,u=i.iframe,f=o.pid,g=o.pesData,m=d.pid,p=c.pid,v=this._klvPid,T=d.pesData,E=c.pesData,S=null,b=null,A=this.pmtParsed,x=this._pmtId,R=e.length;if(this.remainderData&&(e=Ye(this.remainderData,e),R=e.length,this.remainderData=null),R<xe&&!n)return this.remainderData=e,{audioTrack:d,videoTrack:o,id3Track:c,textTrack:h};let P=Math.max(0,r.syncOffset(e));R-=(R-P)%xe,R<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,R,e.buffer.byteLength-R));let I=0;for(let D=P;D<R;D+=xe)if(e[D]===71){let F=!!(e[D+1]&64),G=ms(e,D),$=(e[D+3]&48)>>4,C;if($>1){if(C=D+5+e[D+4],C===D+xe)continue}else C=D+4;switch(G){case f:F&&(g&&!(l!=null&&l.isCorrupted)&&(a=Lt(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,h,a,!1,i)),g={data:[],size:0},l?.reset(f)),l?.handlePacket(e.subarray(D)),g&&(g.data.push(e.subarray(C,D+xe)),g.size+=D+xe-C);break;case m:if(u)break;if(F){if(T&&(a=Lt(T,this.logger)))switch(d.segmentCodec){case"aac":this.parseAACPES(d,a,i);break;case"mp3":this.parseMPEGPES(d,a);break;case"ac3":this.parseAC3PES(d,a);break}T={data:[],size:0}}T&&(T.data.push(e.subarray(C,D+xe)),T.size+=D+xe-C);break;case p:if(u)break;F&&(E&&(a=Lt(E,this.logger))&&this.parseID3PES(c,a),E={data:[],size:0}),E&&(E.data.push(e.subarray(C,D+xe)),E.size+=D+xe-C);break;case v:if(u)break;F&&(S&&(a=Lt(S,this.logger))&&this.parseKlvPES(c,a),S={data:[],size:0}),S&&(S.data.push(e.subarray(C,D+xe)),S.size+=D+xe-C);break;case 0:F&&(C+=e[C]+1),x=this._pmtId=mu(e,C);break;case x:{F&&(C+=e[C]+1);let M=pu(e,C,this.typeSupported,s,this.observer,this.logger,this.config,i);f=M.videoPid,f>0&&(o.pid=f,o.segmentCodec=M.segmentVideoCodec),m=M.audioPid,m>0&&(d.pid=m,d.segmentCodec=M.segmentAudioCodec),p=M.id3Pid,p>0&&(c.pid=p),v=M.klvPid,v>0&&(this._klvPid=v),b!==null&&!A&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${b}'. Backtracking to sync byte @${P} to parse all TS packets.`),b=null,D=P-188),A=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=G;break}}else I++;I>0&&Un(this.observer,new Error(`Found ${I} TS packet/s that do not start with 0x47`),i,void 0,this.logger),o.pesData=g,d.pesData=T,c.pesData=E;let k={audioTrack:d,videoTrack:o,id3Track:c,textTrack:h};return n&&this.extractRemainingSamples(k,i),k}flush(e,t){let{remainderData:i}=this;this.remainderData=null;let s;return i?s=this.demux(i,0,t,!1,!0):s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s,t),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(e,t){let{audioTrack:i,videoTrack:s,id3Track:n,textTrack:a}=e,o=s.pesData,l=i.pesData,d=n.pesData,c=this.videoIntegrityChecker,h;if(o&&!(c!=null&&c.isCorrupted)&&(h=Lt(o,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,a,h,!0,t),s.pesData=null)):s.pesData=o,l&&(h=Lt(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,h,t);break;case"mp3":this.parseMPEGPES(i,h);break;case"ac3":this.parseAC3PES(i,h);break}i.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;d&&(h=Lt(d,this.logger))?(this.parseID3PES(n,h),n.pesData=null):n.pesData=d}demuxSampleAes(e,t,i,s){let n=this.demux(e,i,s,!0,!this.config.progressive),a=this.sampleAes=new us(this.observer,this.config,t);return this.decrypt(n,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Bn:e==="hevc"&&(this.videoParser=new $n))}decrypt(e,t){return new Promise(i=>{let{audioTrack:s,videoTrack:n}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e)}):i(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,i){let s=0,n=this.aacOverFlow,a=t.data;if(n){this.aacOverFlow=null;let u=n.missing,f=n.sample.unit.byteLength;if(u===-1)a=Ye(n.sample.unit,a);else{let g=f-u;n.sample.unit.set(a.subarray(0,u),g),e.samples.push(n.sample),s=n.missing}}let o,l;for(o=s,l=a.length;o<l-1&&!hs(a,o);o++);if(o!==s){let u,f=o<l-1;if(f?u=`AAC PES did not start with ADTS header,offset:${o}`:u="No ADTS header found in AAC PES",Un(this.observer,new Error(u),i,f,this.logger),!f)return}Kl(e,this.observer,a,o,this.audioCodec);let d;if(t.pts!==void 0)d=t.pts;else if(n){let u=ql(e.samplerate);d=n.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;o<l;)if(h=Wl(e,a,o,d,c),o+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;o<l-1&&!hs(a,o);o++);}parseMPEGPES(e,t){let i=t.data,s=i.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(zl(i,a)){let l=Yl(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{let i=t.data,s=t.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=i.length,a=0,o=0,l;for(;o<n&&(l=Zl(e,i,o,s,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=ce({},t,{type:this._videoTrack?Me.emsg:Me.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}parseKlvPES(e,t){var i;let s=(i=t.pts)!=null?i:t.dts;if(s===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}let n=t.data;if(n.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<n.length;){var o;if(a+16>n.length)break;let l=a;if(a+=16,a>=n.length)break;let d=n[a];a+=1;let c=0;if(d&128){let g=d&127;if(g===0||g>4||a+g>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let m=0;m<g;m++)c=c<<8|n[a+m];a+=g}else c=d;if(a+c>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let h=a+c,u=n.subarray(l,h),f={data:u,len:u.byteLength,pts:s,dts:(o=t.dts)!=null?o:s,type:Me.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(f),a=h}}};function ms(r,e){return((r[e+1]&31)<<8)+r[e+2]}function mu(r,e){return(r[e+10]&31)<<8|r[e+11]}function pu(r,e,t,i,s,n,a,o){let l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=(r[e+1]&15)<<8|r[e+2],c=e+3+d-4,h=(r[e+10]&15)<<8|r[e+11];for(e+=12+h;e<c;){let u=ms(r,e),f=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!i){en("ADTS AAC",n);break}case 15:l.audioPid===-1&&(l.audioPid=u);break;case 21:l.id3Pid===-1&&(l.id3Pid=u);break;case 219:if(!i){en("H.264",n);break}case 27:l.videoPid===-1&&(l.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=u,l.segmentAudioCodec="mp3");break;case 193:if(!i){en("AC-3",n);break}case 129:t.ac3?l.audioPid===-1&&(l.audioPid=u,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(f>0){let g=e+5,m=f;for(;m>2;){switch(r[g]){case 106:l.audioPid===-1&&(t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=u,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=u,n.log(`KLV metadata PID found: ${u}`));break}let v=r[g+1]+2;g+=v,m-=v}}break;case 194:case 135:return Un(s,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:l.videoPid===-1&&(l.videoPid=u,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=f+5}return l}function Un(r,e,t,i,s){s.warn(`parsing error: ${e.message}`),r.emit(y.ERROR,y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:t,error:e,reason:e.message})}function en(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Lt(r,e){let t=0,i,s,n,a,o,l=r.data;if(!r||r.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ye(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(s=(i[4]<<8)+i[5],s&&s>r.size-6)return null;let c=i[7];c&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,c&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let h=n+9;if(r.size<=h)return null;r.size-=h;let u=new Uint8Array(r.size);for(let f=0,g=l.length;f<g;f++){i=l[f];let m=i.byteLength;if(h)if(h>m){h-=m;continue}else i=i.subarray(h),m-=h,h=0;u.set(i,t),t+=m}return s&&(s-=n+3),{data:u,pts:a,dts:o,len:s}}return null}var Gn=class{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;let t=ms(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let i=(e[3]&48)>>4;if(i===0)return;let s=e[3]&15,n=this.lastContinuityCounter;this.lastContinuityCounter=s;let a=(i&1)!=0;if((i&2)!=0&&e[4]!=0&&(e[5]&128)!=0||n<0)return;let d=a?n+1&15:n;if(s!==d){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${s}, Expected-CC=${d} Last-CC=${n}`),this.integrityState="cc-failed";return}if(e[1]&128){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}},Vn=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)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(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)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(t===2)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(t===3)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]);break}}},ps,yu={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},tn=new Uint8Array([0,0,0,0,0,0,0,0]),vu=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Eu=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Tu=new Uint8Array([0,0,0,0,0,0,0,0]),Xt=new Uint8Array([0,0,0,0,0,0,0,1]),lo=new Uint8Array([105,115,111,109]),Su=new Uint8Array([97,118,99,49]),bu=new Uint8Array([0,0,0,1]),ft=class r{static box(e,...t){let i=8,s=t.length,n=s;for(;s--;)i+=t[s].byteLength;let a=new Uint8Array(i);for(Se(a,0,i),Se(a,4,e),s=0,i=8;s<n;s++)a.set(t[s],i),i+=t[s].byteLength;return a}static hdlr(e){return r.box(X.hdlr,yu[e])}static mdat(e){return r.box(X.mdat,e)}static mdhd(e,t){t*=e;let i=Math.floor(t/(nt+1)),s=Math.floor(t%(nt+1));return r.box(X.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return r.box(X.mdia,r.mdhd(e.timescale||0,e.duration||0),r.hdlr(e.type),r.minf(e))}static mfhd(e){return r.box(X.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?r.box(X.minf,r.box(X.smhd,Tu),r.DINF,r.stbl(e)):r.box(X.minf,r.box(X.vmhd,Eu),r.DINF,r.stbl(e))}static moof(e,t,i){return r.box(X.moof,r.mfhd(e),r.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=r.trak(e[t]);return r.box.apply(null,[X.moov,r.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(r.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=r.trex(e[t]);return r.box.apply(null,[X.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(nt+1)),s=Math.floor(t%(nt+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,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 r.box(X.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),s,n;for(s=0;s<t.length;s++)n=t[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return r.box(X.sdtp,i)}static stbl(e){return r.box(X.stbl,r.stsd(e),r.box(X.stts,tn),r.box(X.stsc,tn),r.box(X.stsz,vu),r.box(X.stco,tn))}static avc1(e){let t=[],i=[],s,n,a;for(s=0;s<e.sps.length;s++)n=e.sps[s],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(s=0;s<e.pps.length;s++)n=e.pps[s],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));let o=r.box(X.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,d=e.height,c=e.pixelRatio[0],h=e.pixelRatio[1];return r.box(X.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,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,r.box(X.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r.box(X.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){let t=e.config,i=t.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return r.box(X.mp4a,r.audioStsd(e),r.box(X.esds,r.esds(e)))}static mp3(e){return r.box(X[".mp3"],r.audioStsd(e))}static ac3(e){return r.box(X["ac-3"],r.audioStsd(e),r.box(X.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return r.box(X.stsd,Xt,r.mp4a(e));if(t==="ac3"&&e.config)return r.box(X.stsd,Xt,r.ac3(e));if(t==="mp3"&&e.codec==="mp3")return r.box(X.stsd,Xt,r.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return r.box(X.stsd,Xt,r.avc1(e));if(t==="hevc"&&e.vps)return r.box(X.stsd,Xt,r.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,n=e.height||0,a=Math.floor(i/(nt+1)),o=Math.floor(i%(nt+1));return r.box(X.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,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,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=r.sdtp(e),s=e.id,n=Math.floor(t/(nt+1)),a=Math.floor(t%(nt+1));return r.box(X.traf,r.box(X.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),r.box(X.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),r.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,r.box(X.trak,r.tkhd(e),r.mdia(e))}static trex(e){let t=e.id;return r.box(X.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i=e.samples||[],s=i.length,n=12+16*s,a=new Uint8Array(n),o,l,d,c,h,u;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)l=i[o],d=l.duration,c=l.size,h=l.flags,u=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return r.box(X.trun,a)}static initSegment(e){let t=r.moov(e);return Ye(r.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],s=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),s-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),a=n.length;for(let g=0;g<i.length;g+=1){a+=3;for(let m=0;m<i[g].length;m+=1)a+=2+i[g][m].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=i.length-1;for(let g=0;g<i.length;g+=1){o.set(new Uint8Array([32+g|(g===l?128:0),0,i[g].length]),a),a+=3;for(let m=0;m<i[g].length;m+=1)o.set(new Uint8Array([i[g][m].length>>8,i[g][m].length&255]),a),a+=2,o.set(i[g][m],a),a+=i[g][m].length}let d=r.box(X.hvcC,o),c=e.width,h=e.height,u=e.pixelRatio[0],f=e.pixelRatio[1];return r.box(X.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,c>>8&255,c&255,h>>8&255,h&255,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]),d,r.box(X.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r.box(X.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,f>>24,f>>16&255,f>>8&255,f&255])))}};ps=ft;ft.FTYP=ps.box(X.ftyp,lo,bu,lo,Su);ft.DINF=ps.box(X.dinf,ps.box(X.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var Jl=9e4;function Zr(r,e,t=1,i=!1){let s=r*e*t;return i?Math.round(s):s}function Au(r,e,t=1,i=!1){return Zr(r,e,1/t,i)}function Qt(r,e=!1){return Zr(r,1e3,1/Jl,e)}function xu(r,e=1){return Zr(r,Jl,1/e)}function co(r){let{baseTime:e,timescale:t,trackId:i}=r;return`${e/t} (${e}/${t}) trackId: ${i}`}var Iu=10*1e3,Lu=1024,Ru=1152,Pu=1536,Hn=8589934592;function ho(r,e,t,i){return{duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1,paddingValue:0}}}var Ht=class extends Oe{constructor(e,t,i,s){super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&co(t)} > ${e&&co(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e[0].pts,s=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=Ve(o,i),l=o-n),l>0?n:o},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,n,a,o,l,d){let c,h,u,f,g,m,p=n,v=n,E=!d.iframe&&e.pid>-1,S=t.pid>-1,b=t.samples.length,A=e.samples.length>0,x=o&&b>0||b>1;if((!E||A)&&(!S||x)||this.ISGenerated||o){if(this.ISGenerated){var P,I,k,D;let C=this.videoTrackConfig;(C&&(t.width!==C.width||t.height!==C.height||((P=t.pixelRatio)==null?void 0:P[0])!==((I=C.pixelRatio)==null?void 0:I[0])||((k=t.pixelRatio)==null?void 0:k[1])!==((D=C.pixelRatio)==null?void 0:D[1]))||!C&&x||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,n,a));let F=this.isVideoContiguous,G=-1,$;if(x&&(G=_u(t.samples),!F&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,G>0){this.warn(`Dropped ${G} out of ${b} video samples due to a missing keyframe`);let C=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(G),t.dropped+=G,v+=(t.samples[0].pts-C)/t.inputTimeScale,$=v}else G===-1&&(this.warn(`No keyframe found out of ${b} video samples`),m=!1);if(this.ISGenerated){if(A&&x&&n){let C=this.getVideoStartPts(t.samples),w=(Ve(e.samples[0].pts,C)-C)/t.inputTimeScale;p+=Math.max(0,w),v+=Math.max(0,-w)}if(A){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,a)),h=this.remuxAudio(e,p,this.isAudioContiguous,a,S||x||l===H.AUDIO?v:void 0,d),x){let C=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,a)),c=this.remuxVideo(t,v,F,C,d)}}else x&&(c=this.remuxVideo(t,v,F,0,d));c&&(c.firstKeyFrame=G,c.independent=G!==-1,c.firstKeyFramePTS=$)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(g=ed(i,n,this._initPTS,this._initDTS)),s.samples.length&&(f=td(s,n,this._initPTS))),{audio:h,video:c,initSegment:u,independent:m,text:f,id3:g}}computeInitPts(e,t,i,s){let n=Math.round(i*t),a=Ve(e,n);if(a<n)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${s}`);a<n;)a+=Hn;return a-n}generateIS(e,t,i,s){let n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS,c=!d||s,h="audio/mp4",u,f,g,m=-1;if(c&&(u=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):ft.initSegment([e]),metadata:{channelCount:e.channelCount}},c){m=e.id,g=e.inputTimeScale;let p=this.computeInitPts(n[0].pts,g,i,"audio");(!d||g!==d.timescale||i===0&&p<d.baseTime)&&(u=f=p)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:ft.initSegment([t]),metadata:{width:t.width,height:t.height}},c){m=t.id,g=t.inputTimeScale;let p=this.getVideoStartPts(a),v=Ve(a[0].dts,p),T=this.computeInitPts(v,g,i,"video"),E=this.computeInitPts(p,g,i,"video");(!d||g!==d.timescale||B(u)||i===0&&E<d.baseTime)&&(f=Math.min(f,T),u=Math.min(u,T))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,c&&B(u)?(d&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${u/g} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${u/g} (${u}/${g}) trackId: ${m}`),this._initPTS={baseTime:u,timescale:g,trackId:m},this._initDTS={baseTime:f,timescale:g,trackId:m}):u=g=void 0,{tracks:l,initPTS:u,timescale:g,trackId:m}}remuxVideo(e,t,i,s,n){let a=e.inputTimeScale,o=e.samples,l=[],d=o.length,c=this._initPTS,h=c.baseTime*a/c.timescale,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m,p,v=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,E=!1;if(!i||u===null){let O=h+t*a,U=o[0].pts-Ve(o[0].dts,o[0].pts);ei()&&u!==null&&Math.abs(O-U-(u+h))<15e3?i=!0:u=O-U-h}let S=u+h;for(let O=0;O<d;O++){let U=o[O];U.pts=Ve(U.pts,S),U.dts=Ve(U.dts,S),U.dts<o[O>0?O-1:O].dts&&(E=!0)}E&&o.sort(function(O,U){let Z=O.dts-U.dts,j=O.pts-U.pts;return Z||j}),m=o[0].dts,p=o[o.length-1].dts;let b=p-m,A=b?Math.round(b/(d-1)):g||e.inputTimeScale/30;if(i){let O=m-S,U=O>A,Z=O<-1;if((U||Z)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Qt(O,!0)} ms (${O}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Qt(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Z||S>=o[0].pts||ei())){m=S;let j=o[0].pts-O;if(U)o[0].dts=m,o[0].pts=j;else{let ie=!0;for(let z=0;z<o.length&&!(o[z].dts>j&&ie);z++){let ne=o[z].pts;if(o[z].dts-=O,o[z].pts-=O,z<o.length-1){let ee=o[z+1].pts,ae=o[z].pts,be=ee<=ae,Fe=ee<=ne;ie=be==Fe}}}this.log(`Video: Initial PTS/DTS adjusted: ${Qt(j,!0)}/${Qt(m,!0)}, delta: ${Qt(O,!0)} ms`)}}m=Math.max(0,m);let x=0,R=0,P=m;for(let O=0;O<d;O++){let U=o[O],Z=U.units,j=Z.length,ie=0;for(let z=0;z<j;z++)ie+=Z[z].data.length;R+=ie,x+=j,U.length=ie,U.dts<P?(U.dts=P,P+=A/4|0||1):P=U.dts,v=Math.min(U.pts,v),T=Math.max(U.pts,T)}p=o[d-1].dts;let I=R+4*x+8,k;try{k=new Uint8Array(I)}catch(O){this.observer.emit(y.ERROR,y.ERROR,{type:W.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:O,bytes:I,reason:`fail allocating video mdat ${I}`});return}Se(k,0,I),Se(k,4,X.mdat);let D=!1,F=Number.POSITIVE_INFINITY,G=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let O=0;O<d;O++){let U=o[O],Z=U.units,j=0;for(let ne=0,ee=Z.length;ne<ee;ne++){let ae=Z[ne],be=ae.data,Fe=ae.data.byteLength;Se(k,f,Fe),f+=4,k.set(be,f),f+=Fe,j+=4+Fe}let ie;if(O<d-1)g=o[O+1].dts-U.dts,ie=o[O+1].pts-U.pts;else{let ne=this.config,ee=O>0?U.dts-o[O-1].dts:A;if(ie=O>0?U.pts-o[O-1].pts:A,ne.stretchShortVideoTrack&&this.nextAudioTs!==null){let ae=Math.floor(ne.maxBufferHole*a),be=(s?v+s*a:this.nextAudioTs+h)-U.pts;be>ae?(g=be-ee,g<0?g=ee:D=!0,this.log(`It is approximately ${be/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=ee}else g=ee}let z=Math.round(U.pts-U.dts);if(F=Math.min(F,g),$=Math.max($,g),G=Math.min(G,ie),C=Math.max(C,ie),!i&&O===0&&z>g){let ne=Math.round(z/A)*A;ne-z===1&&(this.log(`pad first CTS ${z} -> ${ne} of sn: ${n.sn}`),z=ne)}l.push(ho(U.key,g,j,z))}if(l.length){let O=ei();if(O){if(O<70){let U=l[0].flags;U.dependsOn=2,U.isNonSync=0}}else if(qc()&&C-G<$-F&&A/$<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let U=m;for(let Z=0,j=l.length;Z<j;Z++){let ie=U+l[Z].duration,z=U+l[Z].cts;if(Z<j-1){let ne=ie+l[Z+1].cts;l[Z].duration=ne-z}else l[Z].duration=Z?l[Z-1].duration:A;l[Z].cts=0,U=ie}}}g=D||!g?A:g;let M=p+g;this.nextVideoTs=u=M-h,this.videoSampleDuration=g,this.isVideoContiguous=!0,n.iframe&&(l.length===1?(l[0].duration=g=n.duration*a,this.nextVideoTs=u=m+g-h):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));let K={data1:ft.moof(n.sn,m,ce(e,{samples:l})),data2:k,startPTS:(v-h)/a,endPTS:(T+g-h)/a,startDTS:(m-h)/a,endDTS:u/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,K}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Ru;case"ac3":return Pu;default:return Lu}}remuxAudio(e,t,i,s,n,a){let o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,d=o/l,c=this.getSamplesPerFrame(e),h=c*d,u=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],m=n!==void 0,p=e.samples,v=f?0:8,T=this.nextAudioTs||-1,E=u.baseTime*o/u.timescale,S=E+t*o;if(this.isAudioContiguous=i=i||p.length&&T>0&&(s&&Math.abs(S-(T+E))<9e3||Math.abs(Ve(p[0].pts,S)-(T+E))<20*h),p.forEach(function(M){M.pts=Ve(M.pts,S)}),!i||T<0){let M=p.length;if(p=p.filter(w=>w.pts>=0),M!==p.length&&this.warn(`Removed ${p.length-M} of ${M} samples (initPTS ${E} / ${o})`),!p.length)return;n===0?T=0:s&&!m?T=Math.max(0,S-E):T=p[0].pts-E}if(e.segmentCodec==="aac"){let M=this.config.maxAudioFramesDrift;for(let w=0,N=T+E;w<p.length;w++){let K=p[w],O=K.pts,U=O-N,Z=Math.abs(1e3*U/o);if(U<=-M*h&&m)w===0&&(this.warn(`Audio frame @ ${(O/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*U/o)} ms.`),this.nextAudioTs=T=O-E,N=O);else if(U>=M*h&&Z<Iu&&m){let j=Math.round(U/h);for(N=O-j*h;N<0&&j&&h;)j--,N+=h;w===0&&(this.nextAudioTs=T=N-E),this.warn(`Injecting ${j} audio frames @ ${((N-E)/o).toFixed(3)}s due to ${Math.round(1e3*U/o)} ms gap.`);for(let ie=0;ie<j;ie++){let z=Vn.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);z||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),z=K.unit.subarray()),p.splice(w,0,{unit:z,pts:N}),N+=h,w++}}K.pts=N,N+=h}}let b=null,A=null,x,R=0,P=p.length;for(;P--;)R+=p[P].unit.byteLength;for(let M=0,w=p.length;M<w;M++){let N=p[M],K=N.unit,O=N.pts;if(A!==null){let Z=g[M-1];Z.duration=Math.round((O-A)/d)}else if(i&&e.segmentCodec==="aac"&&(O=T+E),b=O,R>0){R+=v;try{x=new Uint8Array(R)}catch(Z){this.observer.emit(y.ERROR,y.ERROR,{type:W.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:Z,bytes:R,reason:`fail allocating audio mdat ${R}`});return}f||(Se(x,0,R),Se(x,4,X.mdat))}else return;x&&x.set(K,v);let U=K.byteLength;v+=U,g.push(ho(!0,c,U,0)),A=O}let I=g.length;if(!I)return;let k=g[g.length-1];T=A-E,this.nextAudioTs=T+d*k.duration;let D=f?new Uint8Array(0):ft.moof(e.sequenceNumber++,b/d,ce({},e,{samples:g}));e.samples=[];let F=(b-E)/o,G=this.nextAudioTs/o,C={data1:D,data2:x,startPTS:F,endPTS:G,startDTS:F,endDTS:G,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,C}};function Ve(r,e){let t;if(e===null)return r;for(e<r?t=-Hn:t=Hn;Math.abs(r-e)>4294967296;)r+=t;return r}function _u(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function ed(r,e,t,i){let s=r.samples.length;if(!s)return;let n=r.inputTimeScale;for(let o=0;o<s;o++){let l=r.samples[o];l.pts=Ve(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=Ve(l.dts-i.baseTime*n/i.timescale,e*n)/n}let a=r.samples;return r.samples=[],{samples:a}}function td(r,e,t){let i=r.samples.length;if(!i)return;let s=r.inputTimeScale;for(let a=0;a<i;a++){let o=r.samples[a];o.pts=Ve(o.pts-t.baseTime*s/t.timescale,e*s)/s}r.samples.sort((a,o)=>a.pts-o.pts);let n=r.samples;return r.samples=[],{samples:n}}var Kn=class extends Oe{constructor(e,t,i,s){super("passthrough-remuxer",s),this.observer=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.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.decryptdata=s,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,i){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:a,video:o}=this.initData=i||ol(e);if(t)Dc(e,t);else{let d=a||o;d!=null&&d.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${d.codec}")!`)}a&&(s=uo(a,he.AUDIO,this)),o&&(n=uo(o,he.VIDEO,this));let l={};a&&o?l.audiovideo={container:"video/mp4",codec:s+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:s,encrypted:a.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,i,s,n,a,o,l,d,c,h){var u,f;let{initPTS:g,lastEndTime:m}=this,p={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};B(m)||(m=this.lastEndTime=n||0);let v=t.samples;if(!v.length)return p;let T=this.pendingInitSegment;T&&(this.pendingInitSegment=void 0,this.generateInitSegment(T,this.decryptdata,c));let E={initPTS:void 0,timescale:void 0,trackId:void 0},S=this.initData;if((u=S)!=null&&u.length||(this.generateInitSegment(v),S=this.initData),!((f=S)!=null&&f.length))return this.warn("Failed to generate initSegment."),p;if(d.iframe&&S.audio&&S.video){var b;let q=(b=this.initTracks)==null||(b=b.audiovideo)==null?void 0:b.initSegment,se=q?Ic(q):null;if(se){var A;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(se,this.decryptdata),(A=this.initData)!=null&&A.length&&(S=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(E.tracks=this.initTracks,p.initSegment=E,this.emitInitSegment=!1);let x=d.iframe,R=h&&(!x||h.includeSampleDetails)?h.tracks:Oc(v,S,d,this,x),P=S.audio?R[S.audio.id]:null,I=S.video?R[S.video.id]:null,k=!!S.audio,D=!!S.video,F="";k&&(F+="audio"),D&&(F+="video");let G=Mi(I,1/0),$=Mi(P,1/0),C=Mi(I,0,!0),M=Mi(P,0,!0),w=n,N=0;I&&P&&S.audio&&($>C||G>M)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${G}-${C} a: ${$}-${M}}`,I,P);let K=!!P&&(!I||!g&&$<G||!!g&&g.trackId===S.audio.id),O=K?P:I;if(!O)return this.log(`No media samples found in ${l} ${d.level} ${d.part===-1?"":`part: ${d.part} of`} sn: ${d.sn} at playlist time: ${n}`),p;let U=v,Z,j;if(I&&I.sampleCount>=1&&S.video&&d.iframe){let{trun:q,start:se}=I,re=q.length===1,Ae=q.length?re?q[0].samples:q[0].samples.concat(...q.slice(1).map(Te=>Te.samples)):[];if(Ae.length){let Te=q[0],Ce=Te;for(let $e=q.length;$e--;)if(q[$e].samples.length){Ce=q[$e];break}let je=Ce.lastSampleDurationOffset,{defaultSampleDurationOffset:It}=Te,Pe=Math.abs(d.duration-(C-G))>.05,we=Ae.length<I.sampleCount;if(!(Pe||we||this.videoOnlyRemux||!re))N=C-G;else{let $e=we?Ce.sampleOffset+Ce.samples.reduce((ze,va)=>ze+va.size,0):void 0,De=Pe?d.duration:C-G,gt=Du(Ae,De*S.video.timescale,je,It),ct=Lc(v,S.video.id,Ae.length,$e,gt);ct?(U=ct,j=ku(se,Ae)):this.warn(`IFrame remux skipped (sn ${d.sn}); using native sample duration`),N=ct&&gt?De:C-G}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${q.length})`),N=C-G}else N=K?M-$:C-G;if(this.videoOnlyRemux&&U===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${d.sn})`),p;let ie=O.timescale,z=O.start-n*ie,ne=K?S.audio.id:S.video.id;if(w=O.start/ie,(a||!g)&&(Cu(g,w,n,N)||ie!==g.timescale)){let q=!1,se=K?"audio":"video";if(g){let re=n!==0?w/n:1+w/1;q=w>=0&&Math.abs(1-re)<.001,this.log(`${se} timestamps in track ${ne} at playlist time: ${a?"":"~"}${n} maps to ${w} with initPTS: ${g.baseTime/g.timescale} (${z/ie-g.baseTime/g.timescale}s diff) (${F}) drift estimate: ${re} ${q?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}q||(this.log(`Found initPTS in ${se} track ${ne} at playlist time: ${n} offset: ${w-n} (${z}/${ie})`),g=null,E.initPTS=z,E.timescale=ie,E.trackId=ne)}g?(E.initPTS=g.baseTime,E.timescale=g.timescale,E.trackId=g.trackId):((!E.timescale||E.trackId===void 0||E.initPTS===void 0)&&(this.warn("Could not set initPTS"),E.initPTS=w,E.timescale=1,E.trackId=-1),this.initPTS=g={baseTime:E.initPTS,timescale:E.timescale,trackId:E.trackId});let ee=w-g.baseTime/g.timescale,ae=ee+N,be=D&&O?.ptsMin!==void 0?O.ptsMin/O.timescale-g.baseTime/g.timescale:ee,Fe=j!==void 0&&I?j/I.timescale-g.baseTime/g.timescale:D&&O!=null&&O.ptsMax?O.ptsMax/O.timescale-g.baseTime/g.timescale:ae;N>0?this.lastEndTime=ae:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let dt=(S.audio?S.audio.encrypted:!1)||(S.video?S.video.encrypted:!1),ge={data1:U,data2:Z,startPTS:be,startDTS:ee,endPTS:Fe,endDTS:ae,type:F,hasAudio:k,hasVideo:D,nb:1,dropped:0,encrypted:dt};p.audio=k&&!D?ge:void 0,p.video=D?ge:void 0;let Ke=this.isVideoContiguous,tt=I?.sampleCount;if(tt){let q=I.keyFrameIndex,se=q!==-1;ge.nb=tt,ge.dropped=q===0||Ke?0:se?q:tt,ge.independent=se,ge.firstKeyFrame=q,se&&I.keyFrameStart&&(ge.firstKeyFramePTS=(I.keyFrameStart-g.baseTime)/g.timescale),Ke||(p.independent=se),this.isVideoContiguous||(this.isVideoContiguous=se),ge.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${q}/${tt} dropped: ${ge.dropped} start: ${ge.firstKeyFramePTS||"NA"}`)}return p.initSegment=E,p.id3=ed(i,n,g,g),s.samples.length&&(p.text=td(s,n,g)),p}};function Mi(r,e,t=!1){return r?.start!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function ku(r,e){let t=r,i=r;for(let s=0;s<e.length;s++){let{cts:n,duration:a}=e[s];i=Math.max(i,t+(n||0)+a),t+=a}return i}function Du(r,e,t,i){if(t!==void 0){let n=r[r.length-1],a=e;for(let o=0;o<r.length-1;o++)a-=r[o].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:t,value:a}}if(i===void 0)return;let s=Math.round(e/r.length);for(let n=0;n<r.length;n++)r[n].duration=s;return{durationOffset:i,value:s}}function Cu(r,e,t,i){if(r===null)return!0;let s=Math.max(i,1),n=e-r.baseTime/r.timescale;return Math.abs(n-t)>=s}function uo(r,e,t){let i=r.codec;return i&&i.length>4?i:e===he.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Qi(i,!1):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):i==="mjpg"?i:(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var vt;try{vt=self.performance.now.bind(self.performance)}catch{vt=Date.now}var qi=[{demux:Nn,remux:Kn},{demux:gs,remux:Ht},{demux:Mn,remux:Ht},{demux:Fn,remux:Ht}];qi.splice(2,0,{demux:On,remux:Ht});var ys=class{constructor(e,t,i,s,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){if(!this.observer)return Oi(i);let n=i.transmuxing;n.executeStart=vt();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);let{contiguous:d,discontinuity:c,trackSwitch:h,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:m,videoCodec:p,defaultInitPts:v,duration:T,initSegmentData:E}=l,S=wu(a,t);if(S&&Vt(S.method)){let R=this.getDecrypter(),P=Yr(S.method);return this.asyncResult=!0,this.decryptionPromise=R.decrypt(a,S.key.buffer,S.iv.buffer,P,i.decryptRange).then(I=>{let k=this.push(I,null,i);return this.decryptionPromise=null,k}),this.decryptionPromise}let b=this.needsProbing(c,h);if(b){let R=i.iframe&&E&&gs.probe(E,this.logger)?E:a,P=this.configureTransmuxer(R);if(P)return this.logger.warn(`[transmuxer] ${P.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:P,reason:P.message}),n.executeEnd=vt(),Oi(i)}(c||h||g||b)&&this.resetInitSegment(E,m,p,T,t,i),(c||g||b)&&this.resetInitialTimestamp(v),d||this.resetContiguity();let A=this.transmux(a,S,f,u,i);this.asyncResult=vi(A);let x=this.currentTransmuxState;return x.contiguous=!0,x.discontinuity=!1,x.trackSwitch=!1,n.executeEnd=vt(),A}flush(e){let t=e.transmuxing;t.executeStart=vt();let{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=s;if(i){let h=i.flush();h&&a.push(this.push(h.buffer,null,e))}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=vt();let h=[Oi(e)];return this.asyncResult?Promise.resolve(h):h}let c=l.flush(o,e);return vi(c)?(this.asyncResult=!0,c.then(h=>(this.flushRemux(a,h,e),a))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){if(!this.remuxer)return;let{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);let c=this.remuxer.remux(s,n,a,o,d,l,!0,this.id,i,t.initData,t.sampleData);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=vt()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,n,a){let{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,i,s,n,a),l.resetInitSegment(e,t,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,i,s,n){let a;return t?.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,s,n):a=this.transmuxUnencrypted(e,i,s,n),a}transmuxUnencrypted(e,t,i,s){let{demuxer:n,remuxer:a}=this;if(!n||!a)return Oi(s);let o=n.demux(e,t,s,!1,!this.config.progressive),{audioTrack:l,videoTrack:d,id3Track:c,textTrack:h}=o;return{remuxResult:a.remux(l,d,c,h,t,i,!1,this.id,s,o.initData,o.sampleData),chunkMeta:s}}transmuxSampleAes(e,t,i,s,n){return this.demuxer?this.demuxer.demuxSampleAes(e,t,i,n).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id,n,a.initData,a.sampleData),chunkMeta:n})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:s}=this;if(!i)return;let n;try{for(let h=0,u=qi.length;h<u;h++){var a;if((a=qi[h].demux)!=null&&a.probe(e,this.logger)){n=qi[h];break}}}catch(h){return h}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,d=n.demux,c=n.remux;(!o||!(o instanceof d))&&(this.logger.log(`Using ${d.name}`),this.demuxer=new d(i,t,s,this.logger),this.probe=d.probe),(!l||!(l instanceof c))&&(this.logger.log(`Using ${c.name}`),this.remuxer=new c(i,t,s,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new fi(this.config)),e}};function wu(r,e){let t=null;return r.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var Oi=r=>({remuxResult:{},chunkMeta:r});function vi(r){return"then"in r&&r.then instanceof Function}var qn=class{constructor(e,t,i,s,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}},Wn=class{constructor(e,t,i,s,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=a}},fo=0,vs=class{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=fo++,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=l=>{let d=l.data,c=this.hls;if(!(!c||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var h;let u=(h=this.workerContext)==null?void 0:h.objectURL;u&&self.URL.revokeObjectURL(u);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{c.logger[d.data.logType]&&c.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,c.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;let a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===y.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d)};this.observer=new zr,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);let o=ka(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(n.workerPath||Qh()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Jh(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=Zh());let{worker:c}=this.workerContext;c.addEventListener("message",this.onWorkerMessage),c.addEventListener("error",this.onWorkerError),c.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:fe(n)})}catch(c){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,c),this.terminateWorker(),this.error=null,this.transmuxer=new ys(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new ys(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=fo++;let t=this.hls.config,i=ka(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:fe(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),eu(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,n,a,o,l,d,c){var h,u;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:g}=this,m=a?a.start:n.start,p=n.decryptdata,v=this.frag,T=v?n.cc!==v.cc:!0,E=v?d.level!==v.level:!0,S=v?d.sn-v.sn:-1,b=this.part?d.part-this.part.index:-1,A=S===0&&d.id>1&&d.id===v?.stats.chunkCount,x=!E&&(S===1||S===0&&(b===1||A&&b<=0)),R=self.performance.now();(E||S||n.stats.parsing.start===0)&&(n.stats.parsing.start=R),a&&(b||!x)&&(a.stats.parsing.start=R);let P=!(v&&((h=n.initSegment)==null?void 0:h.url)===((u=v.initSegment)==null?void 0:u.url)),I=new Wn(T,x,l,E,m,P);if(!x||T||P){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id} playlist: ${d.level} id: ${d.id}
17
17
  discontinuity: ${T}
18
18
  trackSwitch: ${E}
19
19
  contiguous: ${x}
20
20
  accurateTimeOffset: ${l}
21
21
  timeOffset: ${m}
22
- initSegmentChange: ${P}`);let k=new Hn(i,s,t,o,c);this.configureTransmuxer(k)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:d,state:I},e instanceof ArrayBuffer?[e]:[]);else if(g){let k=g.push(e,p,d,I);vi(k)?k.then(D=>{this.handleTransmuxComplete(D)}).catch(D=>{this.transmuxerError(D,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(k)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let s=i.flush(e);vi(s)?s.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},ho=100,qn=class extends mi{constructor(e,t,i){super(e,t,i,"audio-stream-controller",H.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){let{frag:i,id:s,initPTS:n,timescale:a,trackId:o,timestampOffsets:l}=t;if(s===H.MAIN){let d=i.cc,c=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${d} found from main: ${n/a} (${n}/${a}) trackId: ${o}`),this.mainAnchor=i,this.state===_.WAITING_INIT_PTS){let h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==d)&&this.syncWithAnchor(i,h?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==d?(c.abortRequests(),this.syncWithAnchor(i,c)):this.state===_.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&s?.cc===t.cc)return;let n=(s||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Sl(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===_.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=_.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(ho),i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=_.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case _.IDLE:this.doTickIdle();break;case _.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=e?.[t],s=i?.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=_.WAITING_INIT_PTS}break}case _.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case _.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:s,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=_.FRAG_LOADING;let o=s.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=_.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;let{hls:t,levels:i,media:s,trackId:n}=this,a=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[n]))return;let o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=_.WAITING_TRACK,this.startFragRequested=!1;return}let d=this.getBufferOutput();this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,he.AUDIO));let c=this.getFwdBufferInfo();if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,l)){t.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=_.ENDED;return}let h=c.len,u=t.maxBufferLength,f=l.fragments,g=f[0].start,m=this.getLoadPosition(),p=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?m:c.end;if(this.switchingTrack&&s){let E=m;l.PTSKnown&&E<g&&E>=this.timelineOffset&&(c.end>g||c.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${E} -> ${g} + 0.05`),s.currentTime=g+.05)}if(h>=u&&!this.switchingTrack&&p<f[f.length-1].start)return;let v=this.getNextFragment(p,l);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,l,c,H.MAIN,u)),!v){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(c,u,v))return;let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&ve(v)&&!v.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===ye.OK&&(this.mainFragLoading=T=null),T&&ve(T))){if(v.start>T.end){let S=this.fragmentTracker.getFragAtPos(p,H.MAIN);S&&S.end>T.end&&(T=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(v.start>T.end)return}this.loadFragment(v,o,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Ct(i))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==_.STOPPED&&(this.setInterval(ho),this.state=_.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(y.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;let{levels:s}=this,{details:n,id:a,groupId:o,track:l}=t;if(!s){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==_.STOPPED&&(this.state=_.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let c=s[a],h=0;if(n.live||(i=c.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(c.details){var u;h=this.alignPlaylists(n,c.details,(u=this.levelLastLoaded)==null?void 0:u.details)}n.alignedSliding||(os(d,n,this),h=n.fragmentStart)}c.details=n,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===_.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=_.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:s,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let c=d.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let h=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new vs(this.hls,H.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let p=s?s.index:-1,v=p!==-1,T=new gi(i.level,i.sn,i.stats.chunkCount,n.byteLength,p,v,i.duration);u.push(n,g,h,"",i,s,c.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);let{cache:m}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new cs,complete:!1};m.push(new Uint8Array(n)),this.state!==_.STOPPED&&(this.state=_.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===H.MAIN&&ve(t.frag)&&(this.mainFragLoading=t,this.state===_.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:i,part:s}=t;if(i.type!==H.AUDIO){!this.audioOnly&&i.type===H.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(ve(i)){let n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(i,s),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,H.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let i=this.fragPlaying,s=e?.level;return(!i||i.level!==s)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var i;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.AUDIO,t);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===te.AUDIO_TRACK&&(this.state=_.IDLE);break;case L.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==he.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==he.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===_.ENDED&&(this.state=_.IDLE);let i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,t),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:c}=o,{details:h}=c,{audio:u,text:f,id3:g,initSegment:m}=n;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l),m!=null&&m.tracks&&this.resetTransmuxer();return}if(this.state=_.PARSING,u&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:p}=this,v=p.nextAudioTrackBufferFlushForwardOffset,T=Math.max(this.getLoadPosition()+v,l.start);super.flushMainBuffer(T,Number.POSITIVE_INFINITY,H.AUDIO)}if(m!=null&&m.tracks){let p=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(c,m.tracks,p,a),s.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:m.tracks})}if(u){let{startPTS:p,endPTS:v,startDTS:T,endDTS:E}=u;d&&(d.elementaryStreams[he.AUDIO]={startPTS:p,endPTS:v,startDTS:T,endDTS:E}),l.setElementaryStreamInfo(he.AUDIO,p,v,T,E),this.bufferFragmentData(u,l,d,a)}if(g!=null&&(t=g.samples)!=null&&t.length){let p=ce({id:i,frag:l,details:h},g);s.trigger(y.FRAG_PARSING_METADATA,p)}if(f){let p=ce({id:i,frag:l,details:h},f);s.trigger(y.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,s){if(this.state!==_.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=H.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a?.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(y.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===ye.NOT_LOADED||s===ye.PARTIAL){var n;if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=_.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&os(a,t.details,this)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;kt({name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o},e,_t)||(es(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(y.AUDIO_TRACK_SWITCHED,Y({},e))}get nextAudioTrack(){return this.nextTrackId}},Ei=class extends Oe{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let s=t?.renditionReports;if(s){let n=-1;for(let a=0;a<s.length;a++){let o=s[a],l;try{l=new self.URL(o.URI,t.url).href}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){let a=s[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let c=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&c>t.partTarget&&(l+=1)}let d=i&&Pa(i);return new Ji(o,l>=0?l:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){let{details:s,stats:n}=t,a=s.fragments,o=self.performance.now(),l=n.loading.first?Math.max(0,Math.floor(o-n.loading.first)):0;s.advancedDateTime=Date.now()-l;let d=this.hls.config.timelineOffset;if(d!==s.appliedTimelineOffset){let h=Math.max(d||0,0);s.appliedTimelineOffset=h,a.forEach(u=>{u?.setStart(u.playlistOffset+h)})}if(s.live||i!=null&&i.live){var c;let h="levelInfo"in t?t.levelInfo:t.track;s.reloaded(i);let u=(c=a[a.length-1])==null?void 0:c.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let b=new Error(`${u} playlist ${h.id} hit max allowed unchanged reloads.`);this.warn(b);let{networkDetails:A,context:x}=t;this.hls.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:b,reason:b.message,level:t.level,parent:u,context:x,networkDetails:A,stats:n});return}if(i){Fh(i,s,this);let b=s.playlistParsingError;if(b){this.warn(b);let A=this.hls;if(!A.config.ignorePlaylistParsingErrors){let{networkDetails:x}=t;A.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:b,reason:b.message,level:t.level,parent:u,networkDetails:x,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);let f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,m=(s.edge-g)*1e3,p=wl(s,m);s.requestScheduled+p<o?s.requestScheduled=o:s.requestScheduled<=o&&(s.requestScheduled+=p);let v=t.deliveryDirectives;if(this.log(`live playlist ${e} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${v?` | requested ${v.msn} - ${v.part}`:""})`}`),!this.canLoad||!s.live)return;let T,E,S;if(s.canBlockReload&&s.endSN&&s.advanced){let b=this.hls.config.lowLatencyMode,A=s.lastPartSn,x=s.endSN,R=s.lastPartIndex,P=R!==-1,I=A===x;P?I?(E=x+1,S=b?0:R):(E=A,S=b?R+1:s.maxPartIndex):E=x+1;let k=s.age,D=k+s.ageHeader,F=Math.min(D-s.partTarget,s.targetduration*1.5);if(F>0){if(D>s.targetduration*3)this.log(`Playlist last advanced ${k.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,S=void 0;else if(i!=null&&i.tuneInGoal&&D-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${F} with playlist age: ${s.age}`),F=0;else{let G=Math.floor(F/s.targetduration);if(E+=G,S!==void 0){let $=Math.round(F%s.targetduration/s.partTarget);S+=$}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${k.toFixed(2)}s goal: ${F} skip sn ${G} to part ${S}`)}s.tuneInGoal=F}if(T=this.getDeliveryDirectives(s,t.deliveryDirectives,E,S),b||!I){s.requestScheduled=o,this.loadingPlaylist(h,T);return}}else(s.canBlockReload||s.canSkipUntil)&&(T=this.getDeliveryDirectives(s,t.deliveryDirectives,E,S));T&&E!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(p-l*2,p/2)),this.scheduleLoading(h,T,s)}else this.clearTimer()}scheduleLoading(e,t,i){let s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=s.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}let o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,s){let n=Pa(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=Ki.No),new Ji(i,s,n)}checkRetry(e){let t=e.details,i=zi(e),s=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(n===Re.RetryRequest||!s.resolved&&n===Re.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var c;let h=oi((c=e.response)==null?void 0:c.code);if(this.clearTimer(),h)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let u=Br(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),u)}}e.levelRetry=!0,s.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),oi(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}};function Jl(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Ti(r[t].attrs,e[t].attrs))return!1;return!0}function Ti(r,e,t){let i=r["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>r[s]!==e[s])}var Wn=class extends Ei{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,s=this.groupIds,n=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(o=>s?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(u=>ui(u.groupId,i));if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,f)=>{u.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let u=ot(l,o,_t);if(u>-1)n=o[u];else{let f=ot(l,this.tracks);n=this.tracks[f]}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,c);let h=this.trackId;if(d!==-1&&h===-1)this.setAudioTrack(d);else if(o.length&&h===-1){var a;let u=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(u.message),this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(e,t){t.fatal||!t.context||t.context.type===te.AUDIO_TRACK&&t.context.id===this.trackId&&ui(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let s=this.currentTrack;if(s&&kt(e,s,_t))return s;let n=ot(e,this.tracksInGroup,_t);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in e&&e.flushImmediate),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=uh(e,t.levels,i,a,_t);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=ot(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e,t=!0){let i=this.tracksInGroup;if(e<0||e>=i.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,n=i[e],a=n.details&&!n.details.live;if(e===this.trackId&&n===s&&a||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(y.AUDIO_TRACK_SWITCHING,Y(Y({},n),{},{flushImmediate:t})),a))return;let o=this.switchParams(n.url,s?.details,n.details);this.loadPlaylist(o)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||kt(e,s,_t)))return i}if(e){let{name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){let c=t[d];if(kt({name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:l},c,_t))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Ti(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Ti(e.attrs,c.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&es(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},Yn=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;let s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=(t=e[0])==null?void 0:t.label;i==="async-blocker"||i==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):i==="block-audio"&&e.splice(0,1)})}insertNext(e,t){this.queues!==null&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let s=t[0];try{s.execute()}catch(n){var i;if(s.onError(n),this.queues===null||this.tracks===null)return;let a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
22
+ initSegmentChange: ${P}`);let k=new qn(i,s,t,o,c);this.configureTransmuxer(k)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:d,state:I},e instanceof ArrayBuffer?[e]:[]);else if(g){let k=g.push(e,p,d,I);vi(k)?k.then(D=>{this.handleTransmuxComplete(D)}).catch(D=>{this.transmuxerError(D,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(k)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let s=i.flush(e);vi(s)?s.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},go=100,Yn=class extends mi{constructor(e,t,i){super(e,t,i,"audio-stream-controller",H.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){let{frag:i,id:s,initPTS:n,timescale:a,trackId:o,timestampOffsets:l}=t;if(s===H.MAIN){let d=i.cc,c=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${d} found from main: ${n/a} (${n}/${a}) trackId: ${o}`),this.mainAnchor=i,this.state===_.WAITING_INIT_PTS){let h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==d)&&this.syncWithAnchor(i,h?.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==d?(c.abortRequests(),this.syncWithAnchor(i,c)):this.state===_.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let s=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&s?.cc===t.cc)return;let n=(s||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=xl(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===_.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=_.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(go),i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=_.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case _.IDLE:this.doTickIdle();break;case _.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=e?.[t],s=i?.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=_.WAITING_INIT_PTS}break}case _.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case _.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:s,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=_.FRAG_LOADING;let o=s.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=_.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;let{hls:t,levels:i,media:s,trackId:n}=this,a=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[n]))return;let o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=_.WAITING_TRACK,this.startFragRequested=!1;return}let d=this.getBufferOutput();this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,he.AUDIO));let c=this.getFwdBufferInfo();if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,l)){t.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=_.ENDED;return}let h=c.len,u=t.maxBufferLength,f=l.fragments,g=f[0].start,m=this.getLoadPosition(),p=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?m:c.end;if(this.switchingTrack&&s){let E=m;l.PTSKnown&&E<g&&E>=this.timelineOffset&&(c.end>g||c.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${E} -> ${g} + 0.05`),s.currentTime=g+.05)}if(h>=u&&!this.switchingTrack&&p<f[f.length-1].start)return;let v=this.getNextFragment(p,l);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,l,c,H.MAIN,u)),!v){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(c,u,v))return;let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&ve(v)&&!v.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===ye.OK&&(this.mainFragLoading=T=null),T&&ve(T))){if(v.start>T.end){let S=this.fragmentTracker.getFragAtPos(p,H.MAIN);S&&S.end>T.end&&(T=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(v.start>T.end)return}this.loadFragment(v,o,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Ct(i))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==_.STOPPED&&(this.setInterval(go),this.state=_.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(y.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;let{levels:s}=this,{details:n,id:a,groupId:o,track:l}=t;if(!s){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==_.STOPPED&&(this.state=_.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let c=s[a],h=0;if(n.live||(i=c.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(c.details){var u;h=this.alignPlaylists(n,c.details,(u=this.levelLastLoaded)==null?void 0:u.details)}n.alignedSliding||(os(d,n,this),h=n.fragmentStart)}c.details=n,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(y.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===_.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=_.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:s,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let c=d.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let h=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new vs(this.hls,H.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let p=s?s.index:-1,v=p!==-1,T=new gi(i.level,i.sn,i.stats.chunkCount,n.byteLength,p,v,i.duration);u.push(n,g,h,"",i,s,c.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);let{cache:m}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new cs,complete:!1};m.push(new Uint8Array(n)),this.state!==_.STOPPED&&(this.state=_.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===H.MAIN&&ve(t.frag)&&(this.mainFragLoading=t,this.state===_.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:i,part:s}=t;if(i.type!==H.AUDIO){!this.audioOnly&&i.type===H.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(ve(i)){let n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(i,s),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,H.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let i=this.fragPlaying,s=e?.level;return(!i||i.level!==s)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var i;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.AUDIO,t);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===te.AUDIO_TRACK&&(this.state=_.IDLE);break;case L.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==he.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==he.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===_.ENDED&&(this.state=_.IDLE);let i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,t),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:c}=o,{details:h}=c,{audio:u,text:f,id3:g,initSegment:m}=n;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l),m!=null&&m.tracks&&this.resetTransmuxer();return}if(this.state=_.PARSING,u&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:p}=this,v=p.nextAudioTrackBufferFlushForwardOffset,T=Math.max(this.getLoadPosition()+v,l.start);super.flushMainBuffer(T,Number.POSITIVE_INFINITY,H.AUDIO)}if(m!=null&&m.tracks){let p=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(c,m.tracks,p,a),s.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:m.tracks})}if(u){let{startPTS:p,endPTS:v,startDTS:T,endDTS:E}=u;d&&(d.elementaryStreams[he.AUDIO]={startPTS:p,endPTS:v,startDTS:T,endDTS:E}),l.setElementaryStreamInfo(he.AUDIO,p,v,T,E),this.bufferFragmentData(u,l,d,a)}if(g!=null&&(t=g.samples)!=null&&t.length){let p=ce({id:i,frag:l,details:h},g);s.trigger(y.FRAG_PARSING_METADATA,p)}if(f){let p=ce({id:i,frag:l,details:h},f);s.trigger(y.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,i,s){if(this.state!==_.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=H.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a?.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(y.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(y.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===ye.NOT_LOADED||s===ye.PARTIAL){var n;if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=_.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&os(a,t.details,this)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;kt({name:t,lang:i,assocLang:s,characteristics:n,audioCodec:a,channels:o},e,_t)||(es(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(y.AUDIO_TRACK_SWITCHED,Y({},e))}get nextAudioTrack(){return this.nextTrackId}},Ei=class extends Oe{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let s=t?.renditionReports;if(s){let n=-1;for(let a=0;a<s.length;a++){let o=s[a],l;try{l=new self.URL(o.URI,t.url).href}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){let a=s[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let c=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&c>t.partTarget&&(l+=1)}let d=i&&Da(i);return new Ji(o,l>=0?l:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return e}playlistLoaded(e,t,i){let{details:s,stats:n}=t,a=s.fragments,o=self.performance.now(),l=n.loading.first?Math.max(0,Math.floor(o-n.loading.first)):0;s.advancedDateTime=Date.now()-l;let d=this.hls.config.timelineOffset;if(d!==s.appliedTimelineOffset){let h=Math.max(d||0,0);s.appliedTimelineOffset=h,a.forEach(u=>{u?.setStart(u.playlistOffset+h)})}if(s.live||i!=null&&i.live){var c;let h="levelInfo"in t?t.levelInfo:t.track;s.reloaded(i);let u=(c=a[a.length-1])==null?void 0:c.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let b=new Error(`${u} playlist ${h.id} hit max allowed unchanged reloads.`);this.warn(b);let{networkDetails:A,context:x}=t;this.hls.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:b,reason:b.message,level:t.level,parent:u,context:x,networkDetails:A,stats:n});return}if(i){$h(i,s,this);let b=s.playlistParsingError;if(b){this.warn(b);let A=this.hls;if(!A.config.ignorePlaylistParsingErrors){let{networkDetails:x}=t;A.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:b,reason:b.message,level:t.level,parent:u,networkDetails:x,stats:n});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=n.loading.start);let f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,m=(s.edge-g)*1e3,p=Fl(s,m);s.requestScheduled+p<o?s.requestScheduled=o:s.requestScheduled<=o&&(s.requestScheduled+=p);let v=t.deliveryDirectives;if(this.log(`live playlist ${e} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${v?` | requested ${v.msn} - ${v.part}`:""})`}`),!this.canLoad||!s.live)return;let T,E,S;if(s.canBlockReload&&s.endSN&&s.advanced){let b=this.hls.config.lowLatencyMode,A=s.lastPartSn,x=s.endSN,R=s.lastPartIndex,P=R!==-1,I=A===x;P?I?(E=x+1,S=b?0:R):(E=A,S=b?R+1:s.maxPartIndex):E=x+1;let k=s.age,D=k+s.ageHeader,F=Math.min(D-s.partTarget,s.targetduration*1.5);if(F>0){if(D>s.targetduration*3)this.log(`Playlist last advanced ${k.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,S=void 0;else if(i!=null&&i.tuneInGoal&&D-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${F} with playlist age: ${s.age}`),F=0;else{let G=Math.floor(F/s.targetduration);if(E+=G,S!==void 0){let $=Math.round(F%s.targetduration/s.partTarget);S+=$}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${k.toFixed(2)}s goal: ${F} skip sn ${G} to part ${S}`)}s.tuneInGoal=F}if(T=this.getDeliveryDirectives(s,t.deliveryDirectives,E,S),b||!I){s.requestScheduled=o,this.loadingPlaylist(h,T);return}}else(s.canBlockReload||s.canSkipUntil)&&(T=this.getDeliveryDirectives(s,t.deliveryDirectives,E,S));T&&E!==void 0&&s.canBlockReload&&(s.requestScheduled=n.loading.first+Math.max(p-l*2,p/2)),this.scheduleLoading(h,T,s)}else this.clearTimer()}scheduleLoading(e,t,i){let s=i||e.details;if(!s){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=s.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}let o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,i,s){let n=Da(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,n=Ki.No),new Ji(i,s,n)}checkRetry(e){let t=e.details,i=zi(e),s=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(n===Re.RetryRequest||!s.resolved&&n===Re.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var c;let h=oi((c=e.response)==null?void 0:c.code);if(this.clearTimer(),h)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let u=Ur(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),u)}}e.levelRetry=!0,s.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),oi(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}};function id(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Ti(r[t].attrs,e[t].attrs))return!1;return!0}function Ti(r,e,t){let i=r["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>r[s]!==e[s])}var jn=class extends Ei{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Audio track with id:${i} and group:${s} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,s=this.groupIds,n=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(o=>s?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(u=>ui(u.groupId,i));if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,f)=>{u.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let u=ot(l,o,_t);if(u>-1)n=o[u];else{let f=ot(l,this.tracks);n=this.tracks[f]}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,c);let h=this.trackId;if(d!==-1&&h===-1)this.setAudioTrack(d);else if(o.length&&h===-1){var a;let u=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(u.message),this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(e,t){t.fatal||!t.context||t.context.type===te.AUDIO_TRACK&&t.context.id===this.trackId&&ui(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let s=this.currentTrack;if(s&&kt(e,s,_t))return s;let n=ot(e,this.tracksInGroup,_t);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in e&&e.flushImmediate),a}else if(s){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=mh(e,t.levels,i,a,_t);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=ot(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e,t=!0){let i=this.tracksInGroup;if(e<0||e>=i.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,n=i[e],a=n.details&&!n.details.live;if(e===this.trackId&&n===s&&a||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(y.AUDIO_TRACK_SWITCHING,Y(Y({},n),{},{flushImmediate:t})),a))return;let o=this.switchParams(n.url,s?.details,n.details);this.loadPlaylist(o)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let s=t[i];if(!(this.selectDefaultTrack&&!s.default)&&(!e||kt(e,s,_t)))return i}if(e){let{name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){let c=t[d];if(kt({name:i,lang:s,assocLang:n,characteristics:a,audioCodec:o,channels:l},c,_t))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Ti(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Ti(e.attrs,c.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&es(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},zn=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(this.queues===null||this.tracks===null)return;let s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=(t=e[0])==null?void 0:t.label;i==="async-blocker"||i==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):i==="block-audio"&&e.splice(0,1)})}insertNext(e,t){this.queues!==null&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let s=t[0];try{s.execute()}catch(n){var i;if(s.onError(n),this.queues===null||this.tracks===null)return;let a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
23
23
  ${this.list("video")}
24
24
  ${this.list("audio")}
25
- ${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],s=i?.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},uo=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ed="HlsJsTrackRemovedError",Du=.25,Cu=.001,jn=class extends Error{constructor(e){super(e),this.name=ed}},zn=class extends Oe{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=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.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{let{media:s,mediaSource:n}=this;i&&this.log("Media source opened"),!(!s||!n)&&(le(n,"sourceopen",this._onMediaSourceOpen),le(s,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:s,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let i=this.media.error,{appendError:s,appendErrors:n}=this,a=!1;!s&&i&&(a=Math.max(++n.audio,++n.video,++n.audiovideo)>=this.hls.config.appendErrorMaxRetry);let o=new Error(`MediaSource closed while media attached${go(a,i)}`);this.warn(o),this.hls.trigger(y.ERROR,ce({fatal:a},s,{type:W.MEDIA_ERROR,details:L.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:s}=this;i!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this._onMediaError=()=>{let{media:i}=this;if(i){var s,n;this.log(`Media error (code: ${(s=i.error)==null?void 0:s.code}): ${(n=i.error)==null?void 0:n.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=sc(bt(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=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,this._onMediaEmptied=this._onMediaError=null}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_APPENDING,this.onBufferAppending,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.BUFFER_EOS,this.onBufferEos,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.FRAG_PARSED,this.onFragParsed,this),e.on(y.FRAG_CHANGED,this.onFragChanged,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_APPENDING,this.onBufferAppending,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_EOS,this.onBufferEos,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.FRAG_PARSED,this.onFragParsed,this),e.off(y.FRAG_CHANGED,this.onFragChanged,this),e.off(y.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===t?ce(i,s.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(i[a]=ce({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){let e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let s=bt(this.appendSource);if(s){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,fo(i),wu(i,o),i.load()}catch{i.src=o}else i.src=o}de(i,"emptied",this._onMediaEmptied),de(i,"error",this._onMediaError),this.appendSource&&de(i,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),de(e,"sourceopen",this._onMediaSourceOpen),de(e,"sourceended",this._onMediaSourceEnded),de(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(de(e,"startstreaming",this._onStartStreaming),de(e,"endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,s=t.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
25
+ ${this.list("audiovideo")}}`}list(e){var t,i;return(t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],s=i?.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},mo=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,sd="HlsJsTrackRemovedError",Mu=.25,Ou=.001,Xn=class extends Error{constructor(e){super(e),this.name=sd}},Qn=class extends Oe{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=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.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=i=>{let{media:s,mediaSource:n}=this;i&&this.log("Media source opened"),!(!s||!n)&&(le(n,"sourceopen",this._onMediaSourceOpen),le(s,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:s,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let i=this.media.error,{appendError:s,appendErrors:n}=this,a=!1;!s&&i&&(a=Math.max(++n.audio,++n.video,++n.audiovideo)>=this.hls.config.appendErrorMaxRetry);let o=new Error(`MediaSource closed while media attached${yo(a,i)}`);this.warn(o),this.hls.trigger(y.ERROR,ce({fatal:a},s,{type:W.MEDIA_ERROR,details:L.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:s}=this;i!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this._onMediaError=()=>{let{media:i}=this;if(i){var s,n;this.log(`Media error (code: ${(s=i.error)==null?void 0:s.code}): ${(n=i.error)==null?void 0:n.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=ac(bt(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=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,this._onMediaEmptied=this._onMediaError=null}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_APPENDING,this.onBufferAppending,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.BUFFER_EOS,this.onBufferEos,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.FRAG_PARSED,this.onFragParsed,this),e.on(y.FRAG_CHANGED,this.onFragChanged,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_APPENDING,this.onBufferAppending,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_EOS,this.onBufferEos,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.FRAG_PARSED,this.onFragParsed,this),e.off(y.FRAG_CHANGED,this.onFragChanged,this),e.off(y.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===t?ce(i,s.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(i[a]=ce({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){let e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let s=bt(this.appendSource);if(s){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,po(i),Fu(i,o),i.load()}catch{i.src=o}else i.src=o}de(i,"emptied",this._onMediaEmptied),de(i,"error",this._onMediaError),this.appendSource&&de(i,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),de(e,"sourceopen",this._onMediaSourceOpen),de(e,"sourceended",this._onMediaSourceEnded),de(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(de(e,"startstreaming",this._onStartStreaming),de(e,"endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,s=t.tracks,n=s?Object.keys(s):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
26
26
  required tracks: ${fe(i,(l,d)=>l==="initSegment"?void 0:d)};
27
- transfer tracks: ${fe(s,(l,d)=>l==="initSegment"?void 0:d)}}`),!Yo(s,i)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,c=Math.max(l,d?.fragments[0].start||0);if(c-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${c} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,t),e.currentTime=c;return}this.transferData=void 0,n.forEach(l=>{let d=l,c=s[d];if(c){let h=c.buffer;if(h){let u=this.fragmentTracker,f=c.id;if(u.hasFragments(f)||u.hasParts(f)){let p=J.getBuffered(h);u.detectEvictedFragments(d,p,f,null,null,!0)}let g=en(d),m=[d,h];this.sourceBuffers[g]=m,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,c)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:s,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let l=n.sourceBuffers;for(let d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}le(n,"sourceopen",this._onMediaSourceOpen),le(n,"sourceended",this._onMediaSourceEnded),le(n,"sourceclose",this._onMediaSourceClose),this.appendSource&&(le(n,"startstreaming",this._onStartStreaming),le(n,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(le(s,"emptied",this._onMediaEmptied),le(s,"error",this._onMediaError),le(s,"seeking",this._onStartStreaming),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&fo(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[en(e)]=[null,null];let t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Yn(this.tracks)}onBufferCodecs(e,t){var i;let s=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!s[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,c;let h=t[l],{id:u,codec:f,levelCodec:g,container:m,metadata:p,supplemental:v}=h,T=s[l],E=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],S=E!=null&&E.buffer?E:T,b=S?.pendingCodec||S?.codec,A=S?.levelCodec;T||(T=s[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:m,levelCodec:g,metadata:p,id:u});let x=Hi(b,A),R=x?.replace(uo,"$1"),P=Hi(f,g),I=(c=P)==null?void 0:c.replace(uo,"$1");P&&x&&R!==I&&(l.slice(0,5)==="audio"&&(P=Qi(P,this.appendSource)),this.log(`switching codec ${b} to ${P}`),P!==(T.pendingCodec||T.codec)&&(T.pendingCodec=P),T.container=m,this.appendChangeType(l,m,P))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let s=`${t};codecs=${i}`,n={label:`change-type=${s}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,H.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>s||J.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,s)||((l=this.fragmentTracker.getAppendedFrag(s,H.MAIN))==null?void 0:l.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(a,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:i}=this,{data:s,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:c}=t,h=d.buffering[n],u=ve(o)&&!l&&!o.gap&&!d.partial&&!d.iframe,f=null,g=!1,{sn:m,cc:p}=o,v=self.performance.now();h.start=v;let T=o.stats.buffering,E=l?l.stats.buffering:null;T.start===0&&(T.start=v),E?.start===0&&(E.start=v);let S=i.audio,b=!1;n==="audio"&&S?.container==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let A=i.video,x=A?.buffer;if(x&&m!=="initSegment"&&c!==void 0){let I=S?.buffer,k=l||o;if(n==="audio"&&a!=="main"&&!(A.ending||A.ended)&&I&&J.getBuffered(I).length){let F=k.start+k.duration*.05,G=J.getBuffered(x),$=this.currentOp("video");!G.length&&!$?this.blockAudio(k):!J.isBuffered(x,F)&&this.lastVideoAppendEnd<F&&this.blockAudio(k)}else if(n==="video"){let D=k.end,F=this.lastVideoAppendEnd-D;this.lastVideoAppendEnd=D,F<0||F>k.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}let R=(l||o).start,P={label:`append-${n}`,execute:()=>{var I;h.executeStart=self.performance.now();let k=(I=this.tracks[n])==null?void 0:I.buffer;k&&(u&&(f=J.timeRangesToArray(J.getBuffered(k)),g=po(tn(f,o),o)),b?this.updateTimestampOffset(k,R,.1,n,m,p):c!==void 0&&B(c)&&this.updateTimestampOffset(k,c,1e-6,n,m,p)),this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[n]);let I=self.performance.now();h.executeEnd=h.end=I,T.first===0&&(T.first=I),E?.first===0&&(E.first=I);let k={};if(this.sourceBuffers.forEach(([D,F])=>{D&&(k[D]=J.getBuffered(F))}),u){let D=this.getFragmentAppendProgress(o),F=k[n];if(F&&f){let G=J.timeRangesToArray(F),$=tn(G,o);D.progressed||(D.progressed=$-tn(f,o)>Cu);let C=g&&po($,o);D.fullyBuffered[n]=(D.fullyBuffered[n]===void 0||D.fullyBuffered[n])&&C}}this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:a,timeRanges:k})},onError:I=>{var k;this.clearBufferAppendTimeoutId(this.tracks[n]);let D=I.code===DOMException.QUOTA_EXCEEDED_ERR||I.name=="QuotaExceededError"||"quota"in I;if(D&&!this._quotaEvictionPending[n]){let C=this.getBackBufferEvictionTarget(n,s.byteLength,o.type);if(C>0){this._quotaEvictionPending[n]=!0,this.log(`QuotaExceededError on "${n}" append sn: ${m} - evicting back buffer to ${C.toFixed(3)}s and retrying`);let M=this.getFlushOp(n,0,C),w=this.getClearEvictionPendingOp(n);this.insertNext([M,P,w],n);return}this.warn(`QuotaExceededError on "${n}" sn: ${m} - no back buffer available to evict`)}u&&(this.getFragmentAppendProgress(o).errored=!0);let F={type:W.MEDIA_ERROR,parent:a,details:L.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:I,err:I,fatal:!1},G=(k=this.media)==null?void 0:k.error;if(I.name===ed&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))F.errorAction=ti(!0);else{var $;D&&(F.details=L.BUFFER_FULL_ERROR);let C=++this.appendErrors[n],M=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${C}/${M+1} times to append segment in "${n}" sourceBuffer with error: ${I.message}`),C>=M&&(F.fatal=!D);let w=($=this.mediaSource)==null?void 0:$.readyState;(w==="ended"||w==="closed"||G)&&(this.warn(`MediaSource readyState "${w}" during SourceBuffer${go(F.fatal,G)}`),F.details=L.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=F,this.hls.trigger(y.ERROR,F),D&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${n}" append sn: ${m}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${p} offset: ${c} bytes: ${s.byteLength}`),this.append(P,n,this.isPending(this.tracks[n]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{var s;let n=(s=this.tracks[e])==null?void 0:s.buffer;this.log(`Remove request ${t}-${i} from ${e} Source Buffer complete > buffer: ${n?ls(J.getBuffered(n)):"(detached)"}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:t,end:i})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:0,end:0,error:s})}}}onBufferFlushing(e,t){let{type:i,startOffset:s,endOffset:n}=t;(!i||i==="audio")&&this.unblockAudio(),i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,n),a)})}onFragParsed(e,t){let{frag:i,part:s,chunkMeta:n}=t,a=[],o=s?s.elementaryStreams:i.elementaryStreams;o[he.AUDIOVIDEO]?a.push("audiovideo"):(o[he.AUDIO]&&a.push("audio"),o[he.VIDEO]&&a.push("video"));let l=()=>{let d=self.performance.now();i.stats.buffering.end=d,s&&(s.stats.buffering.end=d);let c=s?s.stats:i.stats;this.checkAppendProgress(i,s,n,a),this.hls&&(this.hls.trigger(y.FRAG_BUFFERED,{frag:i,part:s,stats:c,id:i.type,chunkMeta:n}),!s&&i.gap&&c.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${c.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${s?`part: ${s.index} of `:""}sn: ${i.sn}`),this.blockBuffers(l,a).catch(d=>{this.warn(`Fragment buffered callback ${d.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var i,s;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let{backBufferLength:a,frontBufferFlushThreshold:o}=n;this.trimBuffers(o,a,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:d}=this,c=(s=this.appendError)==null?void 0:s.sourceBufferName;Object.keys(l).forEach(h=>{l[h]&&(d[h]=0,h===c&&(this.appendError=void 0),h==="audio"||h==="video"?(d.audiovideo=0,c==="audiovideo"&&(this.appendError=void 0)):(d.audio=0,d.video=0,c!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});let s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?(this.unblockAudio(),s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(a?.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(y.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0))):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===L.BUFFER_APPEND_ERROR&&t.frag){var i;let s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;B(s)&&s!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,i){let{media:s}=this;return s?this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,i,t):0}getFragmentAppendProgress(e){var t;let i=mo(e),s=this.fragmentAppendProgress[i];return((t=s)==null?void 0:t.stats)!==e.stats&&(s={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=s),s}checkAppendProgress(e,t,i,s){if(t||!ve(e)||e.gap||i.iframe||i.partial)return;let n=mo(e),a=this.fragmentAppendProgress[n];delete this.fragmentAppendProgress[n];let o=e.stats.buffering;if(o.start&&!o.first)return;let l=a?.stats===e.stats?a:void 0;if(l!=null&&l.errored)return;let d=s.length>0&&s.every(f=>l?.fullyBuffered[f]===!0);if(l!=null&&l.progressed||d){delete this.appendsWithoutProgress[n];return}if(!l&&s.length===0)return;let c=(this.appendsWithoutProgress[n]||0)+1,h=this.hls;c>=h.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=c,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${c} time${c>1?"s":""} without buffered range growth`),h.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:i,parent:e.type,appendsWithoutProgress:c,error:new Error(`Fragment append did not increase buffered coverage (${c})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,i,s){let{hls:n,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;let l=n.config,d=o.currentTime,c=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let h=-1/0;if(B(t)&&t>=0){let u=Math.max(t,c);h=Math.floor(d/c)*c-u}if(i){let u=this.getLoopBackBufferFlushEnd(i,s??null);u>0&&(h=Math.max(h,u))}if(h>0&&this.flushBackBuffer(d,c,h),B(e)&&e>0){let u=Math.max(l.maxBufferLength,e),f=Math.max(u,c),g=Math.floor(d/c)*c+f;this.flushFrontBuffer(d,c,g)}}getLoopBackBufferFlushEnd(e,t){var i;let{media:s}=this;if(((i=this.hls)==null?void 0:i.config.loopBackBufferFlush)===!1||!(s!=null&&s.loop)||!t||e.level<=t.level)return 0;let{video:n,audiovideo:a}=e.elementaryStreams;if(n!=null&&n.partial||a!=null&&a.partial)return 0;let o=this.getEarliestElementaryStreamStart(e)-Du;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(e){let{audio:t,video:i,audiovideo:s}=e.elementaryStreams,n=e.start;return s?n=Math.min(n,s.startDTS):(t&&(n=Math.min(n,t.startDTS)),i&&(n=Math.min(n,i.startDTS))),n}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){let d=J.getBuffered(n);if(d.length>0&&i>d.start(0)){var a,o,l;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:i});let c=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(c!=null&&c.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){let a=J.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),d=a.end(o-1);if(i>l||e>=l&&e<=d)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;let s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),c=Math.max(d,s);return{duration:1/0,start:d,end:c}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return B(n)?{duration:n}:null;let a=this.media.duration,o=B(i.duration)?i.duration:0;return s>o&&s>a||!B(a)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){let s=this.mediaSource;!s||!this.media||s.readyState!=="open"||(s.duration!==e&&(B(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${fe(i)}`),this.tracksReady){var s;let n=(s=this.transferData)==null?void 0:s.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(y.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${fe(o)}`);try{let c=i.addSourceBuffer(d),h=en(a),u=[a,c];t[h]=u,o.buffer=c}catch(c){var s;this.error(`error while trying to add sourceBuffer: ${c.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:a,mimeType:d,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){let i=e.supplemental,s=e.codec;i&&(t==="video"||t==="audiovideo")&&ci(i,"video")&&(s=jc(s,i));let n=Hi(s,e.levelCodec);return n?t.slice(0,5)==="audio"?Qi(n,this.appendSource):n:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&(this.log(`${n} buffer removed ${ls(o)}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:n,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,i;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let s=this.currentOp(e);if(!s)return;if(s.onComplete(),(i=this.tracks[e])==null||(i=i.buffer)==null?void 0:i.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var i;let s=(i=this.mediaSource)==null?void 0:i.readyState,n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${s}`);this.error(`${n.message}`,t),this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});let a=this.currentOp(e);a&&a.onError(n)}updateTimestampOffset(e,t,i,s,n,a){let o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:s,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!s||!n||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let l=B(s.duration)?s.duration:1/0,d=B(n.duration)?n.duration:1/0,c=Math.max(0,t);if(c>=d){var h;(h=this.currentOp(e))==null||h.onComplete(),this.shiftAndExecuteNext(e);return}let u=Math.min(i,l,d);if(u>c&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${c},${u}] from the ${e} SourceBuffer`),o.remove(c,u);else throw new Error(`Cannot remove ${u<=c?`invalid range (${c} >= ${u}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){let i=this.tracks[t],s=i?.buffer;if(!s)throw new jn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){let n=this.calculateAppendTimeoutTime(s);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,s,n),n)}s.appendBuffer(e)}appendTimeoutHandler(e,t,i){this.log(`Received timeout after ${i}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}let s=this.currentOp(e);s&&s.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=Il;this.details&&(t=this.details.levelTargetDuration);let i=2*t*1e3;if(this.media===null)return i;let s=J.bufferInfo(e,this.media.currentTime,0);return s.len?(i=Math.max(s.len*1e3,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,n=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(n).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;let s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let s=this.tracks[e];if(!s)return;let n=s.buffer;if(!n)return;let a=i.bind(this,e);s.listeners.push({event:t,listener:a}),de(n,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(s=>{le(i,s.event,s.listener)}),t.listeners.length=0)}};function fo(r){let e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function wu(r,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function en(r){return r==="audio"?1:0}function go(r,e){return`${r?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function mo(r){return`${r.type}_${r.sn}_${r.level}`}function tn(r,e){let{start:t,end:i}=e,s=0;for(let n=0;n<r.length;n++){let a=r[n];if(a.start>=i)break;let o=Math.max(t,a.start),l=Math.min(i,a.end);l>o&&(s+=l-o)}return s}function po(r,e){return e.duration-r<=.05}var Xn=class r{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){let{hls:e}=this;e&&(e.on(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){let{hls:e}=this;e&&(e.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){let i=t.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping()}onLevelsUpdated(e,{levels:t}){(this.timer||this.observer)&&B(this.autoLevelCapping)?this.detectPlayerSize():this.observer===void 0&&this.timer===void 0&&t.length>1&&t.some(i=>!!i.videoCodec)&&this.startCapping()}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}let e=this.hls.levels;if(e.length>1){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.observer||(this.clientRect=null),r.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(t=>{var i;let s=(i=t[0])==null?void 0:i.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:i}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,i)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;let s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&s(l,e[o+1])){n=o;break}}return n}},Be=class Qn{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Qn?i:new Qn(i))),this.value=e,this.params=t}},Mu="Dict";function Ou(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function Fu(r,e,t,i){return new Error(`failed to ${r} "${Ou(e)}" as ${t}`,{cause:i})}var yo="Bare Item",Nu="Boolean",Bu="Byte Sequence",$u="Decimal",Uu="Integer";function Gu(r){return r<-999999999999999||999999999999999<r}var Vu="String",Hu=/[\x00-\x1f\x7f]+/,td=class{constructor(r){this.description=r}},Ku="Token",qu="Key";function lt(r,e,t){return Fu("serialize",r,e,t)}function Wu(r){if(typeof r!="boolean")throw lt(r,Nu);return r?"?1":"?0"}function Yu(r){if(ArrayBuffer.isView(r)===!1)throw lt(r,Bu);return`:${nc(r)}:`}function id(r){if(Gu(r))throw lt(r,Uu);return r.toString()}function ju(r){return`@${id(r.getTime()/1e3)}`}function zu(r){let e=jo(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw lt(r,$u);let t=e.toString();return t.includes(".")?t:`${t}.0`}function Xu(r){if(Hu.test(r))throw lt(r,Vu);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Qu(r){return r.description||r.toString().slice(7,-1)}function vo(r){let e=Qu(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw lt(e,Ku);return e}function Zn(r){switch(typeof r){case"number":if(!B(r))throw lt(r,yo);return Number.isInteger(r)?id(r):zu(r);case"string":return Xu(r);case"symbol":return vo(r);case"boolean":return Wu(r);case"object":if(r instanceof Date)return ju(r);if(r instanceof Uint8Array)return Yu(r);if(r instanceof td)return vo(r);default:throw lt(r,yo)}}function Jn(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw lt(r,qu);return r}function Qr(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${Jn(e)}`:`;${Jn(e)}=${Zn(t)}`).join("")}function sd(r){return r instanceof Be?`${Zn(r.value)}${Qr(r.params)}`:Zn(r)}function Zu(r){return`(${r.value.map(sd).join(" ")})${Qr(r.params)}`}function Ju(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw lt(r,Mu);let t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof Be||(n=new Be(n));let a=Jn(s);return n.value===!0?a+=Qr(n.params):(a+="=",Array.isArray(n.value)?a+=Zu(n):a+=sd(n)),a}).join(`,${i}`)}function nd(r,e){return Ju(r,e)}var ef=["url"],tf=["version","eventTargets","sid","transmissionMode"],sf=["customData","headers"],Eo=r=>r instanceof Be?new Be(Math.round(r.value),r.params):Math.round(r),sn=r=>Array.isArray(r)?r.map(Eo):Eo(r),er=(r,e)=>Array.isArray(r)?r.map(t=>er(t,e)):r instanceof Be&&typeof r.value=="string"?new Be(er(r.value,e),r.params):(e.baseUrl&&(r=lc(r,oc(e.baseUrl))),e.version===1?encodeURIComponent(r):r),To=r=>r instanceof Be?new Be(Math.round(r.value/100)*100,r.params):Math.round(r/100)*100,Fi=r=>Array.isArray(r)?r.map(To):To(r),nf=(r,e)=>{let t=r;return e.version>=2&&(r instanceof Be&&typeof r.value=="string"?t=new Be([r]):typeof r=="string"&&(t=[r])),er(t,e)},rf={br:sn,d:sn,bl:Fi,dl:Fi,mtp:Fi,nor:nf,rtp:Fi,tb:sn},Si=2,rd="bc",af="ps",ad="pr",of="e",So="t",lf="c",od="b",Zr="rr",ld="ce",Ni={BITRATE_CHANGE:rd,ERROR:of,RESPONSE_RECEIVED:Zr,CUSTOM_EVENT:ld},dd=new Map([[af,"sta"],[ad,"pr"],[lf,"cid"],[od,"bg"],[rd,"br"]]),Jr="event",ea="request",cd=["cen","e","h","ts"],hd=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],df=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ta(r){return df.test(r)}var cf=new Set(hd);function ud(r){return cf.has(r)||ta(r)}var fd=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],hf=new Set(fd);function gd(r){return hf.has(r)}var uf=new Set(cd);function ff(r){return ud(r)||gd(r)||uf.has(r)}var gf=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Ds=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],mf=new Set(Ds);function pf(r){return mf.has(r)||ta(r)}var yf=new Set(["ot","sf","st","e","sta"]);function vf(r){return yf.has(r)}function Ef(r){return typeof r=="number"?B(r):r!=null&&r!==""&&r!==!1}var Tf={[Jr]:ff,[ea]:ud};function md(r,e){if(Array.isArray(r)){let t;return e&&(t=r.find(i=>{var s;return((s=i.params)==null?void 0:s.ot)===e})),t||(t=r[0]),md(t)}return r instanceof Be?r.value:r}function Sf(r){let e={};for(let[i,s]of Object.entries(r)){if(s==null){e[i]=s;continue}if(i==="nor"){let n=(Array.isArray(s)?s:[s])[0];if(n instanceof Be){var t;e.nor=n.value,(t=n.params)!=null&&t.r&&(e.nrr=n.params.r)}else e.nor=n}else gf.has(i)?e[i]=md(s,r.ot):e[i]=s}return e}function pd(r,e={}){let t={};if(r==null||typeof r!="object")return t;let i=e.version||r.v||Si,s=e.reportingMode||ea,n=i===1?Sf(r):r,a=i===1?pf:Tf[s],o=Object.keys(n).filter(a);n.e&&n.e!==Zr&&(o=o.filter(f=>!gd(f)));let l=e.filter;typeof l=="function"&&(o=o.filter(l));let d=s===Jr;if(d){let f=n.e;!o.includes("e")&&f!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&n.cen!=null&&f===ld&&o.push("cen");let g=f?dd.get(f):void 0;g&&n[g]!=null&&!o.includes(g)&&o.push(g)}if(o.length===0)return t;i>1&&!o.includes("v")&&o.push("v");let c={version:i,reportingMode:s,baseUrl:e.baseUrl};o.sort();for(let f of o){var h,u;let g=n[f],m=(h=(u=e.formatters)==null?void 0:u[f])!=null?h:rf[f];if(typeof m=="function"&&(g=m(g,c)),f==="v"){if(i===1)continue;g=i}if(f==="pr"&&g===1&&!(d&&n.e===ad))continue;d&&f==="ts"&&!B(g)&&(g=Date.now());let p=d&&g===!1&&f==="bg"&&n.e===od;!Ef(g)&&!p||(vf(f)&&typeof g=="string"&&(g=new td(g)),t[f]=g)}return t}var ut="CMCD-Object",Ne="CMCD-Request",Bt="CMCD-Session",Xe="CMCD-Status",bf={REQUEST:Ne},Af={ab:ut,br:ut,d:ut,lab:ut,lb:ut,ot:ut,tab:ut,tb:ut,tpb:ut,bl:Ne,cs:Ne,dfa:Ne,dl:Ne,ltc:Ne,mtp:Ne,nor:Ne,nrr:Ne,pb:Ne,sn:Ne,sta:Ne,su:Ne,tbl:Ne,cid:Bt,msd:Bt,sf:Bt,sid:Bt,st:Bt,v:Bt,bg:Xe,bs:Xe,bsa:Xe,bsd:Xe,bsda:Xe,cdn:Xe,ec:Xe,nr:Xe,pr:Xe,pt:Xe,rtp:Xe};function xf(r){return Object.keys(r).reduce((e,t)=>{var i;return(i=r[t])==null||i.forEach(s=>e[s]=t),e},{})}function If(r,e){let t={};if(!r)return t;let i=Object.keys(r),s=e?xf(e):{};for(let a of i){var n;let o=Af[a]||s[a]||bf.REQUEST,l=(n=t[o])!=null?n:t[o]={};l[a]=r[a]}return t}function Lf(r,e){let t={},i=If(r,e);for(let[s,n]of Object.entries(i)){let a=nd(n,{whitespace:!1});a&&(t[s]=a)}return t}var bo="CMCD";function yd(r){return nd(r,{whitespace:!1})}function Rf(r,e={}){return r?yd(pd(r,e)):""}var Pf=30,tr=[...Ds,...hd,...fd,...cd].filter((r,e,t)=>t.indexOf(r)===e),_f="application/cmcd",kf=1,_e={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Qe={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},ia="query",vd="headers";function Ao(r,e,t){var i;let s=new Set((i=e.enabledKeys)!=null?i:[]);return{version:e.version||Si,reportingMode:r,filter:n=>s.has(n),baseUrl:t}}function Df(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let i=r[t],s=e[t];if(i===s)continue;if(typeof i=="number"||typeof s=="number"||i.value!==s.value)return!1;let n=i.params,a=s.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&n&&a&&n[o]!==a[l])return!1}return!0}var Cf=Object.is,wf=r=>r,Ed=Array.from(dd,([r,e])=>e==="br"?{event:r,field:e,equal:(t,i)=>t===void 0||i===void 0?t===i:Df(t,i),snapshot:t=>t.slice()}:{event:r,field:e,equal:Cf,snapshot:wf}),Mf=new Map(Ed.map(r=>[r.event,r]));function Of(r){let{url:e}=r,t=Ps(r,ef);return fetch(e,t)}function Ff(r){let{version:e=Si,eventTargets:t=[],sid:i=zo(),transmissionMode:s=ia}=r,n=Ps(r,tf);return Y(Y({},n),{},{version:e,transmissionMode:s,sid:i,eventTargets:t.reduce((a,o)=>{var l,d,c;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||Si,enabledKeys:((d=o.enabledKeys)==null?void 0:d.slice())||[],url:o.url,events:o.events.slice(),interval:(c=o.interval)!=null?c:Pf,batchSize:o.batchSize||1}),a},[])})}var Nf=class{constructor(r,e=Of){var t;this.timeOrigin=performance.timeOrigin||((t=performance.timing)==null?void 0:t.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=Ff(r),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(let i of this.config.eventTargets)this.eventTargets.set(i,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((r,e)=>{if(this.disarmInterval(r),e.interval===0||!e.events.includes(So))return;let t=()=>{this.recordTargetEvent(r,e,So),this.processEventTargets()};r.intervalId=setInterval(t,e.interval*1e3),t()})}stop(r=!1){r&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(r){r.sid&&r.sid!==this.data.sid&&this.resetSession(),r.msd&&!isNaN(r.msd)&&(this.msd=r.msd),this.data=Y(Y(Y({},this.data),r),{},{msd:void 0});for(let e of Ed)e.field in r&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(r,e={}){let t=Mf.get(r);if(t){let i=t.field,s=e[i];s!==void 0&&ce(this.data,{[i]:s});let n=this.data[i];if(n===void 0||t.equal(n,this.lastEmitted[i]))return;ce(this.lastEmitted,{[i]:t.snapshot(n)})}this.eventTargets.forEach((i,s)=>{this.recordTargetEvent(i,s,r,e)}),this.processEventTargets()}recordTargetEvent(r,e,t,i={}){var s;if(!e.events.includes(t))return;let n=Y(Y(Y({},this.data),i),{},{e:t,ts:(s=i.ts)!=null?s:Date.now(),sn:r.sn++});!isNaN(this.msd)&&!r.msdSent&&(n.msd=this.msd,r.msdSent=!0),r.queue.push(n)}recordResponseReceived(r,e={}){var t,i,s;let{request:n}=r,a=(t=e.url)!=null?t:n?.url;if(!a)return;let o=new URL(a);o.searchParams.delete(bo);let l={url:o.toString(),rc:r.status},d=r.resourceTiming;d&&(d.startTime!=null&&(l.ts=Math.round(this.timeOrigin+d.startTime),d.responseStart!=null&&(l.ttfb=Math.round(d.responseStart-d.startTime))),d.duration!=null&&(l.ttlb=Math.round(d.duration)));let c=(i=(s=n.customData)==null?void 0:s.cmcd)!=null?i:{};this.recordEvent(Zr,Y(Y(Y({},c),l),e))}applyRequestReport(r){var e;return(e=this.createRequestReport(r))!=null?e:r}isRequestReportingEnabled(){var r;return!!((r=this.config.enabledKeys)!=null&&r.length)}createRequestReport(r,e){var t;let{customData:i={},headers:s={}}=r,n=Ps(r,sf),a=Y(Y({},n),{},{headers:Y({},s),customData:Y(Y({},i),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;let o=new URL(a.url),l=Y(Y(Y({},this.data),e),{},{sn:this.requestTarget.sn++}),d=Ao(ea,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);let c=a.customData.cmcd=pd(l,d);switch(this.config.transmissionMode){case ia:let h=yd(c);h&&(o.searchParams.set(bo,h),a.url=o.toString());break;case vd:ce(a.headers,Lf(c,d.customHeaderMap));break}return a}processEventTargets(r=!1){let e=!1;this.eventTargets.forEach((t,i)=>{let{queue:s}=t;if(!s.length||s.length<i.batchSize&&!r)return;let n=r?s.length:i.batchSize,a=s.splice(0,n);this.sendEventReport(i,a).catch(()=>{t.queue.unshift(...a)}),e||(e=s.length>0)}),e&&this.processEventTargets()}async sendEventReport(r,e){let t=Ao(Jr,r),{status:i}=await this.requester({url:r.url,method:"POST",headers:{"Content-Type":_f},body:e.map(s=>Rf(s,t)).join(`
27
+ transfer tracks: ${fe(s,(l,d)=>l==="initSegment"?void 0:d)}}`),!Xo(s,i)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,c=Math.max(l,d?.fragments[0].start||0);if(c-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${c} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,t),e.currentTime=c;return}this.transferData=void 0,n.forEach(l=>{let d=l,c=s[d];if(c){let h=c.buffer;if(h){let u=this.fragmentTracker,f=c.id;if(u.hasFragments(f)||u.hasParts(f)){let p=J.getBuffered(h);u.detectEvictedFragments(d,p,f,null,null,!0)}let g=sn(d),m=[d,h];this.sourceBuffers[g]=m,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,c)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:s,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let l=n.sourceBuffers;for(let d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}le(n,"sourceopen",this._onMediaSourceOpen),le(n,"sourceended",this._onMediaSourceEnded),le(n,"sourceclose",this._onMediaSourceClose),this.appendSource&&(le(n,"startstreaming",this._onStartStreaming),le(n,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(le(s,"emptied",this._onMediaEmptied),le(s,"error",this._onMediaError),le(s,"seeking",this._onStartStreaming),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&po(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[sn(e)]=[null,null];let t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new zn(this.tracks)}onBufferCodecs(e,t){var i;let s=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!s[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,c;let h=t[l],{id:u,codec:f,levelCodec:g,container:m,metadata:p,supplemental:v}=h,T=s[l],E=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],S=E!=null&&E.buffer?E:T,b=S?.pendingCodec||S?.codec,A=S?.levelCodec;T||(T=s[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:m,levelCodec:g,metadata:p,id:u});let x=Hi(b,A),R=x?.replace(mo,"$1"),P=Hi(f,g),I=(c=P)==null?void 0:c.replace(mo,"$1");P&&x&&R!==I&&(l.slice(0,5)==="audio"&&(P=Qi(P,this.appendSource)),this.log(`switching codec ${b} to ${P}`),P!==(T.pendingCodec||T.codec)&&(T.pendingCodec=P),T.container=m,this.appendChangeType(l,m,P))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let s=`${t};codecs=${i}`,n={label:`change-type=${s}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),a.codec=i,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,s=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,H.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>s||J.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,s)||((l=this.fragmentTracker.getAppendedFrag(s,H.MAIN))==null?void 0:l.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(a,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:i}=this,{data:s,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:c}=t,h=d.buffering[n],u=ve(o)&&!l&&!o.gap&&!d.partial&&!d.iframe,f=null,g=!1,{sn:m,cc:p}=o,v=self.performance.now();h.start=v;let T=o.stats.buffering,E=l?l.stats.buffering:null;T.start===0&&(T.start=v),E?.start===0&&(E.start=v);let S=i.audio,b=!1;n==="audio"&&S?.container==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let A=i.video,x=A?.buffer;if(x&&m!=="initSegment"&&c!==void 0){let I=S?.buffer,k=l||o;if(n==="audio"&&a!=="main"&&!(A.ending||A.ended)&&I&&J.getBuffered(I).length){let F=k.start+k.duration*.05,G=J.getBuffered(x),$=this.currentOp("video");!G.length&&!$?this.blockAudio(k):!J.isBuffered(x,F)&&this.lastVideoAppendEnd<F&&this.blockAudio(k)}else if(n==="video"){let D=k.end,F=this.lastVideoAppendEnd-D;this.lastVideoAppendEnd=D,F<0||F>k.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}let R=(l||o).start,P={label:`append-${n}`,execute:()=>{var I;h.executeStart=self.performance.now();let k=(I=this.tracks[n])==null?void 0:I.buffer;k&&(u&&(f=J.timeRangesToArray(J.getBuffered(k)),g=Eo(nn(f,o),o)),b?this.updateTimestampOffset(k,R,.1,n,m,p):c!==void 0&&B(c)&&this.updateTimestampOffset(k,c,1e-6,n,m,p)),this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[n]);let I=self.performance.now();h.executeEnd=h.end=I,T.first===0&&(T.first=I),E?.first===0&&(E.first=I);let k={};if(this.sourceBuffers.forEach(([D,F])=>{D&&(k[D]=J.getBuffered(F))}),u){let D=this.getFragmentAppendProgress(o),F=k[n];if(F&&f){let G=J.timeRangesToArray(F),$=nn(G,o);D.progressed||(D.progressed=$-nn(f,o)>Ou);let C=g&&Eo($,o);D.fullyBuffered[n]=(D.fullyBuffered[n]===void 0||D.fullyBuffered[n])&&C}}this.hls.trigger(y.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:a,timeRanges:k})},onError:I=>{var k;this.clearBufferAppendTimeoutId(this.tracks[n]);let D=I.code===DOMException.QUOTA_EXCEEDED_ERR||I.name=="QuotaExceededError"||"quota"in I;if(D&&!this._quotaEvictionPending[n]){let C=this.getBackBufferEvictionTarget(n,s.byteLength,o.type);if(C>0){this._quotaEvictionPending[n]=!0,this.log(`QuotaExceededError on "${n}" append sn: ${m} - evicting back buffer to ${C.toFixed(3)}s and retrying`);let M=this.getFlushOp(n,0,C),w=this.getClearEvictionPendingOp(n);this.insertNext([M,P,w],n);return}this.warn(`QuotaExceededError on "${n}" sn: ${m} - no back buffer available to evict`)}u&&(this.getFragmentAppendProgress(o).errored=!0);let F={type:W.MEDIA_ERROR,parent:a,details:L.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:I,err:I,fatal:!1},G=(k=this.media)==null?void 0:k.error;if(I.name===sd&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))F.errorAction=ti(!0);else{var $;D&&(F.details=L.BUFFER_FULL_ERROR);let C=++this.appendErrors[n],M=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${C}/${M+1} times to append segment in "${n}" sourceBuffer with error: ${I.message}`),C>=M&&(F.fatal=!D);let w=($=this.mediaSource)==null?void 0:$.readyState;(w==="ended"||w==="closed"||G)&&(this.warn(`MediaSource readyState "${w}" during SourceBuffer${yo(F.fatal,G)}`),F.details=L.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=F,this.hls.trigger(y.ERROR,F),D&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${n}" append sn: ${m}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${p} offset: ${c} bytes: ${s.byteLength}`),this.append(P,n,this.isPending(this.tracks[n]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{var s;let n=(s=this.tracks[e])==null?void 0:s.buffer;this.log(`Remove request ${t}-${i} from ${e} Source Buffer complete > buffer: ${n?ls(J.getBuffered(n)):"(detached)"}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:t,end:i})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s),this.hls.trigger(y.BUFFER_FLUSHED,{type:e,start:0,end:0,error:s})}}}onBufferFlushing(e,t){let{type:i,startOffset:s,endOffset:n}=t;(!i||i==="audio")&&this.unblockAudio(),i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,n),a)})}onFragParsed(e,t){let{frag:i,part:s,chunkMeta:n}=t,a=[],o=s?s.elementaryStreams:i.elementaryStreams;o[he.AUDIOVIDEO]?a.push("audiovideo"):(o[he.AUDIO]&&a.push("audio"),o[he.VIDEO]&&a.push("video"));let l=()=>{let d=self.performance.now();i.stats.buffering.end=d,s&&(s.stats.buffering.end=d);let c=s?s.stats:i.stats;this.checkAppendProgress(i,s,n,a),this.hls&&(this.hls.trigger(y.FRAG_BUFFERED,{frag:i,part:s,stats:c,id:i.type,chunkMeta:n}),!s&&i.gap&&c.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${c.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${s?`part: ${s.index} of `:""}sn: ${i.sn}`),this.blockBuffers(l,a).catch(d=>{this.warn(`Fragment buffered callback ${d.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var i,s;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let{backBufferLength:a,frontBufferFlushThreshold:o}=n;this.trimBuffers(o,a,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:d}=this,c=(s=this.appendError)==null?void 0:s.sourceBufferName;Object.keys(l).forEach(h=>{l[h]&&(d[h]=0,h===c&&(this.appendError=void 0),h==="audio"||h==="video"?(d.audiovideo=0,c==="audiovideo"&&(this.appendError=void 0)):(d.audio=0,d.video=0,c!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});let s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?(this.unblockAudio(),s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(a?.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(y.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0))):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===L.BUFFER_APPEND_ERROR&&t.frag){var i;let s=(i=t.errorAction)==null?void 0:i.nextAutoLevel;B(s)&&s!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,i){let{media:s}=this;return s?this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,i,t):0}getFragmentAppendProgress(e){var t;let i=vo(e),s=this.fragmentAppendProgress[i];return((t=s)==null?void 0:t.stats)!==e.stats&&(s={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=s),s}checkAppendProgress(e,t,i,s){if(t||!ve(e)||e.gap||i.iframe||i.partial)return;let n=vo(e),a=this.fragmentAppendProgress[n];delete this.fragmentAppendProgress[n];let o=e.stats.buffering;if(o.start&&!o.first)return;let l=a?.stats===e.stats?a:void 0;if(l!=null&&l.errored)return;let d=s.length>0&&s.every(f=>l?.fullyBuffered[f]===!0);if(l!=null&&l.progressed||d){delete this.appendsWithoutProgress[n];return}if(!l&&s.length===0)return;let c=(this.appendsWithoutProgress[n]||0)+1,h=this.hls;c>=h.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=c,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${c} time${c>1?"s":""} without buffered range growth`),h.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:i,parent:e.type,appendsWithoutProgress:c,error:new Error(`Fragment append did not increase buffered coverage (${c})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,i,s){let{hls:n,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;let l=n.config,d=o.currentTime,c=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let h=-1/0;if(B(t)&&t>=0){let u=Math.max(t,c);h=Math.floor(d/c)*c-u}if(i){let u=this.getLoopBackBufferFlushEnd(i,s??null);u>0&&(h=Math.max(h,u))}if(h>0&&this.flushBackBuffer(d,c,h),B(e)&&e>0){let u=Math.max(l.maxBufferLength,e),f=Math.max(u,c),g=Math.floor(d/c)*c+f;this.flushFrontBuffer(d,c,g)}}getLoopBackBufferFlushEnd(e,t){var i;let{media:s}=this;if(((i=this.hls)==null?void 0:i.config.loopBackBufferFlush)===!1||!(s!=null&&s.loop)||!t||e.level<=t.level)return 0;let{video:n,audiovideo:a}=e.elementaryStreams;if(n!=null&&n.partial||a!=null&&a.partial)return 0;let o=this.getEarliestElementaryStreamStart(e)-Mu;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(e){let{audio:t,video:i,audiovideo:s}=e.elementaryStreams,n=e.start;return s?n=Math.min(n,s.startDTS):(t&&(n=Math.min(n,t.startDTS)),i&&(n=Math.min(n,i.startDTS))),n}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){let d=J.getBuffered(n);if(d.length>0&&i>d.start(0)){var a,o,l;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:i});let c=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(c!=null&&c.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([s,n])=>{if(n){let a=J.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),d=a.end(o-1);if(i>l||e>=l&&e<=d)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;let s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),c=Math.max(d,s);return{duration:1/0,start:d,end:c}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return B(n)?{duration:n}:null;let a=this.media.duration,o=B(i.duration)?i.duration:0;return s>o&&s>a||!B(a)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){let s=this.mediaSource;!s||!this.media||s.readyState!=="open"||(s.duration!==e&&(B(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${fe(i)}`),this.tracksReady){var s;let n=(s=this.transferData)==null?void 0:s.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(y.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${fe(o)}`);try{let c=i.addSourceBuffer(d),h=sn(a),u=[a,c];t[h]=u,o.buffer=c}catch(c){var s;this.error(`error while trying to add sourceBuffer: ${c.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:a,mimeType:d,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){let i=e.supplemental,s=e.codec;i&&(t==="video"||t==="audiovideo")&&ci(i,"video")&&(s=Qc(s,i));let n=Hi(s,e.levelCodec);return n?t.slice(0,5)==="audio"?Qi(n,this.appendSource):n:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&(this.log(`${n} buffer removed ${ls(o)}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:n,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,i;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let s=this.currentOp(e);if(!s)return;if(s.onComplete(),(i=this.tracks[e])==null||(i=i.buffer)==null?void 0:i.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var i;let s=(i=this.mediaSource)==null?void 0:i.readyState,n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${s}`);this.error(`${n.message}`,t),this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});let a=this.currentOp(e);a&&a.onError(n)}updateTimestampOffset(e,t,i,s,n,a){let o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:s,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!s||!n||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let l=B(s.duration)?s.duration:1/0,d=B(n.duration)?n.duration:1/0,c=Math.max(0,t);if(c>=d){var h;(h=this.currentOp(e))==null||h.onComplete(),this.shiftAndExecuteNext(e);return}let u=Math.min(i,l,d);if(u>c&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${c},${u}] from the ${e} SourceBuffer`),o.remove(c,u);else throw new Error(`Cannot remove ${u<=c?`invalid range (${c} >= ${u}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){let i=this.tracks[t],s=i?.buffer;if(!s)throw new Xn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){let n=this.calculateAppendTimeoutTime(s);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,s,n),n)}s.appendBuffer(e)}appendTimeoutHandler(e,t,i){this.log(`Received timeout after ${i}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}let s=this.currentOp(e);s&&s.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=Pl;this.details&&(t=this.details.levelTargetDuration);let i=2*t*1e3;if(this.media===null)return i;let s=J.bufferInfo(e,this.media.currentTime,0);return s.len?(i=Math.max(s.len*1e3,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,n=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(n).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var i;let s=(i=this.tracks[t])==null?void 0:i.buffer;!s||s.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let s=this.tracks[e];if(!s)return;let n=s.buffer;if(!n)return;let a=i.bind(this,e);s.listeners.push({event:t,listener:a}),de(n,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(s=>{le(i,s.event,s.listener)}),t.listeners.length=0)}};function po(r){let e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function Fu(r,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function sn(r){return r==="audio"?1:0}function yo(r,e){return`${r?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function vo(r){return`${r.type}_${r.sn}_${r.level}`}function nn(r,e){let{start:t,end:i}=e,s=0;for(let n=0;n<r.length;n++){let a=r[n];if(a.start>=i)break;let o=Math.max(t,a.start),l=Math.min(i,a.end);l>o&&(s+=l-o)}return s}function Eo(r,e){return e.duration-r<=.05}var Zn=class r{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){let{hls:e}=this;e&&(e.on(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){let{hls:e}=this;e&&(e.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){let i=t.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping()}onLevelsUpdated(e,{levels:t}){(this.timer||this.observer)&&B(this.autoLevelCapping)?this.detectPlayerSize():this.observer===void 0&&this.timer===void 0&&t.length>1&&t.some(i=>!!i.videoCodec)&&this.startCapping()}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}let e=this.hls.levels;if(e.length>1){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;let t=this.hls.levels;if(!t.length)return-1;let i=t.filter((s,n)=>this.isLevelAllowed(s)&&n<=e);return this.observer||(this.clientRect=null),r.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(t=>{var i;let s=(i=t[0])==null?void 0:i.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:i}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,i)}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;let s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&s(l,e[o+1])){n=o;break}}return n}},Be=class Jn{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof Jn?i:new Jn(i))),this.value=e,this.params=t}},Nu="Dict";function Bu(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function $u(r,e,t,i){return new Error(`failed to ${r} "${Bu(e)}" as ${t}`,{cause:i})}var To="Bare Item",Uu="Boolean",Gu="Byte Sequence",Vu="Decimal",Hu="Integer";function Ku(r){return r<-999999999999999||999999999999999<r}var qu="String",Wu=/[\x00-\x1f\x7f]+/,nd=class{constructor(r){this.description=r}},Yu="Token",ju="Key";function lt(r,e,t){return $u("serialize",r,e,t)}function zu(r){if(typeof r!="boolean")throw lt(r,Uu);return r?"?1":"?0"}function Xu(r){if(ArrayBuffer.isView(r)===!1)throw lt(r,Gu);return`:${oc(r)}:`}function rd(r){if(Ku(r))throw lt(r,Hu);return r.toString()}function Qu(r){return`@${rd(r.getTime()/1e3)}`}function Zu(r){let e=Qo(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw lt(r,Vu);let t=e.toString();return t.includes(".")?t:`${t}.0`}function Ju(r){if(Wu.test(r))throw lt(r,qu);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ef(r){return r.description||r.toString().slice(7,-1)}function So(r){let e=ef(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw lt(e,Yu);return e}function er(r){switch(typeof r){case"number":if(!B(r))throw lt(r,To);return Number.isInteger(r)?rd(r):Zu(r);case"string":return Ju(r);case"symbol":return So(r);case"boolean":return zu(r);case"object":if(r instanceof Date)return Qu(r);if(r instanceof Uint8Array)return Xu(r);if(r instanceof nd)return So(r);default:throw lt(r,To)}}function tr(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw lt(r,ju);return r}function Jr(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${tr(e)}`:`;${tr(e)}=${er(t)}`).join("")}function ad(r){return r instanceof Be?`${er(r.value)}${Jr(r.params)}`:er(r)}function tf(r){return`(${r.value.map(ad).join(" ")})${Jr(r.params)}`}function sf(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw lt(r,Nu);let t=r instanceof Map?r.entries():Object.entries(r),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([s,n])=>{n instanceof Be||(n=new Be(n));let a=tr(s);return n.value===!0?a+=Jr(n.params):(a+="=",Array.isArray(n.value)?a+=tf(n):a+=ad(n)),a}).join(`,${i}`)}function od(r,e){return sf(r,e)}var nf=["url"],rf=["version","eventTargets","sid","transmissionMode"],af=["customData","headers"],bo=r=>r instanceof Be?new Be(Math.round(r.value),r.params):Math.round(r),rn=r=>Array.isArray(r)?r.map(bo):bo(r),ir=(r,e)=>Array.isArray(r)?r.map(t=>ir(t,e)):r instanceof Be&&typeof r.value=="string"?new Be(ir(r.value,e),r.params):(e.baseUrl&&(r=hc(r,cc(e.baseUrl))),e.version===1?encodeURIComponent(r):r),Ao=r=>r instanceof Be?new Be(Math.round(r.value/100)*100,r.params):Math.round(r/100)*100,Fi=r=>Array.isArray(r)?r.map(Ao):Ao(r),of=(r,e)=>{let t=r;return e.version>=2&&(r instanceof Be&&typeof r.value=="string"?t=new Be([r]):typeof r=="string"&&(t=[r])),ir(t,e)},lf={br:rn,d:rn,bl:Fi,dl:Fi,mtp:Fi,nor:of,rtp:Fi,tb:rn},Si=2,ld="bc",df="ps",dd="pr",cf="e",xo="t",hf="c",cd="b",ea="rr",hd="ce",Ni={BITRATE_CHANGE:ld,ERROR:cf,RESPONSE_RECEIVED:ea,CUSTOM_EVENT:hd},ud=new Map([[df,"sta"],[dd,"pr"],[hf,"cid"],[cd,"bg"],[ld,"br"]]),ta="event",ia="request",fd=["cen","e","h","ts"],gd=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],uf=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function sa(r){return uf.test(r)}var ff=new Set(gd);function md(r){return ff.has(r)||sa(r)}var pd=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],gf=new Set(pd);function yd(r){return gf.has(r)}var mf=new Set(fd);function pf(r){return md(r)||yd(r)||mf.has(r)}var yf=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Ds=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],vf=new Set(Ds);function Ef(r){return vf.has(r)||sa(r)}var Tf=new Set(["ot","sf","st","e","sta"]);function Sf(r){return Tf.has(r)}function bf(r){return typeof r=="number"?B(r):r!=null&&r!==""&&r!==!1}var Af={[ta]:pf,[ia]:md};function vd(r,e){if(Array.isArray(r)){let t;return e&&(t=r.find(i=>{var s;return((s=i.params)==null?void 0:s.ot)===e})),t||(t=r[0]),vd(t)}return r instanceof Be?r.value:r}function xf(r){let e={};for(let[i,s]of Object.entries(r)){if(s==null){e[i]=s;continue}if(i==="nor"){let n=(Array.isArray(s)?s:[s])[0];if(n instanceof Be){var t;e.nor=n.value,(t=n.params)!=null&&t.r&&(e.nrr=n.params.r)}else e.nor=n}else yf.has(i)?e[i]=vd(s,r.ot):e[i]=s}return e}function Ed(r,e={}){let t={};if(r==null||typeof r!="object")return t;let i=e.version||r.v||Si,s=e.reportingMode||ia,n=i===1?xf(r):r,a=i===1?Ef:Af[s],o=Object.keys(n).filter(a);n.e&&n.e!==ea&&(o=o.filter(f=>!yd(f)));let l=e.filter;typeof l=="function"&&(o=o.filter(l));let d=s===ta;if(d){let f=n.e;!o.includes("e")&&f!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&n.cen!=null&&f===hd&&o.push("cen");let g=f?ud.get(f):void 0;g&&n[g]!=null&&!o.includes(g)&&o.push(g)}if(o.length===0)return t;i>1&&!o.includes("v")&&o.push("v");let c={version:i,reportingMode:s,baseUrl:e.baseUrl};o.sort();for(let f of o){var h,u;let g=n[f],m=(h=(u=e.formatters)==null?void 0:u[f])!=null?h:lf[f];if(typeof m=="function"&&(g=m(g,c)),f==="v"){if(i===1)continue;g=i}if(f==="pr"&&g===1&&!(d&&n.e===dd))continue;d&&f==="ts"&&!B(g)&&(g=Date.now());let p=d&&g===!1&&f==="bg"&&n.e===cd;!bf(g)&&!p||(Sf(f)&&typeof g=="string"&&(g=new nd(g)),t[f]=g)}return t}var ut="CMCD-Object",Ne="CMCD-Request",Bt="CMCD-Session",Xe="CMCD-Status",If={REQUEST:Ne},Lf={ab:ut,br:ut,d:ut,lab:ut,lb:ut,ot:ut,tab:ut,tb:ut,tpb:ut,bl:Ne,cs:Ne,dfa:Ne,dl:Ne,ltc:Ne,mtp:Ne,nor:Ne,nrr:Ne,pb:Ne,sn:Ne,sta:Ne,su:Ne,tbl:Ne,cid:Bt,msd:Bt,sf:Bt,sid:Bt,st:Bt,v:Bt,bg:Xe,bs:Xe,bsa:Xe,bsd:Xe,bsda:Xe,cdn:Xe,ec:Xe,nr:Xe,pr:Xe,pt:Xe,rtp:Xe};function Rf(r){return Object.keys(r).reduce((e,t)=>{var i;return(i=r[t])==null||i.forEach(s=>e[s]=t),e},{})}function Pf(r,e){let t={};if(!r)return t;let i=Object.keys(r),s=e?Rf(e):{};for(let a of i){var n;let o=Lf[a]||s[a]||If.REQUEST,l=(n=t[o])!=null?n:t[o]={};l[a]=r[a]}return t}function _f(r,e){let t={},i=Pf(r,e);for(let[s,n]of Object.entries(i)){let a=od(n,{whitespace:!1});a&&(t[s]=a)}return t}var Io="CMCD";function Td(r){return od(r,{whitespace:!1})}function kf(r,e={}){return r?Td(Ed(r,e)):""}var Df=30,sr=[...Ds,...gd,...pd,...fd].filter((r,e,t)=>t.indexOf(r)===e),Cf="application/cmcd",wf=1,_e={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Qe={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},na="query",Sd="headers";function Lo(r,e,t){var i;let s=new Set((i=e.enabledKeys)!=null?i:[]);return{version:e.version||Si,reportingMode:r,filter:n=>s.has(n),baseUrl:t}}function Mf(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let i=r[t],s=e[t];if(i===s)continue;if(typeof i=="number"||typeof s=="number"||i.value!==s.value)return!1;let n=i.params,a=s.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&n&&a&&n[o]!==a[l])return!1}return!0}var Of=Object.is,Ff=r=>r,bd=Array.from(ud,([r,e])=>e==="br"?{event:r,field:e,equal:(t,i)=>t===void 0||i===void 0?t===i:Mf(t,i),snapshot:t=>t.slice()}:{event:r,field:e,equal:Of,snapshot:Ff}),Nf=new Map(bd.map(r=>[r.event,r]));function Bf(r){let{url:e}=r,t=Ps(r,nf);return fetch(e,t)}function $f(r){let{version:e=Si,eventTargets:t=[],sid:i=Zo(),transmissionMode:s=na}=r,n=Ps(r,rf);return Y(Y({},n),{},{version:e,transmissionMode:s,sid:i,eventTargets:t.reduce((a,o)=>{var l,d,c;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||Si,enabledKeys:((d=o.enabledKeys)==null?void 0:d.slice())||[],url:o.url,events:o.events.slice(),interval:(c=o.interval)!=null?c:Df,batchSize:o.batchSize||1}),a},[])})}var Uf=class{constructor(r,e=Bf){var t;this.timeOrigin=performance.timeOrigin||((t=performance.timing)==null?void 0:t.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=$f(r),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(let i of this.config.eventTargets)this.eventTargets.set(i,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((r,e)=>{if(this.disarmInterval(r),e.interval===0||!e.events.includes(xo))return;let t=()=>{this.recordTargetEvent(r,e,xo),this.processEventTargets()};r.intervalId=setInterval(t,e.interval*1e3),t()})}stop(r=!1){r&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(r){r.sid&&r.sid!==this.data.sid&&this.resetSession(),r.msd&&!isNaN(r.msd)&&(this.msd=r.msd),this.data=Y(Y(Y({},this.data),r),{},{msd:void 0});for(let e of bd)e.field in r&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(r,e={}){let t=Nf.get(r);if(t){let i=t.field,s=e[i];s!==void 0&&ce(this.data,{[i]:s});let n=this.data[i];if(n===void 0||t.equal(n,this.lastEmitted[i]))return;ce(this.lastEmitted,{[i]:t.snapshot(n)})}this.eventTargets.forEach((i,s)=>{this.recordTargetEvent(i,s,r,e)}),this.processEventTargets()}recordTargetEvent(r,e,t,i={}){var s;if(!e.events.includes(t))return;let n=Y(Y(Y({},this.data),i),{},{e:t,ts:(s=i.ts)!=null?s:Date.now(),sn:r.sn++});!isNaN(this.msd)&&!r.msdSent&&(n.msd=this.msd,r.msdSent=!0),r.queue.push(n)}recordResponseReceived(r,e={}){var t,i,s;let{request:n}=r,a=(t=e.url)!=null?t:n?.url;if(!a)return;let o=new URL(a);o.searchParams.delete(Io);let l={url:o.toString(),rc:r.status},d=r.resourceTiming;d&&(d.startTime!=null&&(l.ts=Math.round(this.timeOrigin+d.startTime),d.responseStart!=null&&(l.ttfb=Math.round(d.responseStart-d.startTime))),d.duration!=null&&(l.ttlb=Math.round(d.duration)));let c=(i=(s=n.customData)==null?void 0:s.cmcd)!=null?i:{};this.recordEvent(ea,Y(Y(Y({},c),l),e))}applyRequestReport(r){var e;return(e=this.createRequestReport(r))!=null?e:r}isRequestReportingEnabled(){var r;return!!((r=this.config.enabledKeys)!=null&&r.length)}createRequestReport(r,e){var t;let{customData:i={},headers:s={}}=r,n=Ps(r,af),a=Y(Y({},n),{},{headers:Y({},s),customData:Y(Y({},i),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;let o=new URL(a.url),l=Y(Y(Y({},this.data),e),{},{sn:this.requestTarget.sn++}),d=Lo(ia,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);let c=a.customData.cmcd=Ed(l,d);switch(this.config.transmissionMode){case na:let h=Td(c);h&&(o.searchParams.set(Io,h),a.url=o.toString());break;case Sd:ce(a.headers,_f(c,d.customHeaderMap));break}return a}processEventTargets(r=!1){let e=!1;this.eventTargets.forEach((t,i)=>{let{queue:s}=t;if(!s.length||s.length<i.batchSize&&!r)return;let n=r?s.length:i.batchSize,a=s.splice(0,n);this.sendEventReport(i,a).catch(()=>{t.queue.unshift(...a)}),e||(e=s.length>0)}),e&&this.processEventTargets()}async sendEventReport(r,e){let t=Lo(ta,r),{status:i}=await this.requester({url:r.url,method:"POST",headers:{"Content-Type":Cf},body:e.map(s=>kf(s,t)).join(`
28
28
  `)+`
29
- `});if(i===410)this.disposeEventTarget(r);else if(i===429||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(r){clearInterval(r.intervalId),r.intervalId=void 0}disposeEventTarget(r){let e=this.eventTargets.get(r);e&&(this.disarmInterval(e),this.eventTargets.delete(r))}resetSession(){this.eventTargets.forEach(r=>r.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},Bf={HLS:"h"},nn={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function $f(r,e){return new Be(r,e)}new Set(Ds);new Set(tr);var Uf=["includeKeys"];function xo(r){return Object.keys(r).every(ta)}var ir=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Qe.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Qe.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Qe.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Qe.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Qe.SEEKING)},this.onSeeked=()=>{var s;this.initialized&&(s=this.media)!=null&&s.paused&&this.setPlayerState(Qe.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=s=>{try{this.apply(s,{ot:_e.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{let{frag:o,part:l}=s,d=this.hls.levels[o.level],c=this.getObjectType(o,d),h={d:(l||o).duration*1e3,ot:c};if(c===_e.VIDEO||c===_e.AUDIO||c===_e.MUXED||c==null&&(o.type==="main"||o.type==="audio")){var n;let f=d.bitrate/1e3;h.br=[f];let{cmcd:g}=this.config,m=(n=g?.rtpSafetyFactor)!=null?n:5;if(h.rtp=Math.round(f*m/100)*100,c===_e.MUXED||c==null&&o.type==="main"){let T=this.getTopBandwidth()/1e3;B(T)&&(h.tb=[T]);let E=this.getLowestBandwidth()/1e3;B(E)&&(h.lb=[E])}let p=this.getBufferLength(o);if(B(p)){var a;h.bl=[p];let T=((a=this.media)==null?void 0:a.playbackRate)||1;h.dl=Math.round(p/T/100)*100}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);let v=this.hls.maxAutoLevel;if(v>=0){let T=this.hls.levels[v];T&&(h.tpb=[T.bitrate/1e3])}}let u=l?this.getNextPart(l):this.getNextFrag(o);u!=null&&u.url&&u.url!==o.url&&(u.byteRange.length>0?h.nor=[$f(u.url,{r:`${u.byteRange[0]}-${u.byteRange[1]}`})]:h.nor=[u.url]),this.apply(s,h)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(s,n,a)=>{var o;let{cmcd:l}=this.config,d=l==null||(o=l.eventTargets)==null?void 0:o.some(c=>{var h;return(h=c.events)==null?void 0:h.includes(Ni.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!d))try{this.reporter.recordResponseReceived({request:{url:s},status:n.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(c){this.hls.logger.warn("Could not record fragment response CMCD data.",c)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;let{cmcd:i}=this.config;if(i==null)return;let s=i.version||kf;if(this.reporter=new Nf({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:s,transmissionMode:i.useHeaders===!0?vd:ia,enabledKeys:(e=i.includeKeys)!=null?e:[...s>=Si?tr:Ds],eventTargets:((t=i.eventTargets)!=null?t:[]).map(n=>{let{includeKeys:a}=n,o=Ps(n,Uf);return Y(Y({},o),{},{enabledKeys:a??tr})})},i.loader),this.reporter.update({sf:Bf.HLS,sta:this.playerState}),i.reporterCallback){let n=this.reporter,a={updateCustomData:o=>{xo(o)&&n.update(o)},recordCustomEvent:(o,l={})=>{xo(l)&&n.recordEvent(Ni.CUSTOM_EVENT,Y({cen:o},l))}};i.reporterCallback(a)}this.reporter.start()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(y.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(y.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(y.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(y.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){let i=this.media=t.media;this.setPlayerState(this.media.autoplay?Qe.STARTING:Qe.PRELOADING),de(i,"waiting",this.onWaiting),de(i,"play",this.onPlay),de(i,"playing",this.onPlaying),de(i,"pause",this.onPause),de(i,"seeking",this.onSeeking),de(i,"seeked",this.onSeeked),de(i,"ratechange",this.onRateChange)}onMediaDetached(){let e=this.media;e&&(le(e,"waiting",this.onWaiting),le(e,"play",this.onPlay),le(e,"playing",this.onPlaying),le(e,"pause",this.onPause),le(e,"seeking",this.onSeeking),le(e,"seeked",this.onSeeked),le(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(Qe.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Qe.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(Qe.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Ni.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var i;if(!this.reporter)return;let s={br:[t.bitrate/1e3]},n=(i=t.details)==null?void 0:i.fragments[0];n&&(s.ot=this.getObjectType(n,t)),this.reporter.recordEvent(Ni.BITRATE_CHANGE,s)}onLevelSwitched(e,t){let i=this.hls.levels[t.level];i&&(this.playheadLevel=i)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){let e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?nn.LOW_LATENCY:nn.LIVE:nn.VOD}apply(e,t={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(i=this.media)==null?void 0:i.playbackRate,st:this.getStreamType()});let s=t.ot===_e.INIT||t.ot===_e.VIDEO||t.ot===_e.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let n=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=n.url,e.headers=n.headers}getNextFrag(e){var t;let i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){let s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t;let{index:i,fragment:s}=e,n=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=s;for(let o=n.length-1;o>=0;o--){let l=n[o];if(l.index===i&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e,t){let{type:i}=e;if(i==="subtitle")return _e.TIMED_TEXT;if(e.sn==="initSegment")return _e.INIT;if(i==="audio")return _e.AUDIO;if(i==="main"){if(e.hasStreams){let s=e.elementaryStreams;if(s.audiovideo)return _e.MUXED;if(s.video)return _e.VIDEO;if(s.audio)return _e.AUDIO}if(t){let{audioCodec:s,videoCodec:n}=t;if(!this.hls.audioTracks.length){if(s&&n)return _e.MUXED;if(s)return _e.AUDIO}if(n)return _e.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,i=t.maxAutoLevel,s=i>-1?i+1:t.levels.length;return t.levels.slice(0,s).forEach(a=>{a.bitrate>e&&(e=a.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0,t=this.hls,i=t.maxAutoLevel,s=i>-1?i+1:t.levels.length;return t.levels.slice(0,s).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),B(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;let t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;let e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1e3;let i=e||t;return i?i.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let i=this.getEventBufferLength();B(i)&&this.reporter.update({bl:[i]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=this.recordFragmentResponse,s=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new s(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,o,l){t(a);let{onSuccess:d}=l;this.loader.load(a,o,Y(Y({},l),{},{onSuccess:(c,h,u,f)=>{d(c,h,u,f),i(a.url,c,h)}}))}}}},Gf=3e5,sr=class extends Oe{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if(i?.action===Re.SendAlternateToPenaltyBox&&i.flags&Le.MoveAllAlternatesMatchingHost){let s=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:d}=t.context;o&&s?a=this.getPathwayForGroupId(o,d,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a,!i.resolved&&(t.details!==L.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${fe(n)} penalized: ${fe(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>Gf&&delete i[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Fl(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===te.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===te.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},s={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(c=>{let h=new pe(c.attrs);h["PATHWAY-ID"]=a;let u=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;u&&(i[h.AUDIO]=u,h.AUDIO=u),f&&(s[h.SUBTITLES]=f,h.SUBTITLES=f);let g=Td(c.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Ct({attrs:h,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:g,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let p=1;p<c.audioGroups.length;p++)m.addGroupId("audio",`${c.audioGroups[p]}_clone_${a}`);if(c.subtitleGroups)for(let p=1;p<c.subtitleGroups.length;p++)m.addGroupId("text",`${c.subtitleGroups[p]}_clone_${a}`);return m});t.push(...d),Io(this.audioTracks,i,l,a),Io(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;Tt(s,"_HLS_pathway",this.pathwayId),Tt(s,"_HLS_throughput",""+c)}let n={type:te.STEERING_MANIFEST,responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(c,h,u,f)=>{this.log(`Loaded steering manifest: "${s}"`);let g=c.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;let{"RELOAD-URI":m,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=g;if(m)try{this.uri=new self.URL(m,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||u.url),p&&this.clonePathways(p);let T={steeringManifest:g,url:s.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v)},onError:(c,h,u,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${h.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(c.code===429){let m=this.loader;if(typeof m?.getResponseHeader=="function"){let p=m.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(c,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Io(r,e,t,i){r&&Object.keys(e).forEach(s=>{let n=r.filter(a=>a.groupId===s).map(a=>{let o=ce({},a);return o.details=void 0,o.attrs=new pe(o.attrs),o.url=o.attrs.URI=Td(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function Td(r,e,t,i){if(e){let{[t]:o}=i;if(o){let l=o[e];if(l)return l}}let{HOST:s,PARAMS:n}=i,a=new self.URL(r);return s&&(a.hostname=s),n&&Object.keys(n).sort().forEach(o=>{o&&Tt(a,o,n[o])}),a.href}var Ge=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}},Es=class r extends Oe{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=r.CDMCleanupPromise?[r.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{let{initDataType:i,initData:s}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.log(n),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=jt(this.config));let o=a.map(js).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o,l=wi(a),d=this.activeLevelKeys();if(l===me.FAIRPLAY&&i==="sinf")try{let g=et(new Uint8Array(s)),m=Gr(JSON.parse(g).sinf),p=al(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${n} Failed to parse sinf: ${g}`);return}else if(l===me.PLAYREADY)o=Wr(new Uint8Array(s));else if(l===me.WIDEVINE){let g=cl(s).filter(m=>m.systemId===Pl.WIDEVINE);if(g.length){var c;let m=g[0];o=(c=m.kids)!=null&&c.length?m.kids[0]:null}}let h;if(o){let g=Ie(o);for(let m=0;m<d.length;m++){let p=d[m];if(p.keyId&&(rs(o,p.keyId)||p.uri.replace(/-/g,"").indexOf(g)!==-1)){p.pssh||(p.scheme=i,p.pssh=new Uint8Array(s),p.keyId=o,wt.setKeyIdForUri(p.uri,o)),h=this.getSessionForKey(p,"encrypted-event-key-match");break}}}if(!h){if(d.length){var u,f;return(u=d[0]).scheme||(u.scheme=i),(f=d[0]).pssh||(f.pssh=new Uint8Array(s)),this.getSessionForKey(d[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${Ie(o)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return h}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=d=>{let c=d.shift();this.getMediaKeysPromise(c,s,n).then(h=>a({keySystem:c,mediaKeys:h})).catch(h=>{d.length?l(d):h instanceof Ge?o(h):o(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return _l===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;let n=Lh(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(s=a)==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${fe(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),o.then(d=>{this.throwIfDestroyed(),this.log(`Access for key-system "${d.keySystem}" obtained`);let c=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let h=l.mediaKeys=d.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,c.then(f=>f?this.setMediaKeysServerCertificate(u,e,f):u)));return h.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),h})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,i,s){let{mediaKeySessions:n}=this,a=` key-session "${e}" keyId: ${Ie(i.keyId||[])} keyUri: ${i.uri} for "${s}"`;for(let d=0;d<n.length;d++){let c=n[d];if(!c.initialized&&c.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${a}`),c}this.log(`Creating${a}`);let o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:s},initialized:!1};return n.push(l),l}resetMediaKeys(){var e;let t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,i=this.keySystemAccessPromises[t];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,i.hasMediaKeys=!1,delete i.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,i){let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Ie(t.keyId||[])}
30
- } (data length: ${i.byteLength})`),s.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>js(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{let i=js(t);if(!i)throw new Error(`Unable to find format for key-system "${t}"`);return i})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=jt(this.config),i=e.map(wi).filter(s=>!!s&&t.indexOf(s)!==-1);return this.selectKeySystem(i)}loadClear(e,t,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){let a=t[s];if(e.cc<=a.cc&&(!ve(e)||!ve(a)||e.sn<a.sn)||!i&&s==n-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);let l=wi(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let s=jt(this.config);if(s.length)return this.getKeySystemAccess(s)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let s=rn(e,t[i]);if(s)return s}}loadKey(e){let t=e.decryptdata,i=this.getKeyStatus(t);if(i==="internal-error"){let o=Lo(i,t);return o.data.frag=e,this.error(`${o.message} (${Ie(t.keyId||[])})`),Promise.reject(o)}let s=e.type,n=this.activeKeys,a=n[s];a&&!t.matches(a.decryptdata)&&(n.previous||(n.previous=[]),n.previous.push(a),delete n[s]),n[s]||(n[s]=e);for(let o=this.mediaKeySessions.length;o--;){let l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[Ie(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,i){let s=this.getSessionForKey(e,t);return s.catch(n=>this.handleError(n,i)),s.then(n=>e)}getSessionForKey(e,t){let i=this.findContextForKey(e);if(i!==void 0)return Promise.resolve(i);let s=e.uri,n=this.sessionSetupByUri[s],a;n===void 0?a=this.resolveSessionForKey(e,t):a=n.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[s]=a;let o=()=>{this.sessionSetupByUri[s]===a&&delete this.sessionSetupByUri[s]};return a.then(o,o),a}findContextForKey(e){let{mediaKeySessions:t}=this;for(let i=t.length;i--;){let s=t[i];if(rn(e,s))return s}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:s})=>{this.throwIfDestroyed();for(let n=this.mediaKeySessions.length;n--;){let a=this.mediaKeySessions[n];if(rn(e,a))return a;let o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,s,e,t))).then(n=>{this.throwIfDestroyed();let a=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(n,e,a,o,t)})})}getUsableKeyPromise(e,t,i){let s=e.keyRequests[t.uri];if(s)return this.log(`Waiting for usable key (${i} keyId: ${Kf(t)} format: "${t.keyFormat}" URI: ${t.uri})`),Ro(s).then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ge){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${Ie(i.keyId||[])})`:""}`),this.hls.trigger(y.ERROR,e.data)}else this.error(e.message),this.hls.trigger(y.ERROR,{type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=wi(e.keyFormat),i=t?[t]:jt(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(e){if(e.length||(e=jt(this.config)),e.length===0)throw new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${fe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(i=>i.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}filterInitData(e,t,i,s,n){var a;let o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let d=o.call(this.hls,i,s,ce({},e,{decryptdata:t,reason:n}),n);if(!d)throw new Error("Invalid response from configured generateRequest filter");t.scheme=d.initDataType?d.initDataType:"cenc";let c=d.initData?d.initData:null;return t.pssh=c?new Uint8Array(c):null,d}catch(d){var l;if(this.warn(d.message),(l=this.hls)!=null&&l.config.debug)throw d}return{initDataType:i,initData:s}}generateRequestWithPreferredKeySession(e,t,i,s,n){let a=this.getUsableKeyPromise(e,t,n);if(a)return a;let o=this.filterInitData(e,t,i,s,n);if(o&&(s=o.initData?o.initData:null,i=o.initDataType),s===null)return n.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${n}"`)):(this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e));let l=t.uri,d=new Yr;d.status="initialized",d.requestErrors=[],e.keyRequests[l]=d;let c=u=>{let f=e.mediaKeysSession;if(!f){let p=new Error("invalid state");d.errored=p,d.emit("error",p);return}let{messageType:g,message:m}=u;d.status=g,this.log(`"${g}" message event for session "${f.sessionId}" message size: ${m.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,t,m).catch(p=>{d.errored=p,d.eventNames().length?d.emit("error",p):this.handleError(p),this.removeSession(e)}):g==="license-release"?e.keySystem===me.FAIRPLAY&&this.updateKeySession(e,t,kn("acknowledged")).then(()=>this.removeSession(e)).catch(p=>this.handleError(p)):this.warn(`unhandled media key message type "${g}"`)};return d.onmessage=c,de(e.mediaKeysSession,"message",c),this.generateRequest(e,t,i,s,n,!1)}generateRequest(e,t,i,s,n,a){if(a){let f=this.filterInitData(e,t,i,s,n);f&&(s=f.initData?f.initData:s,i=f.initDataType)}let o=t.uri,l=e.keyRequests[o],d=Ie(t.keyId||[]),c=f=>{let g;f.startsWith("usable")?(l.resolved=!0,l.emit("resolved")):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?g=Lo(f,t):f==="expired"?g=new Error(`key expired (keyId: ${d})`):f==="released"?g=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${d})`),g&&(l.errored=g,l.eventNames().length?l.emit("error",g):this.handleError(g))},h=f=>{if(!e.mediaKeysSession){let b=new Error("invalid state");l.errored=b,l.emit("error",b);return}let m=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(m).some(b=>m[b]!=="status-pending"))return;let v=this.activeLevelKeys();for(let b=0;b<v.length;b++){let A=Ie(v[b].keyId||[]);if(m[A]==="expired"){var T;this.log(`Expired key ${fe(m)} in key-session "${(T=e.mediaKeysSession)==null?void 0:T.sessionId}"`),this.renewKeySession(t,e).catch(x=>this.handleError(x));break}}let E=m[d];if(E)c(E);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[d]||(S[d]=self.setTimeout(()=>{var A;if(!e.mediaKeysSession)return;let x=this.getKeyStatus(t);if(x&&x!=="status-pending"){var R;return this.log(`No status for keyId ${d} in key-session "${(R=e.mediaKeysSession)==null?void 0:R.sessionId}". Using session key-status ${x} from other session.`),c(x)}this.log(`key status for ${d} in key-session "${(A=e.mediaKeysSession)==null?void 0:A.sessionId}" timed out after 1000ms`),E="internal-error",c(E)},1e3)),this.log(`No status for keyId ${d} (${fe(m)}).`)}};l.onkeystatuseschange=h,de(e.mediaKeysSession,"keystatuseschange",h);let u=Ro(l);return this.log(`Generating key-session request for "${n}" keyId: ${d} URI: ${o} (init data type: ${i} length: ${s.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(i,s).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${d} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>u).catch(f=>{var g;this.log(`mediaKeysSession.generateRequest failed: ${f}`);let m=(g=f.data)==null?void 0:g.details;return(m===L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||m===L.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(p=>e.keyStatuses[p]==="usable")?(this.handleError(f),e):(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))}).then(()=>e)}getKeyStatuses(e){let t={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((s,n)=>{if(typeof n=="string"&&typeof s=="object"){let l=n;n=s,s=l}let a="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===me.PLAYREADY&&a.length===16){let l=Ie(a);t[l]=s,Ll(a)}let o=Ie(a);this.log(`key status change "${s}" for keyStatuses keyId: ${o} key-session "${i}"`),t[o]=s}),t}fetchServerCertificate(e){let t=this.config,i=t.loader,s=new i(t),n=Hf(e,t);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={type:te.SERVER_CERTIFICATE,responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,m)=>{a(u.data)},onError:(u,f,g,m)=>{o(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:Y({url:l.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{o(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(u,f,g)=>{o(new Error("aborted"))}};s.load(l,c,h)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,i){return this.requestLicense(e,t,new Uint8Array(i)).then(s=>this.updateKeySession(e,t,new Uint8Array(s)).catch(n=>{throw new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){let i=et(new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let s=new DOMParser().parseFromString(i,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let h=0,u=n.length;h<u;h++){var a,o;c=n[h];let f=(a=c.querySelector("name"))==null?void 0:a.textContent,g=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}let l=s.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return kn(atob(d))}setupLicenseXHR(e,t,i,s,n){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,Y(Y({},i),{},{decryptdata:s}),n))).catch(o=>{if(!i.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,Y(Y({},i),{},{decryptdata:s}),n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t,i){return new Promise((s,n)=>{let a=Vf(e.keySystem,this.config);if(!a)return n(new Error(`no license server URL configured for key-system "${e.keySystem}"`));let o=e.keyRequests[t.uri];if(!o)return n(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);let l=this.config.keyLoadPolicy.default,d=new XMLHttpRequest;d.responseType="arraybuffer",d.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(d.readyState===4)if(d.status===200){o.requestErrors=[];let c=d.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);let h=this.config.licenseResponseCallback;if(h)try{c=h.call(this.hls,d,a,Y(Y({},e),{},{decryptdata:t}))}catch(u){this.error(u)}s(c)}else{let c=l.errorRetry,h=c?c.maxNumRetry:0;if(o.requestErrors.push({status:d.status,message:d.statusText}),o.requestErrors.length>h||d.status>=400&&d.status<500)n(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:d,response:{url:a,data:void 0,code:d.status,text:d.statusText}},`License Request XHR failed (${a}). Status: ${d.status} (${d.statusText})`));else{let u=h-o.requestErrors.length;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t,i).then(s,n)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=d,this.setupLicenseXHR(d,a,e,t,i).then(({xhr:c,licenseChallenge:h})=>{e.keySystem==me.PLAYREADY&&(h=this.unpackPlayReadyKeyMessage(c,h)),c.send(h)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,de(i,"encrypted",this.onMediaEncrypted),de(i,"waitingforkey",this.onWaitingForKey);let s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){let e=this.media;e&&(le(e,"encrypted",this.onMediaEncrypted),le(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,wt.clearKeyUriToKeyIdMap();let n=s.length;r.CDMCleanupPromise=Promise.all(s.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch(()=>{})}}removeSession(e){let{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(o=>{let l=e.keyRequests[o];l.onmessage&&(t.removeEventListener("message",l.onmessage),l.onmessage=void 0),l.onkeystatuseschange&&(t.removeEventListener("keystatuseschange",l.onkeystatuseschange),l.onkeystatuseschange=void 0);let d=l.licenseXhr;d&&(d.readyState!==XMLHttpRequest.DONE&&d.abort(),l.licenseXhr=void 0),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;let i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);let{keyStatusTimeouts:s}=e;s&&Object.keys(s).forEach(o=>self.clearTimeout(s[o]));let{drmSystemOptions:n}=this.config;return(Ph(n)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o).catch(l)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}};Es.CDMCleanupPromise=void 0;function Vf(r,e){let{drmSystems:t,widevineLicenseUrl:i}=e,s=t?.[r];if(s)return s.licenseUrl;if(r===me.WIDEVINE&&i)return i}function Hf(r,e){let{drmSystems:t}=e,i=t?.[r];if(i)return i.serverCertificateUrl}function Kf(r){if(r.keyFormat===ke.FAIRPLAY)return r.uri;if(r.keyId===null)throw new Error("keyId is null");return Ie(r.keyId)}function rn(r,e){let t=r.keyId,i=e.mediaKeysSession;if(t&&i){let s=e.mediaKeysSession.keyStatuses;if(s.size)return s.has(t)?s.get(t):e.keyStatuses[Ie(t)]}}function Lo(r,e){let t=r==="output-restricted",i=t?L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ge({type:W.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}function Ro(r){return new Promise((e,t)=>{if(r.resolved)return e();if(r.errored)return t(r.errored);r.on("error",t),r.on("resolved",e)})}var nr=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let s=performance.now();if(t){if(this.lastTime){let n=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let c=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=c)&&(c=c-1,d.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:d.currentLevel}),d.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},sa=function(){if(as!=null&&as.VTTCue)return self.VTTCue;let r=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let d=l.toLowerCase();return~o.indexOf(d)?d:!1}function i(o){return t(r,o)}function s(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){let c=arguments[d];for(let h in c)o[h]=c[h]}return o}function a(o,l,d){let c=this,h={enumerable:!0};c.hasBeenReset=!1;let u="",f=!1,g=o,m=l,p=d,v=null,T="",E=!0,S="auto",b="start",A=50,x="middle",R=50,P="middle";Object.defineProperty(c,"id",n({},h,{get:function(){return u},set:function(I){u=""+I}})),Object.defineProperty(c,"pauseOnExit",n({},h,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(c,"startTime",n({},h,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},h,{get:function(){return m},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");m=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},h,{get:function(){return p},set:function(I){p=""+I,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},h,{get:function(){return v},set:function(I){v=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},h,{get:function(){return T},set:function(I){let k=i(I);if(k===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},h,{get:function(){return E},set:function(I){E=!!I,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},h,{get:function(){return S},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},h,{get:function(){return b},set:function(I){let k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");b=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},h,{get:function(){return A},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");A=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},h,{get:function(){return x},set:function(I){let k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");x=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},h,{get:function(){return R},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");R=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},h,{get:function(){return P},set:function(I){let k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");P=k,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),rr=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Sd(r){function e(i,s,n,a){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}let t=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var ar=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}};function bd(r,e,t,i){let s=i?r.split(i):[r];for(let n in s){if(typeof s[n]!="string")continue;let a=s[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l)}}var or=new sa(0,0,""),Bi=or.align==="middle"?"middle":"center";function qf(r,e,t){let i=r;function s(){let o=Sd(r);if(o===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let d=new ar;bd(o,function(u,f){let g;switch(u){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){d.set(u,t[m].region);break}break;case"vertical":d.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),d.integer(u,g[0]),d.percent(u,g[0])&&d.set("snapToLines",!1),d.alt(u,g[0],["auto"]),g.length===2&&d.alt("lineAlign",g[1],["start",Bi,"end"]);break;case"position":g=f.split(","),d.percent(u,g[0]),g.length===2&&d.alt("positionAlign",g[1],["start",Bi,"end","line-left","line-right","auto"]);break;case"size":d.percent(u,f);break;case"align":d.alt(u,f,["start",Bi,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let c=d.get("line","auto");c==="auto"&&or.line===-1&&(c=-1),l.line=c,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",Bi);let h=d.get("position","auto");h==="auto"&&or.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function a(){r=r.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),a(),e.endTime=s(),a(),n(r,e)}function Ad(r){return r.replace(/<br(?: \/)?>/gi,`
31
- `)}var lr=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new rr,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,a=0;for(n=Ad(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
29
+ `});if(i===410)this.disposeEventTarget(r);else if(i===429||i>499&&i<600)throw new Error(`Event report failed with status ${i}`)}disarmInterval(r){clearInterval(r.intervalId),r.intervalId=void 0}disposeEventTarget(r){let e=this.eventTargets.get(r);e&&(this.disarmInterval(e),this.eventTargets.delete(r))}resetSession(){this.eventTargets.forEach(r=>r.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},Gf={HLS:"h"},an={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function Vf(r,e){return new Be(r,e)}new Set(Ds);new Set(sr);var Hf=["includeKeys"];function Ro(r){return Object.keys(r).every(sa)}var nr=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Qe.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Qe.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Qe.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Qe.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Qe.SEEKING)},this.onSeeked=()=>{var s;this.initialized&&(s=this.media)!=null&&s.paused&&this.setPlayerState(Qe.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=s=>{try{this.apply(s,{ot:_e.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{let{frag:o,part:l}=s,d=this.hls.levels[o.level],c=this.getObjectType(o,d),h={d:(l||o).duration*1e3,ot:c};if(c===_e.VIDEO||c===_e.AUDIO||c===_e.MUXED||c==null&&(o.type==="main"||o.type==="audio")){var n;let f=d.bitrate/1e3;h.br=[f];let{cmcd:g}=this.config,m=(n=g?.rtpSafetyFactor)!=null?n:5;if(h.rtp=Math.round(f*m/100)*100,c===_e.MUXED||c==null&&o.type==="main"){let T=this.getTopBandwidth()/1e3;B(T)&&(h.tb=[T]);let E=this.getLowestBandwidth()/1e3;B(E)&&(h.lb=[E])}let p=this.getBufferLength(o);if(B(p)){var a;h.bl=[p];let T=((a=this.media)==null?void 0:a.playbackRate)||1;h.dl=Math.round(p/T/100)*100}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);let v=this.hls.maxAutoLevel;if(v>=0){let T=this.hls.levels[v];T&&(h.tpb=[T.bitrate/1e3])}}let u=l?this.getNextPart(l):this.getNextFrag(o);u!=null&&u.url&&u.url!==o.url&&(u.byteRange.length>0?h.nor=[Vf(u.url,{r:`${u.byteRange[0]}-${u.byteRange[1]}`})]:h.nor=[u.url]),this.apply(s,h)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(s,n,a)=>{var o;let{cmcd:l}=this.config,d=l==null||(o=l.eventTargets)==null?void 0:o.some(c=>{var h;return(h=c.events)==null?void 0:h.includes(Ni.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!d))try{this.reporter.recordResponseReceived({request:{url:s},status:n.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(c){this.hls.logger.warn("Could not record fragment response CMCD data.",c)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;let{cmcd:i}=this.config;if(i==null)return;let s=i.version||wf;if(this.reporter=new Uf({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:s,transmissionMode:i.useHeaders===!0?Sd:na,enabledKeys:(e=i.includeKeys)!=null?e:[...s>=Si?sr:Ds],eventTargets:((t=i.eventTargets)!=null?t:[]).map(n=>{let{includeKeys:a}=n,o=Ps(n,Hf);return Y(Y({},o),{},{enabledKeys:a??sr})})},i.loader),this.reporter.update({sf:Gf.HLS,sta:this.playerState}),i.reporterCallback){let n=this.reporter,a={updateCustomData:o=>{Ro(o)&&n.update(o)},recordCustomEvent:(o,l={})=>{Ro(l)&&n.recordEvent(Ni.CUSTOM_EVENT,Y({cen:o},l))}};i.reporterCallback(a)}this.reporter.start()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(y.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(y.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(y.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(y.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){let i=this.media=t.media;this.setPlayerState(this.media.autoplay?Qe.STARTING:Qe.PRELOADING),de(i,"waiting",this.onWaiting),de(i,"play",this.onPlay),de(i,"playing",this.onPlaying),de(i,"pause",this.onPause),de(i,"seeking",this.onSeeking),de(i,"seeked",this.onSeeked),de(i,"ratechange",this.onRateChange)}onMediaDetached(){let e=this.media;e&&(le(e,"waiting",this.onWaiting),le(e,"play",this.onPlay),le(e,"playing",this.onPlaying),le(e,"pause",this.onPause),le(e,"seeking",this.onSeeking),le(e,"seeked",this.onSeeked),le(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(Qe.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Qe.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(Qe.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Ni.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var i;if(!this.reporter)return;let s={br:[t.bitrate/1e3]},n=(i=t.details)==null?void 0:i.fragments[0];n&&(s.ot=this.getObjectType(n,t)),this.reporter.recordEvent(Ni.BITRATE_CHANGE,s)}onLevelSwitched(e,t){let i=this.hls.levels[t.level];i&&(this.playheadLevel=i)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){let e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?an.LOW_LATENCY:an.LIVE:an.VOD}apply(e,t={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(i=this.media)==null?void 0:i.playbackRate,st:this.getStreamType()});let s=t.ot===_e.INIT||t.ot===_e.VIDEO||t.ot===_e.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let n=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=n.url,e.headers=n.headers}getNextFrag(e){var t;let i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){let s=e.sn-i.startSN;return i.fragments[s+1]}}getNextPart(e){var t;let{index:i,fragment:s}=e,n=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=s;for(let o=n.length-1;o>=0;o--){let l=n[o];if(l.index===i&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e,t){let{type:i}=e;if(i==="subtitle")return _e.TIMED_TEXT;if(e.sn==="initSegment")return _e.INIT;if(i==="audio")return _e.AUDIO;if(i==="main"){if(e.hasStreams){let s=e.elementaryStreams;if(s.audiovideo)return _e.MUXED;if(s.video)return _e.VIDEO;if(s.audio)return _e.AUDIO}if(t){let{audioCodec:s,videoCodec:n}=t;if(!this.hls.audioTracks.length){if(s&&n)return _e.MUXED;if(s)return _e.AUDIO}if(n)return _e.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,i=t.maxAutoLevel,s=i>-1?i+1:t.levels.length;return t.levels.slice(0,s).forEach(a=>{a.bitrate>e&&(e=a.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0,t=this.hls,i=t.maxAutoLevel,s=i>-1?i+1:t.levels.length;return t.levels.slice(0,s).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),B(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;let t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;let e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1e3;let i=e||t;return i?i.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let i=this.getEventBufferLength();B(i)&&this.reporter.update({bl:[i]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=this.recordFragmentResponse,s=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new s(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,o,l){t(a);let{onSuccess:d}=l;this.loader.load(a,o,Y(Y({},l),{},{onSuccess:(c,h,u,f)=>{d(c,h,u,f),i(a.url,c,h)}}))}}}},Kf=3e5,rr=class extends Oe{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if(i?.action===Re.SendAlternateToPenaltyBox&&i.flags&Le.MoveAllAlternatesMatchingHost){let s=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:d}=t.context;o&&s?a=this.getPathwayForGroupId(o,d,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&s&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a,!i.resolved&&(t.details!==L.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${s&&s.length} priorities: ${fe(n)} penalized: ${fe(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>Kf&&delete i[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,$l(t),this.hls.trigger(y.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<s.length;n++)if(t===te.AUDIO_TRACK&&s[n].hasAudioGroup(e)||t===te.SUBTITLE_TRACK&&s[n].hasSubtitleGroup(e))return s[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},s={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(c=>{let h=new pe(c.attrs);h["PATHWAY-ID"]=a;let u=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;u&&(i[h.AUDIO]=u,h.AUDIO=u),f&&(s[h.SUBTITLES]=f,h.SUBTITLES=f);let g=Ad(c.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Ct({attrs:h,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:g,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let p=1;p<c.audioGroups.length;p++)m.addGroupId("audio",`${c.audioGroups[p]}_clone_${a}`);if(c.subtitleGroups)for(let p=1;p<c.subtitleGroups.length;p++)m.addGroupId("text",`${c.subtitleGroups[p]}_clone_${a}`);return m});t.push(...d),Po(this.audioTracks,i,l,a),Po(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;Tt(s,"_HLS_pathway",this.pathwayId),Tt(s,"_HLS_throughput",""+c)}let n={type:te.STEERING_MANIFEST,responseType:"json",url:s.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(c,h,u,f)=>{this.log(`Loaded steering manifest: "${s}"`);let g=c.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;let{"RELOAD-URI":m,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=g;if(m)try{this.uri=new self.URL(m,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||u.url),p&&this.clonePathways(p);let T={steeringManifest:g,url:s.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v)},onError:(c,h,u,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${h.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(c.code===429){let m=this.loader;if(typeof m?.getResponseHeader=="function"){let p=m.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(c,h,u)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Po(r,e,t,i){r&&Object.keys(e).forEach(s=>{let n=r.filter(a=>a.groupId===s).map(a=>{let o=ce({},a);return o.details=void 0,o.attrs=new pe(o.attrs),o.url=o.attrs.URI=Ad(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function Ad(r,e,t,i){if(e){let{[t]:o}=i;if(o){let l=o[e];if(l)return l}}let{HOST:s,PARAMS:n}=i,a=new self.URL(r);return s&&(a.hostname=s),n&&Object.keys(n).sort().forEach(o=>{o&&Tt(a,o,n[o])}),a.href}var Ge=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}},Es=class r extends Oe{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=r.CDMCleanupPromise?[r.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{let{initDataType:i,initData:s}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.log(n),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=jt(this.config));let o=a.map(Xs).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o,l=wi(a),d=this.activeLevelKeys();if(l===me.FAIRPLAY&&i==="sinf")try{let g=et(new Uint8Array(s)),m=Hr(JSON.parse(g).sinf),p=dl(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${n} Failed to parse sinf: ${g}`);return}else if(l===me.PLAYREADY)o=jr(new Uint8Array(s));else if(l===me.WIDEVINE){let g=fl(s).filter(m=>m.systemId===Dl.WIDEVINE);if(g.length){var c;let m=g[0];o=(c=m.kids)!=null&&c.length?m.kids[0]:null}}let h;if(o){let g=Ie(o);for(let m=0;m<d.length;m++){let p=d[m];if(p.keyId&&(rs(o,p.keyId)||p.uri.replace(/-/g,"").indexOf(g)!==-1)){p.pssh||(p.scheme=i,p.pssh=new Uint8Array(s),p.keyId=o,wt.setKeyIdForUri(p.uri,o)),h=this.getSessionForKey(p,"encrypted-event-key-match");break}}}if(!h){if(d.length){var u,f;return(u=d[0]).scheme||(u.scheme=i),(f=d[0]).pssh||(f.pssh=new Uint8Array(s)),this.getSessionForKey(d[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${Ie(o)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return h}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=d=>{let c=d.shift();this.getMediaKeysPromise(c,s,n).then(h=>a({keySystem:c,mediaKeys:h})).catch(h=>{d.length?l(d):h instanceof Ge?o(h):o(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Cl===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;let n=_h(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(s=a)==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${fe(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),o.then(d=>{this.throwIfDestroyed(),this.log(`Access for key-system "${d.keySystem}" obtained`);let c=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let h=l.mediaKeys=d.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,c.then(f=>f?this.setMediaKeysServerCertificate(u,e,f):u)));return h.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),h})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,i,s){let{mediaKeySessions:n}=this,a=` key-session "${e}" keyId: ${Ie(i.keyId||[])} keyUri: ${i.uri} for "${s}"`;for(let d=0;d<n.length;d++){let c=n[d];if(!c.initialized&&c.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${a}`),c}this.log(`Creating${a}`);let o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:s},initialized:!1};return n.push(l),l}resetMediaKeys(){var e;let t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,i=this.keySystemAccessPromises[t];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,i.hasMediaKeys=!1,delete i.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,i){let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Ie(t.keyId||[])}
30
+ } (data length: ${i.byteLength})`),s.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Xs(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{let i=Xs(t);if(!i)throw new Error(`Unable to find format for key-system "${t}"`);return i})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=jt(this.config),i=e.map(wi).filter(s=>!!s&&t.indexOf(s)!==-1);return this.selectKeySystem(i)}loadClear(e,t,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){let a=t[s];if(e.cc<=a.cc&&(!ve(e)||!ve(a)||e.sn<a.sn)||!i&&s==n-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);let l=wi(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let s=jt(this.config);if(s.length)return this.getKeySystemAccess(s)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let s=on(e,t[i]);if(s)return s}}loadKey(e){let t=e.decryptdata,i=this.getKeyStatus(t);if(i==="internal-error"){let o=_o(i,t);return o.data.frag=e,this.error(`${o.message} (${Ie(t.keyId||[])})`),Promise.reject(o)}let s=e.type,n=this.activeKeys,a=n[s];a&&!t.matches(a.decryptdata)&&(n.previous||(n.previous=[]),n.previous.push(a),delete n[s]),n[s]||(n[s]=e);for(let o=this.mediaKeySessions.length;o--;){let l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[Ie(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,i){let s=this.getSessionForKey(e,t);return s.catch(n=>this.handleError(n,i)),s.then(n=>e)}getSessionForKey(e,t){let i=this.findContextForKey(e);if(i!==void 0)return Promise.resolve(i);let s=e.uri,n=this.sessionSetupByUri[s],a;n===void 0?a=this.resolveSessionForKey(e,t):a=n.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[s]=a;let o=()=>{this.sessionSetupByUri[s]===a&&delete this.sessionSetupByUri[s]};return a.then(o,o),a}findContextForKey(e){let{mediaKeySessions:t}=this;for(let i=t.length;i--;){let s=t[i];if(on(e,s))return s}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:s})=>{this.throwIfDestroyed();for(let n=this.mediaKeySessions.length;n--;){let a=this.mediaKeySessions[n];if(on(e,a))return a;let o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,s,e,t))).then(n=>{this.throwIfDestroyed();let a=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(n,e,a,o,t)})})}getUsableKeyPromise(e,t,i){let s=e.keyRequests[t.uri];if(s)return this.log(`Waiting for usable key (${i} keyId: ${Yf(t)} format: "${t.keyFormat}" URI: ${t.uri})`),ko(s).then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ge){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${Ie(i.keyId||[])})`:""}`),this.hls.trigger(y.ERROR,e.data)}else this.error(e.message),this.hls.trigger(y.ERROR,{type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=wi(e.keyFormat),i=t?[t]:jt(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(e){if(e.length||(e=jt(this.config)),e.length===0)throw new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${fe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(i=>i.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}filterInitData(e,t,i,s,n){var a;let o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let d=o.call(this.hls,i,s,ce({},e,{decryptdata:t,reason:n}),n);if(!d)throw new Error("Invalid response from configured generateRequest filter");t.scheme=d.initDataType?d.initDataType:"cenc";let c=d.initData?d.initData:null;return t.pssh=c?new Uint8Array(c):null,d}catch(d){var l;if(this.warn(d.message),(l=this.hls)!=null&&l.config.debug)throw d}return{initDataType:i,initData:s}}generateRequestWithPreferredKeySession(e,t,i,s,n){let a=this.getUsableKeyPromise(e,t,n);if(a)return a;let o=this.filterInitData(e,t,i,s,n);if(o&&(s=o.initData?o.initData:null,i=o.initDataType),s===null)return n.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${n}"`)):(this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e));let l=t.uri,d=new zr;d.status="initialized",d.requestErrors=[],e.keyRequests[l]=d;let c=u=>{let f=e.mediaKeysSession;if(!f){let p=new Error("invalid state");d.errored=p,d.emit("error",p);return}let{messageType:g,message:m}=u;d.status=g,this.log(`"${g}" message event for session "${f.sessionId}" message size: ${m.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,t,m).catch(p=>{d.errored=p,d.eventNames().length?d.emit("error",p):this.handleError(p),this.removeSession(e)}):g==="license-release"?e.keySystem===me.FAIRPLAY&&this.updateKeySession(e,t,Cn("acknowledged")).then(()=>this.removeSession(e)).catch(p=>this.handleError(p)):this.warn(`unhandled media key message type "${g}"`)};return d.onmessage=c,de(e.mediaKeysSession,"message",c),this.generateRequest(e,t,i,s,n,!1)}generateRequest(e,t,i,s,n,a){if(a){let f=this.filterInitData(e,t,i,s,n);f&&(s=f.initData?f.initData:s,i=f.initDataType)}let o=t.uri,l=e.keyRequests[o],d=Ie(t.keyId||[]),c=f=>{let g;f.startsWith("usable")?(l.resolved=!0,l.emit("resolved")):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?g=_o(f,t):f==="expired"?g=new Error(`key expired (keyId: ${d})`):f==="released"?g=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${d})`),g&&(l.errored=g,l.eventNames().length?l.emit("error",g):this.handleError(g))},h=f=>{if(!e.mediaKeysSession){let b=new Error("invalid state");l.errored=b,l.emit("error",b);return}let m=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(m).some(b=>m[b]!=="status-pending"))return;let v=this.activeLevelKeys();for(let b=0;b<v.length;b++){let A=Ie(v[b].keyId||[]);if(m[A]==="expired"){var T;this.log(`Expired key ${fe(m)} in key-session "${(T=e.mediaKeysSession)==null?void 0:T.sessionId}"`),this.renewKeySession(t,e).catch(x=>this.handleError(x));break}}let E=m[d];if(E)c(E);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[d]||(S[d]=self.setTimeout(()=>{var A;if(!e.mediaKeysSession)return;let x=this.getKeyStatus(t);if(x&&x!=="status-pending"){var R;return this.log(`No status for keyId ${d} in key-session "${(R=e.mediaKeysSession)==null?void 0:R.sessionId}". Using session key-status ${x} from other session.`),c(x)}this.log(`key status for ${d} in key-session "${(A=e.mediaKeysSession)==null?void 0:A.sessionId}" timed out after 1000ms`),E="internal-error",c(E)},1e3)),this.log(`No status for keyId ${d} (${fe(m)}).`)}};l.onkeystatuseschange=h,de(e.mediaKeysSession,"keystatuseschange",h);let u=ko(l);return this.log(`Generating key-session request for "${n}" keyId: ${d} URI: ${o} (init data type: ${i} length: ${s.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(i,s).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${d} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>u).catch(f=>{var g;this.log(`mediaKeysSession.generateRequest failed: ${f}`);let m=(g=f.data)==null?void 0:g.details;return(m===L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||m===L.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(p=>e.keyStatuses[p]==="usable")?(this.handleError(f),e):(l.removeAllListeners(),this.removeSession(e).then(()=>{throw f}))}).then(()=>e)}getKeyStatuses(e){let t={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((s,n)=>{if(typeof n=="string"&&typeof s=="object"){let l=n;n=s,s=l}let a="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===me.PLAYREADY&&a.length===16){let l=Ie(a);t[l]=s,_l(a)}let o=Ie(a);this.log(`key status change "${s}" for keyStatuses keyId: ${o} key-session "${i}"`),t[o]=s}),t}fetchServerCertificate(e){let t=this.config,i=t.loader,s=new i(t),n=Wf(e,t);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={type:te.SERVER_CERTIFICATE,responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,m)=>{a(u.data)},onError:(u,f,g,m)=>{o(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:Y({url:l.url,data:void 0},u)},`"${e}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{o(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(u,f,g)=>{o(new Error("aborted"))}};s.load(l,c,h)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,i){return new Promise((s,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(a=>{n(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,i){return this.requestLicense(e,t,new Uint8Array(i)).then(s=>this.updateKeySession(e,t,new Uint8Array(s)).catch(n=>{throw new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){let i=et(new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let s=new DOMParser().parseFromString(i,"application/xml"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let h=0,u=n.length;h<u;h++){var a,o;c=n[h];let f=(a=c.querySelector("name"))==null?void 0:a.textContent,g=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}let l=s.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return Cn(atob(d))}setupLicenseXHR(e,t,i,s,n){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,Y(Y({},i),{},{decryptdata:s}),n))).catch(o=>{if(!i.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,Y(Y({},i),{},{decryptdata:s}),n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t,i){return new Promise((s,n)=>{let a=qf(e.keySystem,this.config);if(!a)return n(new Error(`no license server URL configured for key-system "${e.keySystem}"`));let o=e.keyRequests[t.uri];if(!o)return n(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);let l=this.config.keyLoadPolicy.default,d=new XMLHttpRequest;d.responseType="arraybuffer",d.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(d.readyState===4)if(d.status===200){o.requestErrors=[];let c=d.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);let h=this.config.licenseResponseCallback;if(h)try{c=h.call(this.hls,d,a,Y(Y({},e),{},{decryptdata:t}))}catch(u){this.error(u)}s(c)}else{let c=l.errorRetry,h=c?c.maxNumRetry:0;if(o.requestErrors.push({status:d.status,message:d.statusText}),o.requestErrors.length>h||d.status>=400&&d.status<500)n(new Ge({type:W.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:d,response:{url:a,data:void 0,code:d.status,text:d.statusText}},`License Request XHR failed (${a}). Status: ${d.status} (${d.statusText})`));else{let u=h-o.requestErrors.length;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t,i).then(s,n)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=d,this.setupLicenseXHR(d,a,e,t,i).then(({xhr:c,licenseChallenge:h})=>{e.keySystem==me.PLAYREADY&&(h=this.unpackPlayReadyKeyMessage(c,h)),c.send(h)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,de(i,"encrypted",this.onMediaEncrypted),de(i,"waitingforkey",this.onWaitingForKey);let s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){let e=this.media;e&&(le(e,"encrypted",this.onMediaEncrypted),le(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,wt.clearKeyUriToKeyIdMap();let n=s.length;r.CDMCleanupPromise=Promise.all(s.map(a=>this.removeSession(a)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch(()=>{})}}removeSession(e){let{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(o=>{let l=e.keyRequests[o];l.onmessage&&(t.removeEventListener("message",l.onmessage),l.onmessage=void 0),l.onkeystatuseschange&&(t.removeEventListener("keystatuseschange",l.onkeystatuseschange),l.onkeystatuseschange=void 0);let d=l.licenseXhr;d&&(d.readyState!==XMLHttpRequest.DONE&&d.abort(),l.licenseXhr=void 0),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;let i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);let{keyStatusTimeouts:s}=e;s&&Object.keys(s).forEach(o=>self.clearTimeout(s[o]));let{drmSystemOptions:n}=this.config;return(Dh(n)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o).catch(l)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}};Es.CDMCleanupPromise=void 0;function qf(r,e){let{drmSystems:t,widevineLicenseUrl:i}=e,s=t?.[r];if(s)return s.licenseUrl;if(r===me.WIDEVINE&&i)return i}function Wf(r,e){let{drmSystems:t}=e,i=t?.[r];if(i)return i.serverCertificateUrl}function Yf(r){if(r.keyFormat===ke.FAIRPLAY)return r.uri;if(r.keyId===null)throw new Error("keyId is null");return Ie(r.keyId)}function on(r,e){let t=r.keyId,i=e.mediaKeysSession;if(t&&i){let s=e.mediaKeysSession.keyStatuses;if(s.size)return s.has(t)?s.get(t):e.keyStatuses[Ie(t)]}}function _o(r,e){let t=r==="output-restricted",i=t?L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ge({type:W.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}function ko(r){return new Promise((e,t)=>{if(r.resolved)return e();if(r.errored)return t(r.errored);r.on("error",t),r.on("resolved",e)})}var ar=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let s=performance.now();if(t){if(this.lastTime){let n=s-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let c=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=c)&&(c=c-1,d.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:d.currentLevel}),d.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},ra=function(){if(as!=null&&as.VTTCue)return self.VTTCue;let r=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let d=l.toLowerCase();return~o.indexOf(d)?d:!1}function i(o){return t(r,o)}function s(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){let c=arguments[d];for(let h in c)o[h]=c[h]}return o}function a(o,l,d){let c=this,h={enumerable:!0};c.hasBeenReset=!1;let u="",f=!1,g=o,m=l,p=d,v=null,T="",E=!0,S="auto",b="start",A=50,x="middle",R=50,P="middle";Object.defineProperty(c,"id",n({},h,{get:function(){return u},set:function(I){u=""+I}})),Object.defineProperty(c,"pauseOnExit",n({},h,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(c,"startTime",n({},h,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},h,{get:function(){return m},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");m=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},h,{get:function(){return p},set:function(I){p=""+I,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},h,{get:function(){return v},set:function(I){v=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},h,{get:function(){return T},set:function(I){let k=i(I);if(k===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},h,{get:function(){return E},set:function(I){E=!!I,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},h,{get:function(){return S},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},h,{get:function(){return b},set:function(I){let k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");b=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},h,{get:function(){return A},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");A=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},h,{get:function(){return x},set:function(I){let k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");x=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},h,{get:function(){return R},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");R=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},h,{get:function(){return P},set:function(I){let k=s(I);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");P=k,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),or=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function xd(r){function e(i,s,n,a){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}let t=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var lr=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}};function Id(r,e,t,i){let s=i?r.split(i):[r];for(let n in s){if(typeof s[n]!="string")continue;let a=s[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l)}}var dr=new ra(0,0,""),Bi=dr.align==="middle"?"middle":"center";function jf(r,e,t){let i=r;function s(){let o=xd(r);if(o===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let d=new lr;Id(o,function(u,f){let g;switch(u){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){d.set(u,t[m].region);break}break;case"vertical":d.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),d.integer(u,g[0]),d.percent(u,g[0])&&d.set("snapToLines",!1),d.alt(u,g[0],["auto"]),g.length===2&&d.alt("lineAlign",g[1],["start",Bi,"end"]);break;case"position":g=f.split(","),d.percent(u,g[0]),g.length===2&&d.alt("positionAlign",g[1],["start",Bi,"end","line-left","line-right","auto"]);break;case"size":d.percent(u,f);break;case"align":d.alt(u,f,["start",Bi,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let c=d.get("line","auto");c==="auto"&&dr.line===-1&&(c=-1),l.line=c,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",Bi);let h=d.get("position","auto");h==="auto"&&dr.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function a(){r=r.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),a(),e.endTime=s(),a(),n(r,e)}function Ld(r){return r.replace(/<br(?: \/)?>/gi,`
31
+ `)}var cr=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new or,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let n=t.buffer,a=0;for(n=Ld(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
32
32
  `;)++a;let o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
33
- `&&++a,t.buffer=n.slice(a),o}function s(n){bd(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();let o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=i(),t.state){case"HEADER":/:/.test(n)?s(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new sa(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{qf(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
33
+ `&&++a,t.buffer=n.slice(a),o}function s(n){Id(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();let o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=i(),t.state){case"HEADER":/:/.test(n)?s(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new ra(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{jf(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
34
34
  `),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){let e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
35
35
 
36
- `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}};function si(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}var Wf=/\r\n|\n\r|\n|\r/g,Po="Missing initPTS for VTT ",Yf=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!B(t)||!B(i)||!B(s)||!B(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=60*60*1e3*n,t};function na(r,e,t){return si(r.toString())+si(e.toString())+si(t)}function jf(r,e,t,i,s,n,a){let o=new lr,l=He(new Uint8Array(r)).trim().replace(Wf,`
36
+ `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}};function si(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}var zf=/\r\n|\n\r|\n|\r/g,Do="Missing initPTS for VTT ",Xf=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!B(t)||!B(i)||!B(s)||!B(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*s,t+=60*60*1e3*n,t};function aa(r,e,t){return si(r.toString())+si(e.toString())+si(t)}function Qf(r,e,t,i,s,n,a){let o=new cr,l=He(new Uint8Array(r)).trim().replace(zf,`
37
37
  `).split(`
38
- `),d=[],c=e?Su(e.baseTime,e.timescale):0,h="00:00.000",u=0,f=0,g=!1,m,p=!0;o.oncue=function(v){let T=t[i],E=t.ccOffset,S=(u-c)/9e4;if(g){if(T!=null&&T.new&&(E=t.ccOffset=T.start),S){if(!e){m=new Error(Po+"MPEGTS");return}E=S-t.presentationOffset}}else if(e)E=-e.baseTime/e.timescale;else{m=new Error(Po+"without X-TIMESTAMP-MAP");return}let b=v.endTime-v.startTime,A=Ve((v.startTime+E-f)*9e4,s*9e4)/9e4;v.startTime=Math.max(A,0),v.endTime=Math.max(A+b,0);let x=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(x)),v.id?i&&(v.id=`hlsjscc${i}_${v.id}`):v.id=na(v.startTime,v.endTime,x),v.endTime>0&&d.push(v)},o.onparsingerror=function(v){m=v},o.onflush=function(){if(m){a(m);return}n(d)},l.forEach(v=>{if(p)if(v.startsWith("X-TIMESTAMP-MAP=")){p=!1,g=!0,v.slice(16).split(",").forEach(T=>{T.startsWith("LOCAL:")?h=T.slice(6):T.startsWith("MPEGTS:")&&(u=parseInt(T.slice(7)))});try{f=Yf(h)/1e3}catch(T){m=T}return}else v===""&&(p=!1);o.parse(v+`
39
- `)}),o.flush()}var dr="stpp.ttml.im1t",xd=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Id=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,zf={left:"start",center:"center",right:"end",start:"start",end:"end"};function _o(r,e,t,i){let s=Q(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=s.map(o=>He(o)),a=Tu(e.baseTime,1,e.timescale);try{n.forEach(o=>t(Xf(o,a)))}catch(o){i(o)}}function Xf(r,e){let s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((h,u)=>(h[u]=s.getAttribute(`ttp:${u}`)||n[u],h),{}),o=s.getAttribute("xml:space")!=="preserve",l=ko(an(s,"styling","style")),d=ko(an(s,"layout","region")),c=an(s,"body","[begin]");return[].map.call(c,h=>{let u=Ld(h,o);if(!u||!h.hasAttribute("begin"))return null;let f=ln(h.getAttribute("begin"),a),g=ln(h.getAttribute("dur"),a),m=ln(h.getAttribute("end"),a);if(f===null)throw Do(h);if(m===null){if(g===null)throw Do(h);m=f+g}let p=new sa(f-e,m-e,u);p.id=na(p.startTime,p.endTime,p.text);let v=d[h.getAttribute("region")],T=l[h.getAttribute("style")],E=Qf(v,T,l),{textAlign:S}=E;if(S){let b=zf[S];b&&(p.lineAlign=b),p.align=S}return ce(p,E),p}).filter(h=>h!==null)}function an(r,e,t){let i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function ko(r){return r.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Ld(r,e){return[].slice.call(r.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+`
40
- `:(n=i.childNodes)!=null&&n.length?Ld(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Qf(r,e,t){let i="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,l)=>{let d=on(e,i,l)||on(r,i,l)||on(s,i,l);return d&&(o[l]=d),o},{})}function on(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Do(r){return new Error(`Could not parse ttml timestamp ${r}`)}function ln(r,e){if(!r)return null;let t=Sd(r);return t===null&&(xd.test(r)?t=Zf(r,e):Id.test(r)&&(t=Jf(r,e))),t}function Zf(r,e){let t=xd.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function Jf(r,e){let t=Id.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}function ra(r,e,t,i="",s="disabled"){let n=r.ownerDocument.createElement("track");return n.kind=e,n.label=t,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=s,r.appendChild(n),n}function eg(r){return r.forced&&Kc()?"forced":r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function cr(r,e){let t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){oe.debug(`[texttrack-utils]: ${i}`);try{let s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,r.addCue(s)}catch(s){oe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(r.mode=t)}function hr(r,e,t,i){let s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){let n=ig(r.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&r.removeCue(n[a])}s==="disabled"&&(r.mode=s)}function tg(r,e){if(e<=r[0].startTime)return 0;let t=r.length-1;if(e>r[t].endTime)return-1;let i=0,s=t,n;for(;i<=s;)if(n=Math.floor((s+i)/2),e<r[n].startTime)s=n-1;else if(e>r[n].startTime&&i<t)i=n+1;else return n;return r[i].startTime-e<e-r[s].startTime?i:s}function ig(r,e,t){let i=[],s=tg(r,e);if(s>-1)for(let n=s,a=r.length;n<a;n++){let o=r[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}var ur=class extends Ei{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,i=!1;if(this.currentTrack){var s;let o=(s=this.currentTrack.trackNode)==null?void 0:s.track.mode;o==="showing"?(t=this.trackId,i=!0):o==="hidden"&&(t=this.trackId)}if(!i)for(let o=0;o<this.tracksInGroup.length;o++){var n;let l=(n=this.tracksInGroup[o].trackNode)==null?void 0:n.track.mode;if(l==="showing"){t=o;break}else t<0&&l==="hidden"&&(t=o)}if(t>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[t].trackNode)==null?void 0:a.track.mode)==="showing"}this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(i=>{i.trackNode||(i.trackNode=ra(this.media,eg(i),i.name,i.lang))});let t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;t?.mode==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){let i=t.media;this.media=i;let s=this.trackId;this.queuedDefaultTrack>-1&&(s=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(s),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let i=this.media;if(!i)return;let s=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!s&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(n=>{let a=n.trackNode;a&&(a.track.mode="hidden",a.remove(),n.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,s=this.groupIds,n=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(a=>s?.indexOf(a)===-1)){this.groupIds=i;let a=[];if(this.tracks.forEach(c=>{(c.textCodec===dr?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(c.groupId)>-1?(c.id=a.length,a.push(c)):c.trackNode&&(c.trackNode.remove(),c.trackNode=void 0))}),a.length===this.tracksInGroup.length){let c=!1;for(let h=0;h<a.length;h++)if(a[h]!==this.tracksInGroup[h]){c=!0;break}if(!c)return}a.length&&this.selectDefaultTrack&&!a.some(c=>c.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;let c=ot(o,a);if(c>-1)n=a[c];else{let h=ot(o,this.tracks);n=this.tracks[h]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,d),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){let n=t[s];if(!(i&&!n.default||!i&&!e)&&(!e||kt(n,e)))return s}if(e){for(let s=0;s<t.length;s++){let n=t[s];if(Ti(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){let n=t[s];if(Ti(e.attrs,n.attrs,["LANGUAGE"]))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===te.SUBTITLE_TRACK&&t.context.id===this.trackId&&ui(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let i=this.currentTrack;if(i&&kt(e,i))return i;let s=ot(e,this.tracksInGroup);if(s>-1){let n=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),n}else{if(i)return null;{let n=ot(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;let e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){let i=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",s=t.trackNode.track;s.mode!==i&&(s.mode=i)}})}setSubtitleTrack(e,t=!1){let i=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=i.length||!B(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let s=this.currentTrack,n=i[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),!n){s&&this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:e});return}let a=!!n.details&&!n.details.live;if(n===s&&a)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));let{id:o,groupId:l="",name:d,type:c,url:h}=n;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:d,type:c,url:h});let u=this.switchParams(n.url,s?.details,n.details);this.loadPlaylist(u)}},Wi=2,sg=100,fr=class extends ss{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(sg),this.mediaSource=t.mediaSource;let i=this.media=t.media;de(i,"playing",this.onMediaPlaying),de(i,"waiting",this.onMediaWaiting),de(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(le(i,"playing",this.onMediaPlaying),le(i,"waiting",this.onMediaWaiting),le(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;let t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var i,s;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,c=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(c){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}));return}if(!J.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}let h=J.bufferInfo(a,e,0),u=this.fragmentTracker;u&&this.hls&&Mo(h,e,u,this.hls);let f=h.nextStart||0;if(o&&u&&this.hls){let A=Co(this.hls.inFlightFragments,e),x=h.len>Wi,R=!f||A||f-e>Wi&&!u.getPartialFragment(e);if(x||R)return;this.moved=!1}let g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&u){if(!(h.len>0)&&!f)return;let x=Math.max(f,h.start||0)-e,P=!!(g!=null&&g.live)?g.targetduration*2:Wi,I=Jt(e,u);if(x>0&&(x<=P||I)){a.paused||this._trySkipBufferHole(I);return}}let m=n.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting,T=this.stalled;if(T===null)if(v>0&&p-v<m)T=this.stalled=v;else{this.stalled=p;return}let E=p-T;if(!o&&(E>=m||v&&this.moved)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-(g?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return;if(a.currentTime!==e){let A=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${A} > ${e}`);return}}let b=J.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(b,E,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){let n=J.bufferedInfo(J.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=J.timeRangesToArray(s),o=J.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=J.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,c=a[o+1].start;if((l===-1||l>o)&&c-d<1&&e-d<2){let h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${c} buffered index: ${l}`);this.warn(h.message),this.media.currentTime+=1e-6;let u=Jt(e,this.fragmentTracker);u&&"fragment"in u?u=u.fragment:u||(u=void 0);let f=J.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:u,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,i){var s,n;let{fragmentTracker:a,media:o}=this,l=(s=this.hls)==null?void 0:s.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,c=Jt(i,a);if((c||d!=null&&d.live&&i<d.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;let h=e.buffered,u=this.adjacentTraversal(e,i);(h&&h.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||u))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,s=e.nextStart;if(i&&s){let n=i.getFragAtPos(t,H.MAIN),a=i.getFragAtPos(s,H.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${fe(e)})`);this.warn(a.message),t.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:i,hls:s}=this,n=s?.config;if(!i||!t||!n)return 0;let a=i.currentTime,o=J.bufferInfo(i,a,0);Mo(o,a,t,s);let l=a<o.start?o.start:o.nextStart;if(l){let c=o.len<=n.maxBufferHole,h=o.len>0&&o.len<1&&i.readyState<3,u=l-a;if(u>0&&(c||h)){if(u>n.maxBufferHole){let v=!1;if(a===0){let T=t.getAppendedFrag(0,H.MAIN);T&&l<T.end&&(v=!0)}if(!v&&e){var d;if(!((d=s.loadLevelObj)!=null&&d.details)||Co(s.inFlightFragments,l))return 0;let E=!1,S=e.end;for(;S<l;){let b=Jt(S,t),A=b?b.duration:0;if(A>0)S+=A;else{E=!0;break}}if(E)return 0}}let{nudgeMaxRetry:f,skipBufferHolePadding:g}=n,m=++this.skipRetry>f,p=Math.max(l,a)+g;if(m||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${p}`),this.moved=!0,i.currentTime=p),!(e!=null&&e.gap)||m){let v=new Error(m?`Playhead still not moving after seeking over buffer hole from ${a} to ${p} after ${n.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${p}`),T={type:W.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:m,error:v,reason:v.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?T.part=e:T.frag=e),s.trigger(y.ERROR,T)}return p}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:s}=this,n=t?.config;if(!i||!n)return 0;let a=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){let o=a+(s+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Co(r,e){let t=wo(r.main);if(t&&t.start<=e)return t;let i=wo(r.audio);return i&&i.start<=e?i:null}function wo(r){if(!r)return null;switch(r.state){case _.IDLE:case _.STOPPED:case _.ENDED:case _.ERROR:return null}return r.frag}function Jt(r,e){return e.getAppendedFrag(r,H.MAIN)||e.getPartialFragment(r)}function Mo(r,e,t,i){let s=i.latestLevelDetails,n=Jt(e,t);if(ds(i.config)&&!r.nextStart&&s&&n&&i.interstitialsManager){let a="type"in n?n:n.fragment,o=bl(s,a.sn);o?.level===a.level&&Bl(o,i.interstitialsManager.playerQueue,e)&&(r.nextStart=o.start)}}var ng=.25;function gr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function dn(r,e,t,i,s){let n=new r(e,t,"");try{n.value=i,s&&(n.type=s)}catch{n=new r(e,t,fe(s?Y({type:s},i):i))}return n}var $i=(()=>{let r=gr();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),mr=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return ra(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=gr();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===Me.emsg&&!i||!s)continue;let d=Qo(n[o].data),c=n[o].pts,h=c+n[o].duration;h>$i&&(h=$i),h-c<=0&&(h=c+ng);for(let f=0;f<d.length;f++){let g=d[f];if(!Zo(g)){this.updateId3CueEnds(c,l);let m=dn(a,c,h,g,l);m&&this.id3Track.track.addCue(m)}}}}updateId3CueEnds(e,t){var i;let s=(i=this.id3Track)==null?void 0:i.track.cues;if(s)for(let n=s.length;n--;){let a=s[n];a.type===t&&a.startTime<e&&a.endTime===$i&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;s==="audio"?d=c=>c.type===Me.audioId3&&l:s==="video"?d=c=>c.type===Me.emsg&&o:d=c=>c.type===Me.audioId3&&l||c.type===Me.emsg&&o,hr(n.track,t,i,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=gr();if(i&&s&&!a){let{fragmentStart:m,fragmentEnd:p}=e,v=this.assetCue;v?(v.startTime=m,v.endTime=p):o&&(v=this.assetCue=dn(o,m,p,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,c=Object.keys(d),h=this.dateRangeCuesAppended;if(l&&t){var u;if((u=l.track.cues)!=null&&u.length){let m=Object.keys(h).filter(p=>c.indexOf(p)===-1);for(let p=m.length;p--;){var f;let v=m[p],T=(f=h[v])==null?void 0:f.cues;delete h[v],T&&Object.keys(T).forEach(E=>{let S=T[E];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(S)}catch{}}})}}else h=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(!(c.length===0||!B(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<c.length;m++){let p=c[m],v=d[p],T=v.startTime,E=h[p],S=E?.cues||{},b=E?.durationKnown||!1,A=$i,{duration:x,endDate:R}=v;if(R&&x!==null)A=T+x,b=!0;else if(v.endOnNext&&!b){let I=c.reduce((k,D)=>{if(D!==v.id){let F=d[D];if(F.class===v.class&&F.startDate>v.startDate&&(!k||v.startDate<k.startDate))return F}return k},null);I&&(A=I.startTime,b=!0)}let P=Object.keys(v.attr);for(let I=0;I<P.length;I++){let k=P[I];if(!Ah(k))continue;let D=S[k];if(D)b&&!(E!=null&&E.durationKnown)?D.endTime=A:Math.abs(D.startTime-T)>.01&&(D.startTime=T,D.endTime=A);else if(o){let F=v.attr[k];xh(k)&&(F=Jo(F));let $=dn(o,T,A,{key:k,data:F},Me.dateRange);$&&($.id=p,this.id3Track.track.addCue($),S[k]=$,a&&(k==="X-ASSET-LIST"||k==="X-ASSET-URL")&&$.addEventListener("enter",this.onEventCueEnter))}}h[p]={cues:S,dateRange:v,durationKnown:b}}}}};function Rd(){return self.SourceBuffer||self.WebKitSourceBuffer}function Pd(){if(!bt())return!1;let e=Rd();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function rg(){if(!Pd())return!1;let r=bt();return typeof r?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(hi(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(hi(e,"audio"))))}function ag(){var r;let e=Rd();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}var st={DISABLED:0,SWITCHING:1,SWITCHED:2},og=100,Ts=class extends mi{constructor(e,t,i){super(e,t,i,"stream-controller",H.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=st.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let s=this.media,n=s?s.currentTime:null;if(n===null||!B(n)||(this.log(`Media seeked to ${n}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(s,n,H.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${n} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(og),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),e=i),this.state=_.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=_.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case _.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e?.[t],s=i?.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=_.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=_.IDLE;break}break}case _.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===_.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let m={type:this.targetBufferType()};this.hls.trigger(y.BUFFER_EOS,m),this.state=_.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=a.details;if(!d||this.state===_.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=_.WAITING_LEVEL,this.startFragRequested=!1;return}let c=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(c>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);let u=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(u,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&ve(f)&&this.fragmentTracker.getState(f)!==ye.OK){var g;let p=((g=this.backtrackFragment)!=null?g:f).sn-d.startSN,v=d.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,u)){if(!f.gap){let p=this.audioOnly&&!this.altAudio?he.AUDIO:he.VIDEO,v=(p===he.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p)}f=this.getNextFragmentLoopLoading(f,d,o,H.MAIN,h)}f&&(this.exceedsMaxBuffer(o,h,f)||this.loadFragment(f,a,u))}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);s===ye.NOT_LOADED||s===ye.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==st.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===st.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let i=this.fragPlaying;if(i){let s=i.level;this.hls.trigger(y.FRAG_CHANGED,{frag:i,previousFrag:e}),e?.level!==s&&this.hls.trigger(y.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===st.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;de(i,"playing",this.onMediaPlaying),de(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(le(i,"playing",this.onMediaPlaying),le(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=st.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!ag(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==_.IDLE)return;let s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=_.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let d=t.levelInfo,c=this.fragCurrent;c&&(this.state===_.FRAG_LOADING||this.state===_.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let h=0;if(o.live||(i=d.details)!=null&&i.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,d.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,h),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:a}),this.state===_.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=_.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,g)=>{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let s=this.hls.liveSyncPosition,n=this.playhead,a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!l)){let c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||n<o-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s}`),this.config.liveSyncMode==="buffered"){var d;let h=J.bufferInfo(i,s,0);if(!((d=h.buffered)!=null&&d.length)){i.currentTime=s;return}if(h.start<=n){i.currentTime=s;return}let{nextStart:f}=J.bufferedInfo(h.buffered,n,0);f&&(i.currentTime=f)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let d=o.videoCodec,c=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new vs(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=g!==-1,{decryptRange:p,byteRange:v}=is(i,s,this.iframesOnly),T=new gi(i.level,i.sn,i.stats.chunkCount,v?v.end-v.start:n.byteLength,g,m,i.duration,this.iframesOnly,p),E=this.initPTS[i.cc];f.push(n,h,u,d,i,s,l.totalduration,c,T,E)}onAudioTrackSwitching(e,t){let i=this.hls,s=this.altAudio!==st.DISABLED;if(es(t.url,i))this.altAudio=st.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=st.DISABLED,this.fragmentTracker.removeAllFragments(),i.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),i.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=es(t.url,this.hls);if(i){let s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?st.SWITCHED:st.DISABLED,this.tick()}onBufferCreated(e,t){let i=t.tracks,s,n,a=!1;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){let d=i[o];d&&(this.videoBuffer=d.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:s}=t,n=i.type===H.MAIN;if(n){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===_.PARSED&&(this.state=_.IDLE);return}let l=!1;if(ve(i)&&(l=!!i.gap&&!i.tagList.some(d=>d[0]==="GAP")),this.fragBufferedComplete(i,s),l){var a;i.stats.retry++;let d=(a=this.levels)==null?void 0:a[i.level];d&&d.fragmentError++}}let o=this.media;o&&(!this._hasEnoughToStart&&J.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===te.LEVEL&&(this.state=_.IDLE);break;case L.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=_.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==he.AUDIO||!this.altAudio){let i=(t===he.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let s=this.timelineOffset;s&&i&&(i+=s);let n=this.getLevelDetails(),a=J.getBuffered(e),o=a.length?a.start(0):0,l=o-i,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{let{hls:s}=this,n=i?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=_.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(y.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:c,text:h,id3:u,initSegment:f}=s,{details:g}=d,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=_.PARSING,f){let p=f.tracks;if(p){let S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,p,S,n),i.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:p})}let v=f.initPTS,T=f.timescale,E=this.initPTS[o.cc];if(B(v)&&(!E||E.baseTime!==v||E.timescale!==T)){let S=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:T,trackId:S};let b=this.initPTS.slice(0);i.trigger(y.INIT_PTS_FOUND,{timestampOffsets:b,frag:o,id:t,initPTS:v,timescale:T,trackId:S})}}if(c&&g){m&&c.type==="audiovideo"&&this.logMuxedErr(o);let p=g.fragments[o.sn-1-g.startSN],v=o.sn===g.startSN,T=!p||o.cc>p.cc;if(s.independent!==!1){let{startPTS:E,endPTS:S,startDTS:b,endDTS:A}=c;if(l)l.elementaryStreams[c.type]={startPTS:E,endPTS:S,startDTS:b,endDTS:A};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!T&&(this.couldBacktrack=!0),c.dropped&&c.independent){let x=this.getMainFwdBufferInfo(),R=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,P=c.firstKeyFramePTS?c.firstKeyFramePTS:E;if(!v&&R<P-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(c.type,o.start,S,o.start,A,!0)}else v&&E-(g.appliedTimelineOffset||0)>Wi&&(o.gap=!0);o.setElementaryStreamInfo(c.type,E,S,b,A),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n,v||T)}else if(v||T)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:p,endPTS:v,startDTS:T,endDTS:E}=m;l&&(l.elementaryStreams[he.AUDIO]={startPTS:p,endPTS:v,startDTS:T,endDTS:E}),o.setElementaryStreamInfo(he.AUDIO,p,v,T,E),this.bufferFragmentData(m,o,l,n)}if(g&&u!=null&&u.samples.length){let p={id:t,frag:o,details:g,samples:u.samples};i.trigger(y.FRAG_PARSING_METADATA,p)}if(g&&h){let p={id:t,frag:o,details:g,samples:h.samples};i.trigger(y.FRAG_PARSING_USERDATA,p)}}logMuxedErr(e){this.warn(`${ve(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==_.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,c=Hi(n.codec,d);if(c==="mp4a"&&(c="mp4a.40.5"),this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&!Hc()&&(c="mp4a.40.5")}c&&c.indexOf("mp4a.40.5")!==-1&&qc()&&n.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),d&&d!==c&&this.log(`Swapping manifest audio codec "${d}" for "${c}"`),n.levelCodec=c,n.id=H.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${c||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=H.MAIN;let d=a.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(y.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let h=t[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:d,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,H.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=_.IDLE}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return B(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(B(t)){let i=this.getLevelDetails(),s=this.currentFrag||(i?qt(null,i.fragments,t):null);if(s){let n=s.programDateTime;if(n!==null){let a=n+(t-s.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Ss=class extends Ts{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{let t=this.media;t!=null&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:i}=t,s=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=s,this.startPosition=e,this.state){case _.STOPPED:case _.ENDED:case _.ERROR:this.state=_.IDLE}this.state===_.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,t]):this.nextOp=[s,t],this.hls.off(y.BUFFERED_TO_END,this.onBufferedToEnd);let n=this.media;i&&n&&this.seekTo(s)&&(this.currentOp=[s,t],this.nextOp=void 0,this.flushPipeline(s,!0))}seekTo(e){let t=this.media;if(t){var i;let s=(i=this.getLevelDetails())==null?void 0:i.edge,n=s!==void 0?s:t.duration;if(e>=n&&(e=n-.01),J.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let i=this.cached;i.push(e),this.cachedSize+=t.buffer.byteLength;let s=this.hls.config.iframeCacheLimit;for(;this.cachedSize>s&&i.length>1;){let n=i.shift();if(n.data)this.cachedSize-=n.data.byteLength,n.data=void 0;else{this.cached=i.filter(a=>!!a.data),this.cachedSize=i.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:i,payload:s}=e;this.cacheFragmentData&&!i&&s!=null&&s.byteLength&&!t.data&&ve(t)&&this.cacheSet(t,new Uint8Array(s.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);if((s===ye.NOT_LOADED||s===ye.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,i)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let i=e.decryptdata;return i?.keyFormat!=="identity"||!!i.key}replayCachedFragment(e){let t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;let i=e.stats=new ri;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=t.byteLength,i.chunkCount=1,this.state=_.FRAG_LOADING;let s={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(s),this.hls.trigger(y.FRAG_LOADED,s),this._handleFragmentLoadComplete(s)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:i,nextOp:s}=this;this.currentOp=this.nextOp=void 0,this.state=_.STOPPED,i!=null&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!s),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?ls(J.getBuffered(this.media)):"none"}`)),s&&this.loadMediaAt.apply(this,s)}flushPipeline(e,t){if(t){let i=this.media;if(i){let s=J.bufferInfo(i,e,0),n=s.len?s.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,H.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(y.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(y.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){let e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,i){let s=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,i||s||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let i=t.duration;return{len:i,start:e,end:e+i,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,H.MAIN);return!!(t!=null&&t.endList)}},pr=class extends Ss{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;let i=(t=this._img)==null?void 0:t.src;i&&self.URL.revokeObjectURL(i),this._img=e}loadMediaAt(e){if(!this.hls)return;let t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case _.STOPPED:case _.ENDED:case _.ERROR:this.state=_.IDLE}if(this.state===_.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===_.IDLE){let i=this.getBufferedAt(e);i&&(this.fragCurrent=i,this.updateImage(i,null))}}else{let i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}updateImage(e,t,i){let s=e.data;s||this.fragmentTracker.removeFragment(e);let n=this._img;if(n&&s){let a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,n.onload=()=>{if(!this.hls)return;let c=this.hls.levels[e.level];c!=null&&c.fragmentError&&(c.fragmentError=0,e.stats.retry=0);let h=self.performance.now(),u=t?t.stats:e.stats;u.buffering.end=e.stats.buffering.end=h,this.hls.trigger(y.FRAG_BUFFERED,{frag:e,part:t,stats:u,id:e.type,chunkMeta:i})},n.onerror=()=>{this.handleError("Image decode error",e,t,i)};let l=n.src;l&&self.URL.revokeObjectURL(l);let d=new Blob([s],{type:"image/jpeg"});n.src=self.URL.createObjectURL(d)}else this.state=_.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,i,s){if(!this.hls)return;let n=new Error(e);this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:s,frag:t,part:i,fatal:!1,error:n,err:n})}_bufferInitSegment(){}bufferFragmentData(e,t,i,s){super.bufferFragmentData(e,t,i,s,!0);let n=Q(new Uint8Array(e.data1),["mdat"]);if(n.length===0){this.handleError("Could not find I-Frame mdat",t,i,s);return}let a=t;this.cacheSet(a,n[0]),this.updateImage(a,i,s)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;let t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){let i=this.getAppendedFrag(t);if(i&&!Zt(i,this.fragPlaying))return this.fragPlaying=i,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},lg=10,dg="Image I-Frame player does not accept HTMLMediaElements",Oo={seekOnAppend:!0},Ui,cn,yr=class extends Oe{constructor(e,t){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Ui||(Ui=cg(t)),cn||(cn=hg(Ui)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(y.MANIFEST_LOADING,this.clearAsset,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.clearAsset,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var i;let s=(i=this.hls)==null?void 0:i.pathwayPriority;t.length&&s&&this.iframeInstances.forEach(n=>{n.pathwayPriority=s})}onInitPtsFound(e,{id:t,timestampOffsets:i}){t===H.MAIN&&(this.initPTS=i)}onFragBuffered(e,t){var i;let s=this.hls;s&&s.hasEnoughToStart&&(((i=s.mainForwardBufferInfo)==null?void 0:i.len)||0)>lg&&this.iframeInstances.forEach(n=>{if(!n.loadingEnabled){var a;n.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(Ui,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;let i=(t=this.hls)==null?void 0:t.iframeVariants.filter(s=>s.imageCodec);return this.createInstance(cn,i,e,"image-")}createInstance(e,t,i,s){let{hls:n}=this;if(!n)return null;let{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:d,loadLevel:c,bandwidthEstimate:h,sessionId:u}=n,{stats:f,variableList:g}=this;if(!(t!=null&&t.length)||!f||!a)return null;let m=`${s||""}iframe-player-${this.instanceCounter++}`,p=n.levels,v=d||p[c],T=El(v,o.videoPreference),E=v?.pathwayId||".",S=Y(Y({},o),{},{loggerId:m,primarySessionId:u,videoPreference:T,abrEwmaDefaultEstimate:h,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),b=new e(S,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(A=>!A.url),this.iframeInstances.push(b),b.trigger(y.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:E},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),b}};function cg(r){return class extends r{constructor(t,i,s,n){t.streamController||(t.streamController=Ss),super(t),this._url=i,this.streamController.setInitPts(s),this.streamController.initDetails=n}loadSource(){}loadMediaAt(t,i=Oo){if(t<0)return;let s=Y(Y({},Oo),i);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,s)}}}function hg(r){return class extends r{constructor(t,i,s,n){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=pr),t.capLevelController=void 0,t.bufferController=void 0,super(t,i,s,n)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(dg)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}var St=.025,bs=function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r}({});function ug(r,e,t){return`${r.identifier}-${t+1}-${si(e)}`}var vr=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return Fo(t,e)?Yi(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=Yi(t,e);return t-i<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=B(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return Fo(t,e)?Yi(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<St))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?bs.Range:bs.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return fg(this)}};function Yi(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<St)?e.start:e.start+e.duration}function Fo(r,e){return e>r.start-St&&e<r.start+r.duration+St}function _d(r,e,t){let i=new self.URL(r,t);return i.protocol!=="data:"&&Tt(i,"_HLS_primary_id",e),i}function hn(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function fg(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function $t(r){let e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Er=class{constructor(e,t,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=i,this.assetItem=s;let a=()=>{this.hasDetails=!0};n.once(y.LEVEL_LOADED,a),n.once(y.AUDIO_TRACK_LOADED,a),n.once(y.SUBTITLE_TRACK_LOADED,a),n.on(y.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(y.BUFFER_APPENDED,()=>{let c=this.bufferedEnd;this.reachedPlayout(c)&&(this._bufferedEosTime=c,n.trigger(y.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=_d(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var i;if(!this.appendInPlace)return!1;if((i=this.hls)!=null&&i.bufferedToEnd)return!0;if(!e)return!1;let s=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=J.bufferInfo(e,n,.02);return this.getAssetTime(a.end)>=s-.02}reachedPlayout(e){let i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=J.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,i){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,i){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${$t(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},un=.033,Tr=class extends Oe{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let s=this.items;if(s)for(s[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=s[i])!=null&&n.event;){var n;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let s=0;s<i.length;s++){let n=i[s];t&&t!=="primary"&&(n=n[t]);let a=n.start,o=i[s].event,l=o!=null&&o.cue.pre?o.duration:n.end;if(e===a||e>a&&e<l)return s}return-1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){let n=i[s].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return s}return-1}findEventIndex(e){let t=this.items;if(t)for(let s=t.length;s--;){var i;if(((i=t[s].event)==null?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){let i=e.assetList,s=i.length;if(s>1)for(let n=0;n<s;n++){let a=i[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===s-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let i=t.assetList,s=i[i.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t,i=0){let s=e.main.details,{dateRanges:n}=s,a=this.events,o=this.parseDateRanges(n,{url:s.url},t),l=Object.keys(n),d=a?a.filter(c=>l.indexOf(c.identifier)===-1):[];o.length&&o.sort((c,h)=>{let u=c.cue.pre,f=c.cue.post,g=h.cue.pre,m=h.cue.post;if(u&&!g)return-1;if(g&&!u||f&&!m)return 1;if(m&&!f)return-1;if(!u&&!g&&!f&&!m){let p=c.startTime,v=h.startTime;if(p!==v)return p-v}return c.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=o,d.forEach(c=>{this.removeEvent(c)}),this.updateSchedule(e,d,i)}updateSchedule(e,t=[],i=0,s=!1){let n=this.events||[];if(n.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(n,e,i);(s||t.length||a?.length!==o.length||o.some((d,c)=>Math.abs(d.playout.start-a[c].playout.start)>.005||Math.abs(d.playout.end-a[c].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,i){let s=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],l=e[o];if(l.isInterstitial){let d=this.eventMap[o];d?d.setDateRange(l):(d=new vr(l,t),this.eventMap[o]=d,i===!1&&(d.appendInPlace=i)),s.push(d)}}return s}parseSchedule(e,t,i=0){let s=[],n=t.main.details,a=n.live?1/0:n.edge,o=0;if(e=e.filter(d=>!d.error&&!(d.cue.once&&d.hasPlayed)),e.length){this.resolveOffsets(e,t);let d=0,c=0;if(e.forEach((h,u)=>{let f=h.cue.pre,g=h.cue.post,m=e[u-1]||null,p=h.appendInPlace,v=g?a:h.startOffset,T=h.duration,E=h.timelineOccupancy===bs.Range?T:0,S=f&&n.live?i+(h.resumeOffset||0):0,b=S||h.resumptionOffset,A=m?.startTime===v,x=v+h.cumulativeDuration,R=p?x+T:v+b;if(f||!g&&v<=0){let I=c;c+=E,h.timelineStart=x;let k=o;o+=T,s.push({event:h,start:x,end:R,playout:{start:k,end:o},integrated:{start:I,end:c}})}else if(v<=a){if(!A){let D=v-d;if(D>un){let F=d,G=c;c+=D;let $=o;o+=D;let C={previousEvent:e[u-1]||null,nextEvent:h,start:F,end:F+D,playout:{start:$,end:o},integrated:{start:G,end:c}};s.push(C)}else D>0&&m&&(m.cumulativeDuration+=D,s[s.length-1].end=v)}g&&(R=x),h.timelineStart=x;let I=c;c+=E;let k=o;o+=T,s.push({event:h,start:x,end:R,playout:{start:k,end:o},integrated:{start:I,end:c}})}else return;let P=S||h.resumeTime;g||P>a?d=a:!f&&R&&h.appendInPlaceStarted&&P-R>un?d=R:d=P}),d<a){var l;let h=d,u=c,f=a-d;c+=f;let g=o;o+=f,s.push({previousEvent:((l=s[s.length-1])==null?void 0:l.event)||null,nextEvent:null,start:d,end:h+f,playout:{start:g,end:o},integrated:{start:u,end:c}})}this.setDurations(a,o,c)}else s.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return s}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){let i=t.main.details,s=i.live?1/0:i.edge,n=0,a=-1;e.forEach((o,l)=>{let d=o.cue.pre,c=o.cue.post,h=d?0:c?s:o.startTime;this.updateAssetDurations(o),a===h?o.cumulativeDuration=n:(n=0,a=h),!c&&o.snapOptions.in&&(o.resumeAnchor=qt(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<un&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=B(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>St?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),!1;let d=qt(null,o.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let c=a==="audio"?.175:0;return Math.abs(d.start-i)<St+c||Math.abs(d.end-i)<St+c?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,s=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,s||(s=o.duration===null),n||(n=!!o.error);let d=o.error?0:o.duration||0;i+=d}s&&!n?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Ue(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}var Sr=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let i=e.assetListUrl,s;try{s=_d(i,this.hls.sessionId,e.baseUrl)}catch(u){let f=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,u,i);this.hls.trigger(y.ERROR,f);return}t&&s.protocol!=="data:"&&Tt(s,"_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={type:te.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},d=n.interstitialAssetListLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,m)=>{let p=u.data,v=p?.ASSETS;if(!Array.isArray(v)){let T=this.assignAssetListError(e,L.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,m);this.hls.trigger(y.ERROR,T);return}e.assetListResponse=p,this.hls.trigger(y.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:m})},onError:(u,f,g,m)=>{let p=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${f.url})`),f.url,m,g);this.hls.trigger(y.ERROR,p)},onTimeout:(u,f,g)=>{let m=this.assignAssetListError(e,L.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,u,g);this.hls.trigger(y.ERROR,m)}};return o.load(l,c,h),this.hls.trigger(y.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,s,n,a){return e.error=i,{type:W.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:a,stats:n}}};function No(r){var e;r==null||(e=r.play())==null||e.catch(()=>{})}function Rt(r,e){return`[${r}] Advancing timeline position to ${e}`}var br=class extends Oe{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;let s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;let a=s<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;let f=this.findItemIndex(o),g=this.schedule.findItemIndexAtTime(i);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&g>f){let m=this.schedule.findJumpRestrictedIndex(f+1,g);if(m>f){this.setSchedulePosition(m);return}}this.setSchedulePosition(g);return}let d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f))}return}let c=d.timelineStart,h=d.duration||0;if(a&&i<c||i>=c+h){var u;(u=o.event)!=null&&u.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d)}},this.onTimeupdate=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;let s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;let o=this.findItemIndex(s);this.setSchedulePosition(o+1)}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n)},this.onScheduleUpdate=(i,s)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,c=i.map(m=>m.identifier),h=!!(o.length||c.length);(h||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
41
- Schedule: ${l.map(m=>Ue(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`);let u=null,f=null;a&&(u=this.updateItem(a,this.timelinePos),this.itemsMatch(a,u)?this.playingItem=u:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);let g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),i.forEach(m=>{m.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){let p=m.assetItem.timelineStart,v=m.timelineOffset-p;if(v)try{m.timelineOffset=p}catch(T){Math.abs(v)>St&&this.warn(`${T} ("${m.assetId}" ${m.timelineOffset}->${p})`)}}}),h||s){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:c}),this.isInterstitial(a)&&c.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(u,a),g&&f!==u&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Sr(e),this.schedule=new Tr(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){le(e,"play",this.onPlay),le(e,"pause",this.onPause),le(e,"seeking",this.onSeeking),le(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;de(i,"seeking",this.onSeeking),de(i,"timeupdate",this.onTimeupdate),de(i,"play",this.onPlay),de(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();let n=this.findItemIndex(i);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=h=>h&&e.getAssetPlayer(h.identifier),s=(h,u,f,g,m)=>{if(h){let p=h[u].start,v=h.event;if(v){if(u==="playout"||v.timelineOccupancy!==bs.Point){let T=i(f);T?.interstitial===v&&(p+=T.assetItem.startOffset+T[m])}}else{let T=g==="bufferedPos"?a():e[g];p+=T-h.start}return p}return 0},n=(h,u)=>{var f;if(h!==0&&u!=="primary"&&(f=e.schedule)!=null&&f.length){var g;let m=e.schedule.findItemIndexAtTime(h),p=(g=e.schedule.items)==null?void 0:g[m];if(p){let v=p[u].start-p.start;return h+v}}return h},a=()=>{let h=e.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var u,f;return(u=e.primaryDetails)!=null&&u.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[h])||0},l=(h,u)=>{var f,g;let m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${u}"`);let p=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(h,u),T=(g=e.schedule.items)==null?void 0:g[v],E=e.getBufferingPlayer(),S=E?.interstitial,b=S?.appendInPlace,A=p&&e.itemsMatch(p,T);if(p&&(b||A)){let x=i(e.playingAsset),R=x?.media||e.primaryMedia;if(R){let P=u==="primary"?R.currentTime:s(p,u,e.playingAsset,"timelinePos","currentTime"),I=h-P,k=(b?P:R.currentTime)+I;if(k>=0&&(!x||b||k<=x.duration)){R.currentTime=k;return}}}if(T){let x=h;if(u!=="primary"){let P=T[u].start,I=h-P;x=T.start+I}let R=!e.isInterstitial(T);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(R||T.event.appendInPlace)){let P=e.media||(b?E?.media:null);P&&(P.currentTime=x)}else if(p){let P=e.findItemIndex(p);if(v>P){let k=e.schedule.findJumpRestrictedIndex(P+1,v);if(k>P){e.setSchedulePosition(k);return}}let I=0;if(R)e.timelinePos=x,e.checkBuffer();else{let k=T.event.assetList,D=h-(T[u]||T).start;for(let F=k.length;F--;){let G=k[F];if(G.duration&&D>=G.startOffset&&D<G.startOffset+G.duration){I=F;break}}}e.setSchedulePosition(v,I)}}},d=()=>{let h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;let u=t();return e.isInterstitial(u)?u:null},c={get bufferedEnd(){let h=t(),u=e.bufferingItem;if(u&&u===h){var f;return s(u,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-u.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let h=d(),u=e.effectivePlayingItem;return u&&u===h?s(u,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(h){let u=d(),f=e.effectivePlayingItem;f&&f===u&&l(h+f.playout.start,"playout")},get duration(){let h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;let u=(h=d())==null?void 0:h.event.assetList;return u?u.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var h;let u=(h=d())==null?void 0:h.event;return u&&e.effectivePlayingAsset?u.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var h;return((h=e.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=e.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return d()?c:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let h=t();return e.findItemIndex(h)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let h=e.effectivePlayingItem;return e.findItemIndex(h)},primary:{get bufferedEnd(){return a()},get currentTime(){let h=e.timelinePos;return h>0?h:0},set currentTime(h){l(h,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){l(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){return n(e.seekableStart,"integrated")}},skip:()=>{let h=e.effectivePlayingItem,u=h?.event;if(u&&!u.restrictions.skip){let f=e.findItemIndex(h);if(u.appendInPlace){let g=h.playout.start+h.event.duration;l(g+.001,"playout")}else e.advanceAfterAssetEnded(u,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);let n=(t=s)==null?void 0:t.currentTime;if(!(n===void 0||!B(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${fe(n)}`),this.detachedData=n}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource,c;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),c="Primary";else{let g=this.getBufferingPlayer();g?(n=g.transferMedia(),this.detachedData=n,c=`${g}`):d?c="detached MediaSource":c="detached media"}if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${fe(n)}`);else if(!this.detachedData||a.media===t){let g=this.playerQueue;g.length>1&&g.forEach(m=>{if(o&&m.interstitial.appendInPlace!==l){let p=m.interstitial;this.clearInterstitial(m.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${p}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let h=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.readyState)!=="closed";if(this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${c} (media.currentTime: ${t.currentTime})`),!h&&!o){e.attachMedia(t);return}let u=h&&n?Y({},n):{media:t},f=this.schedule;if(f&&o){let g=e.assetId===f.assetIdAtEnd;u.overrides={duration:f.duration,endOfStream:g||e.appendInPlace===!1}}if(!h&&l){let g=e,m=g.assetItem.timelineStart;if(m){let p=g.hls,v=Math.max(this.timelinePos-m,Number.EPSILON);p.startPosition!==v&&(this.log(`Set ${g} startPosition: ${v}`),p.config.startPosition=v,p.loadingEnabled&&p.startLoad(v))}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events,i=this.hls;if(!t||this.playbackDisabled||!this.media||!i)return;this.bufferedPos===-1&&(this.bufferedPos=0);let s=this.timelinePos,n=this.effectivePlayingItem;if(s===-1){if(!i.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}let a=i.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Rt("checkStart (preroll)",a));let o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(Rt("checkStart",a));let o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else i.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Rt("checkStart (playing item)",n.start));let a=e.findItemIndex(n);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){let i=e.event,s=i.findAssetIndex(t),n=hn(i,s);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=this.getNextItemIndex(e,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!B(e.resumeOffset)&&this.hls){let i=this.getLiveStartPos();if(t){let s=this.getBufferingPlayer(),n=s!=null&&s.interstitial.cue.pre?s.remaining:0;return i+n}return i}}getNextItemIndex(e,t){if(this.schedule){let i=this.livePrerollResumption(e.event,t);if(i!==void 0)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,i){let s=hn(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){let n=this.schedule.items;if(n){let a=n[t],o=a.event?this.getNextItemIndex(a):t+1,l=n.length;if(o>=l){this.setSchedulePosition(-1);return}let d=e.resumeTime;this.timelinePos<d&&(this.log(Rt("advanceAfterAssetEnded",d)),this.timelinePos=d,e.appendInPlace&&!n[o].event&&this.hls.startLoad(d+.01),this.checkBuffer(this.bufferedPos<d)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){let n=e.assetList[s];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let s=t.parentIdentifier,n=i.getEvent(s);if(n){let a=i.findEventIndex(s),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var i;let s=(i=this.schedule)==null?void 0:i.items;if(!s||this.playbackDisabled)return;let n=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Ue(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let h=a.event,u=this.playingAsset,f=u?.identifier,g=f?this.getAssetPlayer(f):null;if(g&&f&&(!this.eventItemsMatch(a,n)||t!==void 0&&f!==h.assetList[t].identifier)){var l;let m=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${h.assetList.length} ${$t(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:m,event:h,schedule:s.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(f,n),g.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Ue(a)}`),h.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:h,schedule:s.slice(0),scheduleIndex:e}),h.cue.once&&this.hls)){var d;this.updateSchedule();let m=(d=this.schedule)==null?void 0:d.items;if(n&&m){let p=this.findItemIndex(n),v=this.livePrerollResumption(h);if(v!==void 0){let T=v,E=this.getNextItemIndex(a);if(!this.isInterstitial(s[E])){var c;let S=(c=this.primaryDetails)==null?void 0:c.fragments;if(h.snapOptions.in&&S){let b=qt(null,S,v);b&&(T=Math.min(Math.max(s[E].start,Yi(T,b)),s[E].end))}}if(this.log(Rt("live join (preroll)",T)),this.timelinePos=T,E!==p&&(E||E===0)){this.advanceSchedule(E,m,void 0,a,o);return}}this.advanceSchedule(p,m,t,a,o)}return}}this.advanceSchedule(e,s,t,a,o)}advanceSchedule(e,t,i,s,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(c=>{let h=c.interstitial,u=a.findEventIndex(h.identifier);(u<e||u>e+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let c=o.event;if(i===void 0){i=c.cue.pre?0:a.findAssetIndex(c,this.timelinePos);let g=hn(c,i-1);if(c.isAssetPastPlayoutLimit(g)||c.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(c,e,i);return}i=g}let h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let u=this.preloadAssets(c,i);if(this.eventItemsMatch(o,h||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ue(o)} ${c.appendInPlace?"append in place":""}`),c.hasPlayed=!1,this.hls.trigger(y.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${c}`);return}if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${c}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=c.assetList[i];if(!f){this.advanceAfterAssetEnded(c,e,i||0);return}if(u||(u=this.getAssetPlayer(f.identifier)),u===null||u.destroyed){let g=c.assetList.length;this.warn(`asset ${i+1}/${g} player destroyed ${c}`),u=this.createAssetPlayer(c,f,i),u.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(u,i,t,e,l),this.shouldPlay&&No(u.media)}else o?(this.resumePrimary(o,e,s),this.shouldPlay&&No(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var s,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Ue(e)}`);let a=this.timelinePos;if((s=this.detachedData)!=null&&s.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Rt("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!i)return;let o=(n=this.schedule)==null?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ue(e)}`),this.hls.trigger(y.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,i){let s=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;let n=this.endedItem||this.playingItem,a=n!=null&&n.event?this.livePrerollResumption(n.event,i):void 0;if(a!==void 0)return a;let o=this.primaryDetails;if(o){let{fragmentStart:l,edge:d}=o;if(s<l||s>d&&!i){let c=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${s} [${l}-${d}]) snapping to liveSync ${c}`),c||l}}}return this.log(`primary resumption itemStart: ${s}`),s}getLiveStartPos(){var e;let t=this.hls.startPosition,i=this.hls.liveSyncPosition||0,s=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||i&&i-t<s?i||0:t}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:J.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let s=this.primaryMedia;if(!s)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Rt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){let i=this.hls,{loadingEnabled:s,bufferingEnabled:n,startPosition:a}=i,o=i.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${s} bufferingEnabled: ${n}`),!t&&o||!s||Math.abs(a-e)>.1){let l=this.primaryDetails;if(l!=null&&l.live&&e+.5>=l.edge){let d=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${d?Ue(d):null}`),i.pauseBuffering(),this.bufferPastEdge=!0;return}i.startLoad(e,t)}else n||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(y.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(y.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let s=Y(Y({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s;let n=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,n===-1?0:n),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){let o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+.5<o.edge){this.bufferPastEdge=!1;let d=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${d?Ue(d):null}`),d?.end===1/0){let h=this.playingItem,u=this.isInterstitial(h)&&h.event.appendInPlace;this.hls.startLoad(Math.max(l,d.start),u)}else{let h=this.getBufferingPlayer();h&&h.bufferedInPlaceToEnd(this.primaryMedia,h.currentTime)&&h.hls&&h.hls.trigger(y.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=Y(Y({},this.altSelection),{},{audio:i});return}let n=Y(Y({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=Y(Y({},this.altSelection),{},{subtitles:i});return}let n=Y(Y({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){let i=ka(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=ka(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){let s=t[i];if(s.cue.post){let n=this.getEventItem(s.identifier);n&&this.eventItemsMatch(n,this.bufferingItem)&&this.bufferedToItem(n,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;let s=(i=this.schedule)==null?void 0:i.items;if(e&&s){let n=this.findItemIndex(e,t);return s[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});let i=e.end+.25,s=J.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Ue(e)} (was ${Ue(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;let i=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(i)&&i.event.identifier===e)return i}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,i;let s=this.mediaSelection;if(!s)return;let n=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(i=this.schedule)==null||i.updateSchedule(s,[],n,e)}checkBuffer(e){var t;let i=(t=this.schedule)==null?void 0:t.items;if(!i)return;let s=J.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){let s=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;let c=this.findItemIndex(n),h=Math.min(c+1,t.length-1),u=t[h];if((l===-1&&n&&e>=n.end||(d=u.event)!=null&&d.appendInPlace&&e+.01>=u.start)&&(l=h),this.isInterstitial(n)){let f=n.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>c&&l>o)this.bufferedToItem(u);else{let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&u.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(u)&&this.preloadAssets(u.event,0)}}else i&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(s=>{let n=this.getAssetPlayer(s.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:s,events:n}=i;if(!s||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ue(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((c,h)=>{let u=this.getAssetPlayer(c.identifier);u&&(h===d&&u.loadSource(),u.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(y.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;let s=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(s,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(n,e,!0):this.startLoadingPrimaryAt(n);else{let o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(n,l)}}}}bufferedToEvent(e,t){let i=e.event,s=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(s||!n){let a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let i=e.assetUrl,s=e.assetList.length,n=s===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart,d=this.playingItem,c=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let h,u=0;if((!c||c.interstitial.cue.pre)&&this.primaryLive&&(u=this.getLiveStartPos(),c&&(u+=c.remaining)),u&&!(e.cue.pre||e.cue.post)){let g=u-l;g>0&&(h=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${u?` live-start: ${u} start-offset: ${h} (timeline-start: ${l})`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);let f=this.assetListLoader.loadAssetList(e,h);f&&(e.assetListLoader=f)}else if(!a&&s){for(let d=t;d<s;d++){let c=e.assetList[d],h=this.getAssetPlayerQueueIndex(c.identifier);(h===-1||this.playerQueue[h].destroyed)&&!c.error&&this.createAssetPlayer(e,c,d)}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let i=this.primaryDetails;if(i&&e>=i.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,s,n,a){let o={parentIdentifier:e.identifier,identifier:ug(e,a,t),duration:n,startOffset:i,timelineStart:s,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){let s=this.hls,n=s.userConfig,a=s.loadLevelObj||s.levels[s.currentLevel],o=El(a,n.videoPreference),l=s.audioTracks[s.audioTrack],d=s.subtitleTracks[s.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){let S=this.timelinePos-t.timelineStart;if(S>=0){let b=t.duration;b&&S<b&&(c=S)}}let h=t.identifier,u=Y(Y({},n),{},{maxMaxBufferLength:Math.min(15,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));let f=u.cmcd;f!=null&&f.sessionId&&f.contentId&&(u.cmcd=ce({},f,{contentId:si(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);let g=new Er(this.HlsPlayerClass,u,e,t);this.playerQueue.push(g),e.assetList[i]=t;let m=!0,p=S=>{if(S.live){let x=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:!0,type:W.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:x},P=this.findEventIndex(e.identifier);this.handleAssetItemError(R,e,P,i,x.message);return}let b=S.edge-S.fragmentStart,A=t.duration;(m||A===null||b>A)&&(m=!1,this.log(`Interstitial asset "${h}" duration change ${A} > ${b}`),t.duration=b,this.updateSchedule())};g.on(y.LEVEL_UPDATED,(S,{details:b})=>p(b)),g.on(y.LEVEL_PTS_UPDATED,(S,{details:b})=>p(b)),g.on(y.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(S,b)=>{let A=this.getAssetPlayer(h);if(A&&b.tracks){A.off(y.BUFFER_CODECS,v),A.tracks=b.tracks;let x=this.primaryMedia;this.bufferingAsset===A.assetItem&&x&&!A.media&&this.bufferAssetPlayer(A,x)}};g.on(y.BUFFER_CODECS,v);let T=()=>{let S=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${S}`),!S||!this.schedule)return;let b=this.getEventItem(e.identifier);b&&this.advanceAssetBuffering(b,S.assetItem)};g.on(y.BUFFERED_TO_END,T);let E=S=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;let A=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,A,S)};return g.once(y.MEDIA_ENDED,E(i)),g.once(y.PLAYOUT_LIMIT_REACHED,E(1/0)),g.on(y.ERROR,(S,b)=>{if(!this.schedule)return;let A=this.getAssetPlayer(h);if(b.details===L.BUFFER_STALLED_ERROR){if(A!=null&&A.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(b.details===L.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(b,e,this.findEventIndex(e.identifier),i,`Asset player error ${b.error} ${e}`)}),g.on(y.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;let b=new Error(`Asset player destroyed unexpectedly ${h}`),A={fatal:!0,type:W.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(A,e,this.findEventIndex(e.identifier),i,b.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${$t(t)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(i!==-1){let s=this.playerQueue[i];this.log(`clear ${s} toSegment: ${t&&Ue(t)}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,n){let{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=o,c?.identifier!==l&&(c&&(this.clearAssetPlayer(c.identifier,i[s]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${$t(o)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i;if(!this.schedule)return;let{interstitial:s,assetItem:n}=e,a=this.getEventItem(s.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=n,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,n);return}let o=this.getBufferingPlayer();if(o===e)return;let l=s.appendInPlace;if(l&&o?.interstitial.appendInPlace===!1)return;let d=o?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(l&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!Yo(d,e.tracks)){let c=new Error(`Asset ${$t(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),h={fatal:!0,type:W.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:c},u=s.findAssetIndex(n);this.handleAssetItemError(h,s,this.findEventIndex(s.identifier),u,c.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let s=i.currentTime,n=t.findAssetIndex(e,s),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||s-a.timelineStart,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${s})`),l&&(d/i.playbackRate<.5||o.bufferedInPlaceToEnd(i,o.currentTime))&&o.hls){let c=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,c,n)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let i=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(i),t.currentTime=e):this.log(`Cannot ${i}`)}}handleAssetItemError(e,t,i,s,n){if(e.details===L.BUFFER_STALLED_ERROR)return;let a=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&$t(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,c=this.schedule.items,h=ce({},e,{fatal:!1,errorAction:ti(!0),asset:a,assetListIndex:s,event:t,schedule:c,scheduleIndex:i,player:d});if(this.hls.trigger(y.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;let u=this.playingAsset,f=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(m=>!m.error))t.error=g;else for(let m=s;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):u?.identifier===o?this.advanceAfterAssetEnded(t,i,s):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,s=this.playingItem,n=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Ue(i)} startPosition: ${a} seekableStart: ${n} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,n);let d=this.updateItem(i,o);this.itemsMatch(i,d)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||!this.isInterstitial(s))return;let l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var i,s;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;let l=n.timelineStart,d=n.duration,c=0;o.forEach((g,m)=>{let p=parseFloat(g.DURATION);this.createAsset(n,m,c,l+c,p,g.URI),c+=p}),n.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${d}) ${n}`);let h=this.waitingItem,u=h?.event.identifier===a;this.updateSchedule();let f=(s=this.bufferingItem)==null?void 0:s.event;if(u){let g=this.findEventIndex(a),m=this.getEventItem(a);if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(m)}this.setSchedulePosition(g)}else if(f?.identifier===a){let g=n.assetList[0];if(g){let m=this.getAssetPlayer(g.identifier);if(f.appendInPlace){let p=this.primaryMedia;m&&p&&this.bufferAssetPlayer(m,p)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case L.ASSET_LIST_PARSING_ERROR:case L.ASSET_LIST_LOAD_ERROR:case L.ASSET_LIST_LOAD_TIMEOUT:{let i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case L.BUFFER_STALLED_ERROR:{let i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}let s=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${s?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Ar=class{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;let{media:i}=this,s=this.levelDetails;if(!i||!s||!this.hls)return;this.currentTime=i.currentTime;let n=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;let{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=n;if(!o||l===1||!s.live)return;let d=this.targetLatency;if(d===null)return;let c=a-d,h=Math.min(this.maxLatency,d+s.targetduration),u=c<h,f=ds(n)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(u&&c>.05&&this.forwardBufferLength>1&&!f){let g=Math.min(2,Math.max(1,l)),m=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,p=Math.min(g,Math.max(1,m));this.changeMediaPlaybackRate(i,p)}else i.playbackRate!==1&&i.playbackRate!==0&&this.changeMediaPlaybackRate(i,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;let t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;let i=this.levelDetails;return i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:i,partHoldBack:s,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,d=this.hls.userConfig,c=l&&s||i;(this._targetLatencyUpdated||d.liveSyncDuration||d.liveSyncDurationCount||c===0)&&(c=a!==void 0?a:o*n);let h=n;return c+Math.min(this.stallCount*t.liveSyncOnStallIncrease,h)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;let i=this.levelDetails;if(i===null)return null;let s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null||!this.hls)return 0;let t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.ERROR,this.onError,this),e.on(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.ERROR,this.onError,this),e.off(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var i;let s=this.hls,n=this.media||t.event.appendInPlace&&(s==null||(i=s.interstitialsManager)==null?void 0:i.playerQueue.reduce((a,o)=>a||o.media,null));s&&n&&n.playbackRate>1&&n.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)}onError(e,t){var i;t.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Bo=500,xr=class extends mi{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",H.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=_.IDLE,this.setInterval(Bo),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:i,part:s,success:n}=t;if(!n)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o,l=(s||i).start;for(let c=0;c<a.length;c++)if(l>=a[c].start&&l<=a[c].end){o=a[c];break}let d=l+(s||i).duration;if(o?o.end=d:(o={start:l,end:d},a.push(o)),!s||d>=i.end){let c=this.fragmentTracker.fragBuffered(i);s&&c&&(c.range.subs={time:[{startPTS:i.start,endPTS:d}],partial:!0}),ve(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){let n=s-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,n,H.SUBTITLE)}}onError(e,t){let i=t.frag;i?.type===H.SUBTITLE&&(t.details===L.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==_.STOPPED&&(this.state=_.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Jl(this.levels,t)){this.levels=t.map(i=>new Ct(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let s=new Ct(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,H.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let s=this.levels[this.currentTrackId];if(!(s!=null&&s.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==_.STOPPED&&this.setInterval(Bo)}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:s,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=this.mainDetails,c=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;if(!d){this.startFragRequested=!1;return}if(l.details){var h;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}a.alignedSliding||(os(d,a,this),c=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,d&&!this.startFragRequested&&this.setStartPosition(d,c),o===s&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:i,payload:s}=e;!i||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,i)}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e;this.fragContextChanged(t)||!(i!=null&&i.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(i,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&Vt(t.method))}decryptPayload(e,t,i){let s=t.decryptdata,n=performance.now();this.decrypter.decrypt(new Uint8Array(e),s.key.buffer,s.iv.buffer,qr(s.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(y.FRAG_DECRYPTED,{frag:t,part:i,payload:a,stats:{tstart:n,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:i}),i||(this.warn(`${a.name}: ${a.message}`),this.state=_.IDLE)})}doTick(){if(this.state===_.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:i,levels:s}=this,n=s[i],a=n?.details;if(!a||this.waitForLive(n)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}let{config:o}=this,l=this.playhead,d=J.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:c,len:h}=d,u=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(h>u||h&&!this.buffering)return;let f=this.getNextFragment(c,a);if(!f)return;if(ve(f)){var t;let g=f.sn-a.startSN,m=a.fragments[g-1];f.cc===m?.cc&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(m)===ye.NOT_LOADED&&(f=m)}this.loadFragment(f,n,c)}}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);(s===ye.NOT_LOADED||s===ye.PARTIAL)&&super.loadFragment(e,t,i)}get mediaBufferTimeRanges(){return new Ir(this.tracksBuffered[this.currentTrackId]||[])}},Ir=class{constructor(e){this.buffered=void 0;let t=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}},gg={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},kd=r=>String.fromCharCode(gg[r]||r),Je=15,Ze=42,mg={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},pg={17:2,18:4,21:6,22:8,23:10,19:13,20:15},yg={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},vg={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Eg=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Lr=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;oe.log(`${this.time} [${e}] ${i}`)}}},Pt=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},Rr=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),As=class{constructor(){this.styles=Rr}get foreground(){return this.styles.foreground}set foreground(e){let t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){let t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=Rr}setStyles(e){let t=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(e,"foreground")?e.foreground:t.foreground,underline:i.call(e,"underline")?e.underline:t.underline,italics:i.call(e,"italics")?e.italics:t.italics,background:i.call(e,"background")?e.background:t.background,flash:i.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Pr=class{constructor(){this.uchar=" ",this.penState=new As}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}},_r=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new As,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ze;t++)this.chars.push(new Pr);this.logger=e}equals(e){let t=this.chars,i=e.chars;for(let s=0;s<Ze;s++){let n=t[s],a=i[s];if(n.uchar!==a.uchar)return!1;let o=n.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<Ze;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<Ze;t++){let i=e[t];if(i.uchar!==" ")return!1;let s=i.penState.styles;if(s!==Rr&&(s.foreground!=="white"||s.underline||s.italics||s.background!=="black"||s.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Ze&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ze-1)}moveCursor(e){let t=Math.min(this.pos+e,Ze);if(e>1)for(let i=this.pos+1;i<t;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=kd(e);if(this.pos>=Ze){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ze;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<Ze;i++){let s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},ni=class{constructor(e){this.rows=[],this.currRow=Je-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Je;t++)this.rows.push(new _r(e));this.logger=e}reset(){for(let e=0;e<Je;e++)this.rows[e].clear();this.currRow=Je-1}equals(e){let t=!0;for(let i=0;i<Je;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<Je;t++){let i=this.rows[t].chars,s=e.rows[t].chars;for(let n=0;n<Ze;n++){let a=i[n],o=s[n];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Je;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+fe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Je;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d])}}this.currRow=t;let i=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}let s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+fe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],i="",s=-1;for(let n=0;n<Je;n++){let a=this.rows[n].getTextString();a&&(s=n+1,e?t.push("Row "+s+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
42
- `)),i}getTextAndFormat(){return this.rows}},kr=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new ni(i),this.nonDisplayedMemory=new ni(i),this.lastOutputScreen=new ni(i),this.currRollUpRow=this.displayedMemory.rows[Je-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Je-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(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"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{let i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+fe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},xs=class{constructor(e,t,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=Sg(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Lr,this.field=e,this.outputFilters=[null,t,i]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var i;this.outputFilters[e]=t,(i=this.channels[e])==null||i.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new kr(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){let s=t[i]&127,n=t[i+1]&127,a=!1,o=null;if(s===0&&n===0)continue;this.logger.log(3,()=>"["+Pt([t[i],t[i+1]])+"] -> ("+Pt([s,n])+")");let l=this.cmdHistory;if(s>=16&&s<=31){if(Tg(s,n,l)){Gi(null,null,l),this.logger.log(3,()=>"Repeated command ("+Pt([s,n])+") is dropped");continue}Gi(s,n,this.cmdHistory),a=this.parseCmd(s,n),a||(a=this.parseMidrow(s,n)),a||(a=this.parsePAC(s,n)),a||(a=this.parseBackgroundAttributes(s,n))}else Gi(null,null,l);if(!a&&(o=this.parseChars(s,n),o)){let c=this.currentChannel;c&&c>0?this.getChannel(c).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Pt([s,n])+" orig: "+Pt([t[i],t[i+1]]))}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(i||s))return!1;let n=e===20||e===21||e===23?1:2,a=this.getChannel(n);return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Pt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i,s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(s||n))return!1;let a=e<=23?1:2;return t>=64&&t<=95?i=a===1?mg[e]:yg[e]:i=a===1?pg[e]:vg[e],this.getChannel(a).setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0}interpretPAC(e,t){let i,s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+kd(a)+"' in channel "+i),s=[a]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+Pt(s).join(",")),s}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=Eg[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));let o=e<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}Gi(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}};function Gi(r,e,t){t.a=r,t.b=e}function Tg(r,e,t){return t.a===r&&t.b===e}function Sg(){return{a:null,b:null}}var Gt=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Dr=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=$o(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Gt(this,"textTrack1"),t=new Gt(this,"textTrack2"),i=new Gt(this,"textTrack3"),s=new Gt(this,"textTrack4");this.cea608Parser1=new xs(1,e,t),this.cea608Parser2=new xs(3,i,s)}addCues(e,t,i,s,n){let a=!1;for(let l=n.length;l--;){let d=n[l],c=bg(d[0],d[1],t,i);if(c>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],i),a=!0,c/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let l=this.cueCache[e];if(l){let d=this.Cues.newCue(null,t,i,s);d.length&&l.push.apply(l,d)}else{let d=this.captionsTracks[e].track;this.Cues.newCue(d,t,i,s)}}else{var o;let l=this.Cues.newCue(null,t,i,s),d=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:d})}}onInitPtsFound(e,{id:t,timestampOffsets:i}){let{unparsedVttFrags:s}=this;t===H.MAIN&&(this.initPTS=i),s.length&&(this.unparsedVttFrags=[],s.forEach(n=>{this.initPTS[n.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,n):this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,cueCache:s,media:n}=this,{label:a,languageCode:o}=t[e];n&&(s[e]=[],i[e]=ra(n,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){let{captionsTracks:s,cueCache:n}=this;for(let a in s)s[a].remove(),delete n[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=$o(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!Jl(this.tracks,i)){let s=i.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:s})}this.tracks=i}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;let n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){var i,s;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,c=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(d!==o+1||d===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=c}}onFragLoaded(e,t){let{frag:i,payload:s}=t;if(i.level<this.tracks.length&&i.type===H.SUBTITLE)if(s.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o?.textCodec===dr?this._parseIMSC1(t):this._parseVTTs(t)}}else{let n="part"in t?t.part:null;this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:n,error:new Error("Empty subtitle payload")})}}_parseIMSC1(e){let{frag:t,payload:i}=e,s="part"in e?e.part:null,n=this.hls;_o(i,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:s})},a=>{n.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),n.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:s,error:a})})}_parseVTTs(e){var t;let{frag:i,payload:s}=e,n="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[i.cc]&&l===-1){o.push(e);return}let d=this.hls,c=(t=i.initSegment)==null?void 0:t.data,h=c?Ye(c,new Uint8Array(s)).buffer:s;jf(h,this.initPTS[i.cc],this.vttCCs,i.cc,(n&&!c?n:i).start,u=>{this._appendCues(u,i.level),d.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:n})},u=>{let f=u.message.startsWith("Missing initPTS");if(d.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${u}`),f){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);d.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:n,error:u})})}_fallbackToIMSC1(e){let{frag:t,payload:i}=e,s=this.tracks[t.level];s.textCodec||_o(i,this.initPTS[t.cc],()=>{s.textCodec=dr,this._parseIMSC1(e)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){var s;let n=(s=this.tracks[t].trackNode)==null?void 0:s.track;if(!n||n.mode==="disabled")return;e.forEach(a=>cr(n,a))}else{let n=this.tracks[t];if(!n)return;let a=n.default?"default":"subtitles"+t;i.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===H.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:s}=t;if(!(i.type===H.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<s.length;n++){let a=s[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var i;let{type:s,timeRanges:n}=t;if(s==="video"&&(i=n[s])!=null&&i.length){let{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var d;let c=(d=a[l])==null?void 0:d.track;if(c){let h=o[l];for(let u=0;u<h.length;u++)cr(c,h[u])}delete o[l]})}}}onBufferFlushing(e,t){let{startOffset:i,endOffset:s,endOffsetSubtitles:n,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<s)){if(!a||a==="video"){let{captionsTracks:l,cueCache:d}=this;Object.keys(l).forEach(c=>hr(l[c].track,i,s)),Object.keys(d).forEach(c=>{let h=d[c];for(let u=h.length;u--;){let f=h[u];f.startTime>=i&&f.endTime<=s&&h.splice(u,1)}})}this.config.renderTextTracksNatively&&i===0&&n!==void 0&&this.tracks.forEach(l=>{var d;let c=(d=l.trackNode)==null?void 0:d.track;c&&hr(c,i,n)})}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,s=2;for(let n=0;n<i;n++){let a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){let c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(l))}}return t}};function bg(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function $o(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var Ag=/\s/,xg={newCue(r,e,t,i){let s=[],n,a,o,l,d,c=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,d="",!n.isEmpty()){var h;for(let m=0;m<n.chars.length;m++)Ag.test(n.chars[m].uchar)&&o?l++:(d+=n.chars[m].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Ad(d.trim()),g=na(e,t,f);r!=null&&(h=r.cues)!=null&&h.getCueById(g)||(a=new c(e,t,f),a.id=g,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),s.forEach(u=>cr(r,u))),s}},Is=class{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new ri}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,i){let s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ai(e,t,!0))this.retry(e);else{var i;oe.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Br(e,i.retry),i.retry++,oe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function Ig(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Lg=/(\d+)-(\d+)\/(\d+)/,Ls=class extends Is{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||kg}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:e,context:t,stats:i}=this;if(!e||!t)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;let s=Rg(t,this.controller.signal),n=t.responseType==="arraybuffer",a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=o&&B(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(vi(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var h;this.response=c;let u=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(u-i.loading.start)),!c.ok){let{status:g,statusText:m}=c;throw new Cr(m||"fetch, bad network response",g,c)}i.loading.first=u,i.total=_g(c.headers)||i.total;let f=(h=this.callbacks)==null?void 0:h.onProgress;return f&&B(e.highWaterMark)?this.loadProgressively(c,i,t,e.highWaterMark,f):n?c.arrayBuffer():t.responseType==="json"?c.json():c.text()}).then(c=>{var h,u;let f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);let g=c[a];g&&(i.loaded=i.total=g);let m={url:f.url,data:c,code:f.status},p=(h=this.callbacks)==null?void 0:h.onProgress;p&&!B(e.highWaterMark)&&p(i,t,c,f),(u=this.callbacks)==null||u.onSuccess(m,i,t,f)}).catch(c=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;let h=c&&c.code||0,u=c?c.message:null,f=e.loadPolicy.errorRetry,g=i.retry,m={url:t.url,data:void 0,code:h};if(ai(f,g,!1,m))this.retry(f);else{var p;oe.error(`${h} while loading ${t.url}`),(p=this.callbacks)==null||p.onError({code:h,text:u},t,c?c.details:null,i)}})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,n){let a=new cs,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=d.value,h=c.length;return t.loaded+=h,h<s||a.dataLength?(a.push(c),a.dataLength>=s&&n(t,i,a.flush().buffer,e)):n(t,i,c.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function Rg(r,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ce({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Pg(r){let e=Lg.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function _g(r){let e=r.get("Content-Range");if(e){let i=Pg(e);if(B(i))return i}let t=r.get("Content-Length");if(t)return parseInt(t)}function kg(r,e){return new self.Request(r.url,e)}var Cr=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Dg=(r,e,t)=>Math.max(e,Math.min(r,t)),Cg=/^age:\s*[\d.]+\s*$/im,Rs=class extends Is{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n.call(this,i,t.url,t)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n.call(this,i,t.url,t)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(let o in s)e.setRequestHeader(o,s[o]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&B(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let s=t.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let d=t.status,c=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let g=c??t.response;if(g!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);let m=t.responseType==="arraybuffer"?g.byteLength:g.length;i.loaded=i.total=m,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let p=(a=this.callbacks)==null?void 0:a.onProgress;p&&p(i,e,g,t);let v={url:t.responseURL,data:g,code:d};e.rangeEnd&&m!==e.rangeEnd-e.rangeStart&&oe.warn(`Payload length ${m} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(v,i,e,t);return}}let h=n.loadPolicy.errorRetry,u=i.retry,f={url:e.url,data:void 0,code:d};if(ai(h,u,!1,f))this.retry(h);else{var l;oe.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,i)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Cg.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},wg={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Mg=Y(Y({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Rs,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:_l,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:wg},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,streamController:Ts,abrController:An,bufferController:zn,capLevelController:Xn,errorController:xn,fpsController:nr,id3TrackController:mr,gapController:fr,latencyController:Ar},Og()),{},{subtitleStreamController:xr,subtitleTrackController:ur,timelineController:Dr,audioStreamController:qn,audioTrackController:Wn,emeController:Es,cmcdController:ir,contentSteeringController:sr,iframeController:yr,interstitialsController:br});function Og(){return{cueHandler:xg,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Fg(r,e,t){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(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){let a=e.liveMaxUnchangedPlaylistRefresh,o=Dg(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}let i=wr(r),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(c=>{let h=`${a}Loading${c}`,u=e[h];if(u!==void 0&&l){d.push(h);let f=i[o].default;switch(e[o]={default:f},c){case"TimeOut":f.maxLoadTimeMs=u,f.maxTimeToFirstByteMs=u;break;case"MaxRetry":f.errorRetry.maxNumRetry=u,f.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":f.errorRetry.retryDelayMs=u,f.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=u,f.timeoutRetry.maxRetryDelayMs=u;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${fe(e[o])}`)}),Y(Y({},i),e)}function wr(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(wr):Object.keys(r).reduce((e,t)=>(e[t]=wr(r[t]),e),{}):r}function Ng(r,e){let t=r.loader;t!==Ls&&t!==Rs?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Ig()&&(r.loader=Ls,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Mr=class extends Ei{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.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,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,d=!1,c=!1;t.levels.forEach(h=>{let u=h.attrs,f=Uo(h,i),{audioCodec:g,videoCodec:m,imageCodec:p,width:v,height:T}=h;if(!f){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}o||(o=!!(v&&T)),l||(l=!!m),d||(d=!!g),c||(c=!!p);let{CODECS:E,"FRAME-RATE":S,"HDCP-LEVEL":b,"PATHWAY-ID":A,RESOLUTION:x,"VIDEO-RANGE":R}=u,I=`${`${A||"."}-`}${h.bitrate}-${x}-${S}-${E}-${R}-${b}`;if(n[I])if(n[I].uri!==h.url&&!h.attrs["PATHWAY-ID"]){let k=a[I]+=1;h.attrs["PATHWAY-ID"]=new Array(k+1).join(".");let D=this.createLevel(h);n[I]=D,s.push(D)}else h.iframes||(n[I].addGroupId("audio",u.AUDIO),n[I].addGroupId("text",u.SUBTITLES));else{let k=this.createLevel(h);n[I]=k,a[I]=1,s.push(k)}}),this.filterAndSortMediaOptions(s,t,o,l,d,c)}createLevel(e){let t=new Ct(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!Cd(i.videoCodec,this.hls.config.preferManagedMediaSource)){let s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=gl(s,[])}return t}filterAndSortMediaOptions(e,t,i,s,n,a){var o;let l=[],d=[],c=e,h=((o=t.stats)==null?void 0:o.parsing)||{},u=this.hls.config.preferManagedMediaSource;if((i||s)&&n&&(c=c.filter(({videoCodec:b,videoRange:A,width:x,height:R})=>(!!b||!!(x&&R))&&nh(A))),s&&a&&(c=c.filter(b=>!b.imageCodec)),c.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",A=b;t.levels.length&&(A=`one or more CODECS in variant not supported: ${fe(t.levels.map(R=>R.attrs.CODECS).filter((R,P,I)=>I.indexOf(R)===P))}`,this.warn(A),b+=` (${A})`);let x=new Error(b);this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:x,reason:A})}}),h.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(b=>!b.audioCodec||Dd(b.audioCodec,u)),Go(l)),t.subtitles&&(d=t.subtitles,Go(d));let f=c.slice(0);c.sort((b,A)=>{if(b.attrs["HDCP-LEVEL"]!==A.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(A.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&b.height!==A.height)return b.height-A.height;if(b.frameRate!==A.frameRate)return b.frameRate-A.frameRate;if(b.videoRange!==A.videoRange)return Zi.indexOf(b.videoRange)-Zi.indexOf(A.videoRange);if(b.videoCodec!==A.videoCodec){let x=Ia(b.videoCodec),R=Ia(A.videoCodec);if(x!==R)return R-x}if(b.uri===A.uri&&b.codecSet!==A.codecSet){let x=Xi(b.codecSet),R=Xi(A.codecSet);if(x!==R)return R-x}return b.averageBitrate!==A.averageBitrate?b.averageBitrate-A.averageBitrate:0});let g=f[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==f.length)){for(let b=0;b<f.length;b++)if(f[b].pathwayId===c[0].pathwayId){g=f[b];break}}this._levels=c;for(let b=0;b<c.length;b++)if(c[b]===g){var m;this._firstLevel=b;let A=g.bitrate,x=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${A}`),((m=this.hls.userConfig)==null?void 0:m.abrEwmaDefaultEstimate)===void 0){let R=Math.min(A,this.hls.config.abrEwmaDefaultEstimateMax);R>x&&x===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=R)}break}let p=t.iframeVariants.filter(b=>Uo(b,u));this._iframeVariants=p;let v=n&&!s,T=this.hls.config,E=!!(T.audioStreamController&&T.audioTrackController),S={levels:c,audioTracks:l,subtitleTracks:d,iframeVariants:p,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:E&&!v&&l.some(b=>!!b.url)};h.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,S)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:c,reason:c.message}),h)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let c=this.switchParams(a.uri,s?.details,d);this.loadPlaylist(c)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===te.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===H.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;let{level:s,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(s,t,l)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(y.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let s=this.hls.config.abrSwitchInterval;if(s>0){let n=performance.now(),a=n-this.lastABRSwitchTime,o=s*1e3;if(this.lastABRSwitchTime>-1&&a<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms < ${o}ms / ${s}s)`);return}this.lastABRSwitchTime=n,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms >= ${o}ms / ${s}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));Fl(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(y.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function Dd(r,e){return ci(r,"audio",e)}function Cd(r,e){return ci(r,"video",e)}function Uo(r,e){let{audioCodec:t,videoCodec:i}=r;t&&(r.audioCodec=t=Qi(t,e)||void 0),i&&(i=r.videoCodec=zc(i));let{unknownCodecs:s}=r;return!(s?.length||0||t&&!Dd(t,e)||i&&!Cd(i,e))}function Go(r){let e={};r.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var Or=class extends Oe{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyLoaderInfo){let s=this.keyLoaderInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,i){return this.emeController?this.emeController.loadClear(e,t,i):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(i=>this.loadInternal(e,t,i)):this.loadInternal(e,t)}loadInternal(e,t,i){i&&e.setKeyFormat(i);let s=e.decryptdata;if(!s){let a=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(mt(e,L.KEY_LOAD_ERROR,a))}let n=e;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(n):t?t.then(()=>this.loadKeyEME(n)):this.loadKeyEME(n);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(n);default:return Promise.reject(mt(e,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let i=_c(e.initSegment.data);if(i.length){let s=i[0],n=e.decryptdata.uri;if(s.some(a=>a!==0))this.log(`Using keyId found in init segment ${Ie(s)} keyUri: ${n}`),wt.setKeyIdForUri(n,s);else{let a=wt.addKeyIdForUri(n);this.log(`Patching empty keyId with ${Ie(a)} keyUri: ${n}`),s=a}e.decryptdata.keyId=s}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(mt(e,L.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,i=t.uri;if(!i)return Promise.reject(mt(e,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let s=this.keyLoaderInfo[i];if(s){if(s.decryptdata.key)return t.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then(d=>(t.key=s.decryptdata.key,Y(Y({},d),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ie(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);let n=this.config,a=n.loader,o=new a(n);e.keyLoader=o;let l=this.keyLoaderInfo[i]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((d,c)=>{let h={type:te.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:i},u=n.keyLoadPolicy.default,f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,p,v,T)=>{let{frag:E,keyInfo:S,url:b}=v;if(!E.decryptdata||S!==this.keyLoaderInfo[b])return c(mt(E,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),T));S.decryptdata.key=E.decryptdata.key=new Uint8Array(m.data),E.keyLoader=S.loader=S.keyLoadPromise=null,d({frag:E,keyInfo:S})},onError:(m,p,v,T)=>{this.resetLoader(p),c(mt(e,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),v,Y({url:i,data:void 0},m)))},onTimeout:(m,p,v)=>{this.resetLoader(p),c(mt(e,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(m,p,v)=>{this.resetLoader(p),c(mt(e,L.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};o.load(h,f,g)})}resetLoader(e){let{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[s],n&&n.destroy()}};function mt(r,e=L.KEY_LOAD_ERROR,t,i,s){return new We({type:W.NETWORK_ERROR,details:e,fatal:!1,frag:r,response:s,error:t,networkDetails:i||null})}function Vo(r){let{type:e}=r;switch(e){case te.AUDIO_TRACK:return H.AUDIO;case te.SUBTITLE_TRACK:return H.SUBTITLE;default:return H.MAIN}}function fn(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Fr=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:te.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:te.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:te.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let i=this.loaders[te.LEVEL];if(i){let s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[te.LEVEL])}}load(e){var t;let i=this.hls.config,s=this.getInternalLoader(e);if(s){let d=this.hls.logger,c=s.context;if(c?.levelOrTrack===e.levelOrTrack&&(c.url===e.url||c.deliveryDirectives&&!e.deliveryDirectives)){c.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${c.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===te.MANIFEST?n=i.manifestLoadPolicy.default:n=ce({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),B((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===te.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===te.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===te.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let c=d.partTarget,h=d.targetduration;if(c&&h){let u=Math.max(c*3,h*.8)*1e3;n=ce({},n,{maxTimeToFirstByteMs:Math.min(u,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,n.maxTimeToFirstByteMs)})}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,c,h,u)=>{let f=this.getInternalLoader(h);this.resetInternalLoader(h.type);let g=d.data;c.parsing.start=performance.now(),Et.isMediaPlaylist(g)||h.type!==te.MANIFEST?this.handleTrackOrLevelPlaylist(d,c,h,u||null,f):this.handleMasterPlaylist(d,c,h,u)},onError:(d,c,h,u)=>{this.handleNetworkError(c,h,!1,d,u)},onTimeout:(d,c,h)=>{this.handleNetworkError(c,h,!0,void 0,d)}};s.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){let n=this.hls,a=e.data,o=fn(e,i),l=Et.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}let{contentSteering:d,levels:c,iframeVariants:h,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,c.forEach(E=>{let{unknownCodecs:S}=E;if(S){let{preferManagedMediaSource:b}=this.hls.config,{audioCodec:A,videoCodec:x}=E;for(let R=S.length;R--;){let P=S[R];ci(P,"audio",b)?(E.audioCodec=A=A?`${A},${P}`:P,Kt.audio[A.substring(0,4)]=2,S.splice(R,1)):ci(P,"video",b)&&(E.videoCodec=x=x?`${x},${P}`:P,Kt.video[x.substring(0,4)]=2,S.splice(R,1))}}});let{AUDIO:p=[],SUBTITLES:v,"CLOSED-CAPTIONS":T}=Et.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(S=>!S.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new pe({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:v,iframeVariants:h,captions:T,contentSteering:d,url:o,stats:t,networkDetails:s,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,s,n){let a=this.hls,{id:o,level:l,type:d}=i,c=fn(e,i),h=B(l)?l:B(o)?o:0,u=Vo(i),f=Et.parseLevelPlaylist(e.data,c,h,u,0,this.variableList);if(d===te.MANIFEST){let g={attrs:new pe({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=t.loading.start+wl(f,0),a.trigger(y.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:c,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:t.type===te.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===te.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===te.AUDIO_TRACK||e.type===te.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=L.UNKNOWN,d=!1,c=this.getInternalLoader(e);switch(e.type){case te.MANIFEST:l=i?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,d=!0;break;case te.LEVEL:l=i?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,d=!1;break;case te.AUDIO_TRACK:l=i?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case te.SUBTITLE_TRACK:l=i?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,d=!1;break}c&&this.resetInternalLoader(e.type);let h={type:W.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:n};if(s){let u=e.url;t&&"url"in t&&(u=t.url),h.response=Y({url:u,data:void 0},s)}this.hls.trigger(y.ERROR,h)}handlePlaylistLoaded(e,t,i,s,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:c,id:h,groupId:u,deliveryDirectives:f}=s,g=fn(t,s),m=Vo(s),p=typeof s.level=="number"&&m===H.MAIN?d:void 0;c&&"iframes"in c&&c.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);let v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:t,context:s,level:p,parent:m,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){let T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:t,context:s,level:p,parent:m,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case te.MANIFEST:case te.LEVEL:if(p){if(!c)p=0;else if(c!==o.levels[p]){let T=o.levels.indexOf(c);T>-1&&(p=T)}}o.trigger(y.LEVEL_LOADED,{details:e,levelInfo:c||o.levels[0],level:p||0,id:h||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===te.MANIFEST,context:s});break;case te.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:c,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:f,context:s});break;case te.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:c,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:f,context:s});break}}},xt=class r{static get version(){return pi}static isMSESupported(){return Pd()}static isSupported(){return rg()}static getMediaSource(){return bt()}static get Events(){return y}static get MetadataSchema(){return Me}static get ErrorTypes(){return W}static get ErrorDetails(){return L}static get DefaultConfig(){return r.defaultConfig?r.defaultConfig:Mg}static set DefaultConfig(e){r.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Yr,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=ic(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),i=this.config=Fg(r.DefaultConfig,e,t);this.userConfig=e,i.progressive&&Ng(i,t);let{streamController:s,abrController:n,bufferController:a,capLevelController:o,errorController:l,fpsController:d,id3TrackController:c,iframeController:h,gapController:u}=i,f=new l(this),g=this.abrController=new n(this),m=new In(this),p=i.interstitialsController,v=p?this.interstitialsController=new p(this,r):null,T=a?this.bufferController=new a(this,m):null,E=o?this.capLevelController=new o(this):null,S=d?new d(this):null,b=i.cmcdController,A=b?this.cmcdController=new b(this):null,x=new Fr(this),R=i.contentSteeringController,P=R?new R(this):null,I=this.levelController=new Mr(this,P),k=c?new c(this):void 0,D=new Or(this.config,this.logger),F=this.streamController=new s(this,m,D),G=this.gapController=u?new u(this,m):void 0;E&&E.setStreamController(F);let $=[x,I,F];v&&$.splice(1,0,v),P&&$.splice(1,0,P),this.networkControllers=$;let C=[g];T&&C.push(T),G&&C.push(G),E&&C.push(E),S&&(S.setStreamController(F),C.push(S)),k&&C.push(k),C.push(m),this.audioTrackController=this.createController(i.audioTrackController,$);let M=i.audioStreamController;M&&$.push(this.audioStreamController=new M(this,m,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,$);let w=i.subtitleStreamController;w&&$.push(this.subtititleStreamController=new w(this,m,D)),this.createController(i.timelineController,C),D.emeController=this.emeController=this.createController(i.emeController,C),A&&C.push(A),this.latencyController=this.createController(i.latencyController,C),this.coreComponents=C,this.iframeController=h?new h(this,r):void 0,$.push(f);let N=f.onErrorOut;typeof N=="function"&&this.on(y.ERROR,N,f),this.on(y.MANIFEST_LOADED,x.onManifestLoaded,x)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let s=e===y.ERROR;this.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(y.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,this.iframeController=void 0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(y.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(y.MEDIA_DETACHING,e),this._media=null,this.trigger(y.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,i={transferMedia:t};return this.trigger(y.MEDIA_DETACHING,i),this.trigger(y.MEDIA_DETACHED,i),t}loadSource(e){var t;this.stopLoad();let i=this.media,s=this._url,n=this._url=Nr.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),i&&s&&(s!==n||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(y.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==_.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[H.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[H.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[H.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=this.started,i=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=zo()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=this.capLevelController,i=!!e;t&&i!==this.config.capLevelToPlayerSize&&(i?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){sh(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){let{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){let e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=vl(t);return ml(e,i,navigator.mediaCapabilities)}};xt.defaultConfig=void 0;var fm=.045,wd={textSizeFraction:.045,foregroundColor:"#FFFFFF",backgroundColor:"rgba(0,0,0,0.5)",windowColor:"rgba(0,0,0,0)",edgeType:"NONE",edgeColor:"#000000",applyEmbeddedStyles:!0,fontFamily:null},ue={NETWORK_CONNECTION_FAILED:2e3,NETWORK_TIMEOUT:2001,NETWORK_HTTP_STATUS:2002,SOURCE_MALFORMED:3e3,SOURCE_UNSUPPORTED:3001,SOURCE_NOT_FOUND:3002,DRM_LICENSE_FAILED:4e3,DRM_LICENSE_HTTP_STATUS:4001,DRM_TOKEN_FETCH_FAILED:4002,DRM_PROVISIONING_FAILED:4003,DRM_SESSION_EXPIRED:4004,DRM_UNSUPPORTED:4005,DECODER_INIT_FAILED:5e3,DECODING_FAILED:5001,AUDIO_OUTPUT_FAILED:5002,BEHIND_LIVE_WINDOW:6e3,UNKNOWN:9e3},gm="1.0.3";var Bg={2e3:"NETWORK_CONNECTION_FAILED",2001:"NETWORK_TIMEOUT",2002:"NETWORK_HTTP_STATUS",3e3:"SOURCE_MALFORMED",3001:"SOURCE_UNSUPPORTED",3002:"SOURCE_NOT_FOUND",4e3:"DRM_LICENSE_FAILED",4001:"DRM_LICENSE_HTTP_STATUS",4002:"DRM_TOKEN_FETCH_FAILED",4003:"DRM_PROVISIONING_FAILED",4004:"DRM_SESSION_EXPIRED",4005:"DRM_UNSUPPORTED",5e3:"DECODER_INIT_FAILED",5001:"DECODING_FAILED",5002:"AUDIO_OUTPUT_FAILED",6e3:"BEHIND_LIVE_WINDOW",9e3:"UNKNOWN"};function Ee(r,e,t,i,s,n){return{code:r,category:e,message:t,retryable:i,codeName:Bg[r]??`HTTP_${r}`,...s!==void 0?{httpStatusCode:s}:{},...n!==void 0?{cause:n}:{}}}function Md(r){switch(r?.code){case MediaError.MEDIA_ERR_NETWORK:return Ee(ue.NETWORK_CONNECTION_FAILED,"Network",r.message||"network error while fetching media",!0);case MediaError.MEDIA_ERR_DECODE:return Ee(ue.DECODING_FAILED,"Renderer",r.message||"media decode failed",!0);case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return Ee(ue.SOURCE_UNSUPPORTED,"Source",r.message||"source not supported by this browser",!1);default:return Ee(ue.UNKNOWN,"Unknown",r?.message||"unknown playback error",!0,void 0,r)}}function Od(r){let e=r.response?.code,t=r.details;if(e&&e>=400){let i=e===404?ue.SOURCE_NOT_FOUND:ue.NETWORK_HTTP_STATUS;return Ee(i,e===404?"Source":"Network",`${t} (HTTP ${e})`,e>=500,e,r.error)}if(r.type==="keySystemError"||t.startsWith("keySystem"))return t.includes("NoAccess")||t.includes("NoConfiguredLicense")?Ee(ue.DRM_UNSUPPORTED,"Drm","no supported DRM key system in this browser",!1,void 0,r.error):t.includes("ServerCertificate")?Ee(ue.DRM_PROVISIONING_FAILED,"Drm",t,!0,void 0,r.error):t.includes("LicenseRequestFailed")?Ee(e?ue.DRM_LICENSE_HTTP_STATUS:ue.DRM_LICENSE_FAILED,"Drm",t,!0,e,r.error):t.includes("SessionUpdateFailed")||t.includes("NoKeys")||t.includes("StatusInternalError")?Ee(ue.DRM_LICENSE_FAILED,"Drm",t,!0,void 0,r.error):t.includes("Expired")?Ee(ue.DRM_SESSION_EXPIRED,"Drm",t,!0,void 0,r.error):Ee(ue.DRM_LICENSE_FAILED,"Drm",t,!0,void 0,r.error);if(r.type==="networkError"){let i=t.includes("Timeout")||t.includes("TIMEOUT");return Ee(i?ue.NETWORK_TIMEOUT:ue.NETWORK_CONNECTION_FAILED,"Network",t,!0,void 0,r.error)}return r.type==="mediaError"?t.includes("Parsing")||t.includes("PARSING")||t.includes("manifest")?Ee(ue.SOURCE_MALFORMED,"Source",t,!1,void 0,r.error):Ee(ue.DECODING_FAILED,"Renderer",t,!0,void 0,r.error):t.includes("levelSwitch")||t.includes("liveBackBuffer")?Ee(ue.BEHIND_LIVE_WINDOW,"Live",t,!0,void 0,r.error):Ee(ue.UNKNOWN,"Unknown",t,!r.fatal,void 0,r.error)}var $g="MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV4yKAojBJAh5bd1bJWOc75e4psyXk2HXRlis9YZMcG0fYB5RfkQISQ5hlNVHZisVGAAGV9Dg9tYRY8BbnJTzhg==",Fd=new Map;function oa(r,e,t=$g){let i=`${r??""}|${e}|${t}`,s=Fd.get(i);return s||(s=Ug(r,e,t),Fd.set(i,s)),s}async function Ug(r,e,t){if(!r)return{licensed:!1,reason:"no license key set"};let i=r.split(".");if(i.length!==3||i[0]!=="OGP1")return{licensed:!1,reason:"malformed license key"};let s=Nd(i[1]),n=Nd(i[2]);if(!s||!n)return{licensed:!1,reason:"malformed payload"};if(!await Gg(s,n,t))return{licensed:!1,reason:"invalid signature"};let a;try{a=JSON.parse(new TextDecoder().decode(s))}catch{return{licensed:!1,reason:"unreadable payload"}}if(!(Array.isArray(a.apps)?a.apps:[]).some(d=>Hg(e,d)))return{licensed:!1,reason:`license not valid for ${e}`};let l=typeof a.exp=="string"?a.exp:"";return Kg(l)?{licensed:!1,reason:`license expired ${l}`}:{licensed:!0,licensee:typeof a.to=="string"?a.to:"unknown",edition:typeof a.ed=="string"?a.ed:"standard",exp:l}}async function Gg(r,e,t){try{let i=Bd(t);if(!i)return!1;let s=await crypto.subtle.importKey("spki",aa(i),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),n=Vg(e);return n?await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,aa(n),aa(r)):!1}catch{return!1}}function Vg(r){let e=0;if(r[e++]!==48)return null;let t=r[e++];t&128&&(e+=t&127);let i=()=>{if(r[e++]!==2)return null;let o=r[e++];if(o&128)return null;let l=e;for(e+=o;o>32&&r[l]===0;)l++,o--;if(o>32)return null;let d=new Uint8Array(32);return d.set(r.slice(l,l+o),32-o),d},s=i(),n=i();if(!s||!n)return null;let a=new Uint8Array(64);return a.set(s,0),a.set(n,32),a}function Hg(r,e){return e.endsWith("*")?r.startsWith(e.slice(0,-1)):r===e}function Kg(r){if(!r)return!0;let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`>r}function Nd(r){let e=r.replaceAll("-","+").replaceAll("_","/");for(;e.length%4!==0;)e+="=";return Bd(e)}function Bd(r){try{let e=atob(r),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}catch{return null}}function aa(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}function Ud(r,e,t,i,s){let n=!1,a=null,o=0,l=[],d=$d(e.certificateUrl,void 0,"certificate"),c=async u=>{let{initDataType:f,initData:g}=u;if(!(n||!g))try{if(!a){a=await(await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[f],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'}]}])).createMediaKeys();let v=await d;await a.setServerCertificate(v),await r.setMediaKeys(a)}let m=a.createSession();l.push(m),m.addEventListener("message",p=>{(async()=>{try{let v=o>0;o++;let T={};if(e.tokenProvider)try{T=await e.tokenProvider({licenseUrl:e.licenseUrl,renewal:v})}catch(S){throw{ogError:Ee(ue.DRM_TOKEN_FETCH_FAILED,"Drm",`DRM token provider failed: ${S instanceof Error?S.message:"error"}`,!0,void 0,S)}}let E=await $d(e.licenseUrl,{method:"POST",headers:{"Content-Type":"application/octet-stream",...e.headers,...T},body:p.message},"license");n||(await m.update(E),v?s?.():i?.())}catch(v){h(v)}})()}),await m.generateRequest(f,g)}catch(m){h(m)}},h=u=>{n||(u&&typeof u=="object"&&"ogError"in u?t(u.ogError):t(Ee(ue.DRM_LICENSE_FAILED,"Drm",u instanceof Error?u.message:"FairPlay key exchange failed",!0,void 0,u)))};return r.addEventListener("encrypted",c),()=>{n=!0,r.removeEventListener("encrypted",c),l.forEach(u=>void u.close().catch(()=>{}))}}async function $d(r,e,t){let i;try{i=await fetch(r,e)}catch(s){throw{ogError:Ee(t==="certificate"?ue.DRM_PROVISIONING_FAILED:ue.DRM_LICENSE_FAILED,"Drm",`FairPlay ${t} request failed: ${s instanceof Error?s.message:"network error"}`,!0,void 0,s)}}if(!i.ok)throw{ogError:Ee(ue.DRM_LICENSE_HTTP_STATUS,"Drm",`FairPlay ${t} HTTP ${i.status}`,i.status>=500,i.status)};return i.arrayBuffer()}var qg=/(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?/;function Gd(r){let e=qg.exec(r.trim());if(!e)return null;let t=Number(e[1]??0),i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4].padEnd(3,"0")):0;return((t*60+i)*60+s)*1e3+n}function Wg(r,e){let t=[],i=r.split(/\r?\n/);for(let s=0;s<i.length;s++){let n=i[s];if(!n.includes("-->"))continue;let[a,o]=n.split("-->"),l=Gd(a??""),d=Gd(o??""),c=(i[s+1]??"").trim();if(l===null||d===null||!c)continue;let[h,u]=c.split("#"),f;try{f=new URL(h,e).toString()}catch{continue}let g=/xywh=(\d+),(\d+),(\d+),(\d+)/.exec(u??"");t.push({startMs:l,endMs:d,frame:g?{url:f,x:Number(g[1]),y:Number(g[2]),width:Number(g[3]),height:Number(g[4])}:{url:f,x:0,y:0,width:0,height:0}})}return t}var Cs=class{constructor(e){this.vttUrl=e}cues=null;loading=null;ensureLoaded(){return this.loading??=fetch(this.vttUrl).then(e=>e.ok?e.text():Promise.reject(new Error(`HTTP ${e.status}`))).then(e=>{this.cues=Wg(e,this.vttUrl)}).catch(()=>{this.cues=[]}),this.loading}async frameAt(e){await this.ensureLoaded();let t=this.cues??[],i=t.find(s=>e>=s.startMs&&e<s.endMs)??t[t.length-1];return i&&e>=0?i.frame:null}};var Yg=12;function jg(r){if(!r)return"";try{let e=new Intl.DisplayNames(["en"],{type:"language"}).of(r);return!e||e===r?r:e.charAt(0).toUpperCase()+e.slice(1)}catch{return r}}var Mt=class{videoElement;hls=null;item=null;stateValue="IDLE";listeners=new Set;analyticsListeners=new Set;adListeners=new Set;progressTimer=null;snapshotTimer=null;opts;startedOnce=!1;didDispatchPause=!1;seekTargetMs=null;atLiveEdgeValue=!0;wasEnded=!1;licensedValue=!1;licenseListeners=new Set;loadGeneration=0;lastBitrate=-1;sideloadedDefaultId=null;nativeLoadListeners=[];detachDrm=null;sawEncrypted=!1;drmKeysAnnounced=!1;drmLicenseRequests=0;thumbnailTrack=null;lastDroppedTotal=0;breakResume=null;adsProvider=null;adContainer=null;attachedAdsProvider=null;pendingAdConfig=null;completedAdSessions=new Set;currentAdSessionKey=null;lastLoadedItem=null;lastStablePositionMs=0;pendingContentAutoplay=!0;isPlayingAdFlag=!1;adsPendingFlag=!1;adPausedFlag=!1;adProgressValue=null;adCuePointsValue=[];lastAdInfo=null;suppressAdBreakTransition=!1;hlsConfig=null;fallbackToMutedAutoplay=!1;holdPlayback=!1;constructor(e={}){this.opts={progressUpdateIntervalMs:e.progressUpdateIntervalMs??250,seekForwardIncrementMs:e.seekForwardIncrementMs??1e4,seekBackwardIncrementMs:e.seekBackwardIncrementMs??1e4,...e.licenseKey!==void 0?{licenseKey:e.licenseKey}:{}},this.hlsConfig=e.hlsConfig??null,this.fallbackToMutedAutoplay=e.fallbackToMutedAutoplay??!1,this.videoElement=document.createElement("video"),this.videoElement.playsInline=!0,this.videoElement.preload=e.preload??"auto",this.videoElement.crossOrigin="anonymous",this.bindVideoEvents(),oa(this.opts.licenseKey,location.hostname).then(t=>{this.licensedValue=t.licensed,this.licenseListeners.forEach(i=>i(t.licensed))})}get state(){return this.stateValue}get isPlaying(){return!this.videoElement.paused&&!this.videoElement.ended&&this.stateValue!=="IDLE"}get currentItem(){return this.item}get currentPositionMs(){return Math.max(0,this.videoElement.currentTime*1e3)}get durationMs(){let e=this.videoElement.duration;return Number.isFinite(e)?e*1e3:0}get bufferedPositionMs(){let e=this.videoElement.buffered,t=this.videoElement.currentTime;for(let i=0;i<e.length;i++)if(e.start(i)<=t&&t<=e.end(i))return e.end(i)*1e3;return this.currentPositionMs}get playbackSpeed(){return this.videoElement.playbackRate}set playbackSpeed(e){this.videoElement.playbackRate=e}get volume(){return this.videoElement.volume}set volume(e){this.videoElement.volume=Math.min(1,Math.max(0,e))}get isMuted(){return this.videoElement.muted}set isMuted(e){this.videoElement.muted=e}get isLooping(){return this.videoElement.loop}setLooping(e){this.videoElement.loop=e}setBufferRole(e){let t=e==="STANDBY";this.videoElement.preload=t?"metadata":"auto",this.hls&&(this.hls.config.maxBufferLength=t?10:30,this.hls.config.maxMaxBufferLength=t?10:600,this.hls.config.maxBufferSize=t?8e6:6e7,this.hls.config.backBufferLength=t?0:1/0)}volumeControlMode="PLAYER";get isLicensed(){return this.licensedValue}get seekForwardIncrementMs(){return this.opts.seekForwardIncrementMs}get seekBackwardIncrementMs(){return this.opts.seekBackwardIncrementMs}get isPlayingAd(){return this.isPlayingAdFlag}get adsPending(){return this.adsPendingFlag}get adPaused(){return this.adPausedFlag}get adProgress(){return this.adProgressValue}get adCuePoints(){return this.adCuePointsValue}get currentLoadGeneration(){return this.loadGeneration}subtitleStyle={...wd};subtitleTextScale=1;onLicenseChanged(e){this.licenseListeners.add(e)}addListener(e){this.listeners.add(e)}removeListener(e){this.listeners.delete(e)}addAnalyticsListener(e){this.analyticsListeners.add(e)}removeAnalyticsListener(e){this.analyticsListeners.delete(e)}addAdListener(e){this.adListeners.add(e)}removeAdListener(e){this.adListeners.delete(e)}dispatch(e){this.listeners.forEach(e)}emit(e){this.analyticsListeners.forEach(t=>t(e))}playlistItems=[];playlistPosition=-1;pendingPlaylistAdvanceAfterAds=!1;playlistAdvanceFallback=null;adScheduleSettled=!0;get playlist(){return this.playlistItems.slice()}get currentPlaylistIndex(){return this.playlistPosition}get nextPlaylistItem(){return this.playlistPosition<0?null:this.playlistItems[this.playlistPosition+1]??null}load(e,t={}){this.playlistItems=[],this.playlistPosition=-1,this.loadItemInternal(e,t)}loadPlaylist(e,t={}){let{startIndex:i=0,autoplay:s=!0}=t;if(e.length===0)throw new Error("loadPlaylist requires at least one item");let n=e[i];if(!n)throw new Error("startIndex out of range");this.playlistItems=e.slice(),this.playlistPosition=i,this.dispatch(a=>a.onPlaylistItemChanged?.(i,n)),this.loadItemInternal(n,{autoplay:s})}skipToNext(){let e=this.playlistPosition;e<0||!this.playlistItems[e+1]||(this.dispatch(t=>t.onPlaylistItemSkipped?.(e,e+1)),this.maybeAdvancePlaylist())}releasePendingPlaylistAdvance(){this.pendingPlaylistAdvanceAfterAds&&(this.pendingPlaylistAdvanceAfterAds=!1,this.playlistAdvanceFallback!==null&&(clearTimeout(this.playlistAdvanceFallback),this.playlistAdvanceFallback=null),setTimeout(()=>this.maybeAdvancePlaylist(),0))}maybeAdvancePlaylist(){let e=this.playlistPosition+1,t=this.playlistPosition>=0?this.playlistItems[e]:void 0;t&&(this.playlistPosition=e,this.dispatch(i=>i.onPlaylistItemChanged?.(e,t)),this.loadItemInternal(t,{autoplay:!0}))}loadItemInternal(e,t={}){this.pendingPlaylistAdvanceAfterAds=!1,this.playlistAdvanceFallback!==null&&(clearTimeout(this.playlistAdvanceFallback),this.playlistAdvanceFallback=null),this.adScheduleSettled=!0,this.videoElement.poster=e.posterUrl??"";let{startPositionMs:i=0,autoplay:s=!0}=t;if(this.lastLoadedItem=e,this.lastStablePositionMs=i,this.loadGeneration++,this.teardownSource(),this.item=e,this.startedOnce=!1,this.didDispatchPause=!1,this.wasEnded=!1,this.lastBitrate=-1,this.sawEncrypted=!1,this.drmKeysAnnounced=!1,this.drmLicenseRequests=0,this.lastDroppedTotal=0,this.thumbnailTrack=e.thumbnailTrackUrl?new Cs(e.thumbnailTrackUrl):null,this.resetAdSession(),this.breakResume=null,this.stateValue="IDLE",this.setState("BUFFERING"),this.emit({type:"BufferStart"}),this.attachSource(e,i),this.beginAdsIfNeeded(e,s),s&&!this.adsPendingFlag&&!this.holdPlayback){let n=this.loadGeneration;this.videoElement.play().catch(a=>{this.fallbackToMutedAutoplay&&n===this.loadGeneration&&a instanceof DOMException&&a.name==="NotAllowedError"&&!this.videoElement.muted&&(this.videoElement.muted=!0,this.videoElement.play().then(()=>{this.dispatch(o=>o.onMutedAutoplayFallback?.()),this.emit({type:"MutedAutoplayFallback"})}).catch(()=>{}))})}this.startProgressTimer(),this.startSnapshotTimer()}retry(){let e=this.lastLoadedItem;if(!e)return;let t=(e.streamType??"VOD")==="VOD";this.loadItemInternal(e,{startPositionMs:t?this.lastStablePositionMs:0})}attachSource(e,t){let i=e.url;if((/\.m3u8($|\?)/i.test(i)||i.includes("format=m3u8"))&&xt.isSupported()){let n=e.drm,a={};n?.widevine&&(a["com.widevine.alpha"]={licenseUrl:n.widevine.licenseUrl,...n.widevine.serverCertificateUrl?{serverCertificateUrl:n.widevine.serverCertificateUrl}:{}}),n?.playready&&(a["com.microsoft.playready"]={licenseUrl:n.playready.licenseUrl});let o={...n?.widevine?.headers,...n?.playready?.headers},l=new xt({...this.hlsConfig,renderTextTracksNatively:!0,...Object.keys(a).length>0?{emeEnabled:!0,drmSystems:a,licenseXhrSetup:async d=>{let c=this.drmLicenseRequests>0;this.drmLicenseRequests++;let h={};if(n?.tokenProvider)try{h=await n.tokenProvider({licenseUrl:n.widevine?.licenseUrl??n.playready?.licenseUrl??"",renewal:c})}catch(u){let f=Ee(ue.DRM_TOKEN_FETCH_FAILED,"Drm",`DRM token provider failed: ${u instanceof Error?u.message:"error"}`,!0,void 0,u);throw this.dispatch(g=>g.onError?.(f)),this.emit({type:"Error",error:f}),u}for(let[u,f]of Object.entries({...o,...h}))d.setRequestHeader(u,f);c&&this.dispatch(u=>u.onDrmSessionRenewed?.("PROACTIVE"))}}:{}});this.hls=l,this.bindHlsEvents(l),l.loadSource(i),l.attachMedia(this.videoElement)}else{if(e.drm?.fairplay){let a=e.drm.tokenProvider?{...e.drm.fairplay,tokenProvider:e.drm.tokenProvider}:e.drm.fairplay;this.detachDrm=Ud(this.videoElement,a,o=>{this.dispatch(l=>l.onError?.(o)),this.emit({type:"Error",error:o})},()=>{this.drmKeysAnnounced||(this.drmKeysAnnounced=!0,this.emit({type:"DrmKeysLoaded"}))},()=>this.dispatch(o=>o.onDrmSessionRenewed?.("PROACTIVE")))}this.videoElement.src=i;let n=()=>{};this.videoElement.addEventListener("loadedmetadata",n,{once:!0}),this.nativeLoadListeners.push(["loadedmetadata",n])}if(t>0){let n=()=>{this.videoElement.currentTime=t/1e3};this.videoElement.addEventListener("loadedmetadata",n,{once:!0}),this.nativeLoadListeners.push(["loadedmetadata",n])}this.attachSideloadedSubtitles(e)}adSessionKey(e){let t=e.adBreaks?.adTagUri;return t?`${e.url}|${t}`:null}beginAdsIfNeeded(e,t){!e.adBreaks||!this.adsProvider||(this.currentAdSessionKey=this.adSessionKey(e),!(this.currentAdSessionKey&&this.completedAdSessions.has(this.currentAdSessionKey))&&(this.pendingContentAutoplay=t,this.adScheduleSettled=!1,this.adsPendingFlag=t,this.adContainer?this.startAdsSession(e.adBreaks):this.pendingAdConfig=e.adBreaks))}startAdsSession(e){let t=this.adsProvider,i=this.adContainer;!t||!i||(this.attachedAdsProvider!==t&&(t.attach(this.videoElement,i,this.adCallbacks),this.attachedAdsProvider=t),t.requestAds(e,this.pendingContentAutoplay))}resetAdSession(){this.attachedAdsProvider&&this.attachedAdsProvider!==this.adsProvider&&(this.attachedAdsProvider.destroy(),this.attachedAdsProvider=null),this.adsProvider?.destroy(),this.adContainer&&this.adContainer.replaceChildren(),this.pendingAdConfig=null,this.lastAdInfo=null,this.adCuePointsValue=[],this.adProgressValue=null,this.adPausedFlag=!1,this.adsPendingFlag=!1,this.suppressAdBreakTransition=!1,this.isPlayingAdFlag=!1}dispatchAd(e){this.adListeners.forEach(e)}adCallbacks={onContentPauseRequested:()=>{this.adsPendingFlag=!1,this.isPlayingAdFlag=!0,this.suppressAdBreakTransition=this.isPlaying,this.videoElement.pause(),this.adsProvider?.usesContentVideoElement&&(this.breakResume={positionMs:this.stateValue==="ENDED"?0:this.currentPositionMs,wasEnded:this.stateValue==="ENDED"},this.teardownSource())},onContentResumeRequested:()=>{if(this.adsPendingFlag=!1,this.isPlayingAdFlag=!1,this.adPausedFlag=!1,this.adProgressValue=null,this.breakResume&&this.item){let{positionMs:e,wasEnded:t}=this.breakResume;if(this.breakResume=null,this.videoElement.controls=!1,this.teardownSource(),!t)this.attachSource(this.item,e);else return}this.pendingContentAutoplay&&this.stateValue!=="ENDED"&&!this.holdPlayback?this.videoElement.play().catch(()=>{}):this.suppressAdBreakTransition=!1},onAdCuePoints:e=>{this.adCuePointsValue=e},onAllAdsCompleted:()=>{this.currentAdSessionKey&&this.completedAdSessions.add(this.currentAdSessionKey),this.adScheduleSettled=!0,this.releasePendingPlaylistAdvance()},onAdBreakStarted:(e,t)=>{this.playlistAdvanceFallback!==null&&(clearTimeout(this.playlistAdvanceFallback),this.playlistAdvanceFallback=null),this.dispatchAd(i=>i.onAdBreakStarted?.(e,t))},onAdStarted:e=>{this.lastAdInfo=e,this.adPausedFlag=!1,this.adProgressValue={positionMs:0,durationMs:e.durationMs,adIndex:e.positionInPod,adCount:e.podSize},this.dispatchAd(t=>t.onAdStarted?.(e))},onAdProgress:(e,t,i)=>{this.adProgressValue={positionMs:t,durationMs:i,adIndex:e.positionInPod,adCount:e.podSize},this.dispatchAd(s=>s.onAdProgress?.(e,t,i))},onAdPaused:e=>{this.adPausedFlag=!0,this.dispatchAd(t=>t.onAdPaused?.(e))},onAdResumed:e=>{this.adPausedFlag=!1,this.dispatchAd(t=>t.onAdResumed?.(e))},onAdSkipped:e=>{this.adProgressValue=null,this.dispatchAd(t=>t.onAdSkipped?.(e))},onAdCompleted:e=>{this.adProgressValue=null,this.dispatchAd(t=>t.onAdCompleted?.(e))},onAdBreakCompleted:e=>{if(e==="POSTROLL")this.adCuePointsValue=this.adCuePointsValue.filter(t=>t>=0);else{let t=this.videoElement.currentTime,i=this.adCuePointsValue.filter(s=>s>=0).sort((s,n)=>Math.abs(s-t)-Math.abs(n-t))[0];i!==void 0&&(this.adCuePointsValue=this.adCuePointsValue.filter(s=>s!==i))}this.dispatchAd(t=>t.onAdBreakCompleted?.(e))},onAdError:e=>{this.dispatchAd(t=>t.onAdError?.(e)),this.releasePendingPlaylistAdvance()}};play(){if(!this.holdPlayback){if(this.isPlayingAdFlag){this.adsProvider?.resume();return}this.adsProvider?.startPendingBreak()||(this.stateValue==="ENDED"&&(this.videoElement.currentTime=0),this.videoElement.play().catch(()=>{}))}}pause(){if(this.isPlayingAdFlag){this.adsProvider?.pause();return}this.videoElement.pause()}skipAd(){this.adsProvider?.skip()}clickAd(){this.adsProvider?.click()}get adCuePositionsMs(){return this.adCuePointsValue.map(e=>{if(e>=0)return Math.round(e*1e3);let t=this.durationMs;return t>0?Math.round(t):-1}).filter(e=>e>=0)}get hasThumbnails(){return this.thumbnailTrack!==null}getThumbnail(e){return this.thumbnailTrack?.frameAt(e)??Promise.resolve(null)}attachAdContainer(e){if(this.adContainer=e,this.pendingAdConfig){let t=this.pendingAdConfig;this.pendingAdConfig=null,this.startAdsSession(t)}}notifyAdViewResize(e,t,i){this.adsProvider?.resize(e,t,i)}seekTo(e){let t=this.currentPositionMs;this.seekTargetMs=e,this.dispatch(i=>i.onSeekStarted?.(t,e)),this.emit({type:"Seek",fromMs:Math.round(t),toMs:Math.round(e)}),this.videoElement.currentTime=e/1e3}seekForward(){this.seekTo(Math.min(this.durationMs||1/0,this.currentPositionMs+this.opts.seekForwardIncrementMs))}seekBackward(){this.seekTo(Math.max(0,this.currentPositionMs-this.opts.seekBackwardIncrementMs))}seekToLiveEdge(){let e=this.videoElement.seekable;e.length>0&&this.seekTo(e.end(e.length-1)*1e3)}release(){this.resetAdSession(),this.teardownSource(),this.stopProgressTimer(),this.stopSnapshotTimer(),this.listeners.clear(),this.analyticsListeners.clear(),this.adListeners.clear(),this.videoElement.remove()}teardownSource(){this.detachDrm?.(),this.detachDrm=null,this.hls?.destroy(),this.hls=null;for(let[e,t]of this.nativeLoadListeners)this.videoElement.removeEventListener(e,t);this.nativeLoadListeners=[],this.videoElement.controls=!1,this.videoElement.removeAttribute("src"),[...this.videoElement.querySelectorAll("track")].forEach(e=>e.remove()),this.sideloadedDefaultId=null}get audioTracks(){if(this.hls)return this.hls.audioTracks.map((t,i)=>{let s=parseInt(String(t.channels??"2"),10)||2,a=!t.name||/^stream[_-]?\d+$/i.test(t.name)||t.name===t.lang?`${jg(t.lang??"")||`Audio ${i+1}`}${s>2?" (5.1)":""}`:t.name;return{id:`a${i}`,label:a,language:t.lang||"",channelCount:s,isSelected:this.hls.audioTrack===i}});let e=this.videoElement.audioTracks;if(e&&typeof e=="object"&&"length"in e){let t=e,i=[];for(let s=0;s<t.length;s++){let n=t[s];i.push({id:`a${s}`,label:n.label||n.language||`Audio ${s+1}`,language:n.language,channelCount:2,isSelected:n.enabled})}return i}return[]}selectAudioTrack(e){let t=parseInt(e.slice(1),10);if(this.hls){this.hls.audioTrack=t;return}let i=this.videoElement.audioTracks;if(i){let s=i;for(let n=0;n<s.length;n++)s[n].enabled=n===t}}get textTracks(){let e=[],t=this.videoElement.textTracks;for(let i=0;i<t.length;i++){let s=t[i];if(s.kind!=="subtitles"&&s.kind!=="captions")continue;let n=s.id?.startsWith("ext-");e.push({id:n?s.id:`t${i}`,label:s.label||s.language||`Subtitles ${i+1}`,language:s.language||"",isSelected:s.mode==="showing"})}return e}selectTextTrack(e){let t=this.videoElement.textTracks;for(let i=0;i<t.length;i++){let s=t[i];if(s.kind!=="subtitles"&&s.kind!=="captions")continue;let n=s.id?.startsWith("ext-")?s.id:`t${i}`;s.mode=e!==null&&n===e?"showing":"disabled"}if(this.hls&&e!==null&&e.startsWith("t")){let i=parseInt(e.slice(1),10),s=-1,n=-1,a=this.videoElement.textTracks;for(let o=0;o<=i&&o<a.length;o++){let l=a[o].kind;(l==="subtitles"||l==="captions")&&n++,o===i&&(s=n)}s>=0&&s<this.hls.subtitleTracks.length&&(this.hls.subtitleTrack=s)}else this.hls&&e===null&&(this.hls.subtitleTrack=-1)}get videoQualities(){if(!this.hls)return[];let e=this.hls.currentLevel,t=this.hls.autoLevelEnabled,i=this.hls.levels.map((s,n)=>({id:`q${n}`,width:s.width,height:s.height,bitrate:s.bitrate,isSelected:!t&&e===n}));return i.unshift({id:"auto",width:0,height:0,bitrate:0,isSelected:t}),i}selectVideoQuality(e){this.hls&&(this.hls.currentLevel=e==="auto"?-1:parseInt(e.slice(1),10))}get liveInfo(){let e=this.item?.streamType??"VOD";if(e==="VOD"||!this.item)return null;let t=this.videoElement.seekable;if(t.length===0)return null;let i=t.start(0),s=t.end(t.length-1),n=this.videoElement.currentTime,a=Math.max(0,s-n),o=Math.max(0,(s-i)*1e3),l=null,d=this.videoElement.getStartDate?.();return d&&!Number.isNaN(d.getTime())?l=d.getTime()+n*1e3:this.hls?.playingDate&&(l=this.hls.playingDate.getTime()),{streamType:e,dvrWindowMs:o,atLiveEdge:a<=Yg,latencyMs:Math.round(a*1e3),playheadWallClockMs:l}}setState(e){this.stateValue!==e&&(this.stateValue=e,this.dispatch(t=>t.onStateChanged?.(e)))}bindVideoEvents(){let e=this.videoElement,t=()=>this.breakResume!==null;e.addEventListener("waiting",()=>{t()||this.stateValue!=="IDLE"&&(this.setState("BUFFERING"),this.emit({type:"BufferStart"}))}),e.addEventListener("canplay",()=>{t()||(this.stateValue==="BUFFERING"&&(this.setState("READY"),this.emit({type:"BufferEnd"})),this.sawEncrypted&&!this.drmKeysAnnounced&&(this.drmKeysAnnounced=!0,this.emit({type:"DrmKeysLoaded"})))}),e.addEventListener("encrypted",()=>{this.sawEncrypted=!0}),e.addEventListener("playing",()=>{if(!t()){if(this.holdPlayback){e.pause();return}if(this.isPlayingAdFlag&&(this.hls!==null&&e.currentSrc.startsWith("blob:")||this.item!==null&&e.currentSrc===this.item.url)){e.pause();return}if(this.stateValue==="BUFFERING"&&(this.setState("READY"),this.emit({type:"BufferEnd"})),this.suppressAdBreakTransition){this.suppressAdBreakTransition=!1,this.didDispatchPause=!1;return}this.dispatch(i=>i.onIsPlayingChanged?.(!0)),this.startedOnce?this.didDispatchPause&&this.dispatch(i=>i.onResume?.()):(this.startedOnce=!0,this.dispatch(i=>i.onPlay?.())),this.didDispatchPause=!1,this.emit({type:"Play"})}}),e.addEventListener("pause",()=>{t()||e.ended||this.stateValue==="IDLE"||this.suppressAdBreakTransition||this.isPlayingAdFlag||(this.didDispatchPause=!0,this.dispatch(i=>i.onIsPlayingChanged?.(!1)),this.dispatch(i=>i.onPause?.()),this.emit({type:"Pause"}))}),e.addEventListener("seeked",()=>{if(t())return;let i=this.currentPositionMs;this.seekTargetMs=null,this.dispatch(s=>s.onSeekCompleted?.(i))}),e.addEventListener("ended",()=>{t()||this.wasEnded||(this.wasEnded=!0,this.setState("ENDED"),this.dispatch(i=>i.onPlaybackCompleted?.()),this.emit({type:"Complete"}),this.adsProvider?.contentDidComplete(),!this.isPlayingAdFlag&&this.adScheduleSettled?this.maybeAdvancePlaylist():(this.pendingPlaylistAdvanceAfterAds=!0,this.playlistAdvanceFallback!==null&&(clearTimeout(this.playlistAdvanceFallback),this.playlistAdvanceFallback=null),this.isPlayingAdFlag||(this.playlistAdvanceFallback=setTimeout(()=>{this.playlistAdvanceFallback=null,this.pendingPlaylistAdvanceAfterAds&&(this.pendingPlaylistAdvanceAfterAds=!1,this.maybeAdvancePlaylist())},8e3))))}),e.addEventListener("error",()=>{if(t()||this.hls)return;let i=Md(e.error);this.dispatch(s=>s.onError?.(i)),this.emit({type:"Error",error:i})})}bindHlsEvents(e){e.on(xt.Events.LEVEL_SWITCHED,(t,i)=>{let s=e.levels[i.level];!s||s.bitrate===this.lastBitrate||(this.lastBitrate=s.bitrate,this.emit({type:"BitrateChanged",bitrate:s.bitrate,width:s.width,height:s.height,frameRate:s.frameRate||0}))}),e.on(xt.Events.ERROR,(t,i)=>{let s=Od(i);i.fatal?(this.dispatch(n=>n.onError?.(s)),this.emit({type:"Error",error:s})):this.emit({type:"Error",error:s})})}attachSideloadedSubtitles(e){if((e.sideloadedSubtitles??[]).forEach((i,s)=>{let n=document.createElement("track");n.kind="subtitles",n.label=i.label,n.srclang=i.language,n.src=i.url,n.id=`ext-${s}`,this.videoElement.appendChild(n),i.isDefault&&(this.sideloadedDefaultId=`ext-${s}`),n.addEventListener("load",()=>{let a=n.track;a&&(a.mode=i.isDefault?"showing":"disabled")})}),this.sideloadedDefaultId){let i=this.sideloadedDefaultId,s=()=>this.selectTextTrack(i);this.videoElement.addEventListener("loadedmetadata",s,{once:!0}),this.nativeLoadListeners.push(["loadedmetadata",s])}}startProgressTimer(){this.stopProgressTimer(),this.progressTimer=window.setInterval(()=>{if(this.stateValue==="IDLE")return;this.stateValue==="READY"&&(this.lastStablePositionMs=Math.round(this.currentPositionMs)),this.dispatch(t=>t.onProgress?.(Math.round(this.currentPositionMs),Math.round(this.bufferedPositionMs),Math.round(this.durationMs)));let e=this.liveInfo;e&&e.atLiveEdge!==this.atLiveEdgeValue&&(this.atLiveEdgeValue=e.atLiveEdge,this.dispatch(t=>t.onLiveEdgeChanged?.(e.atLiveEdge)))},this.opts.progressUpdateIntervalMs)}stopProgressTimer(){this.progressTimer!==null&&(clearInterval(this.progressTimer),this.progressTimer=null)}startSnapshotTimer(){this.stopSnapshotTimer(),this.snapshotTimer=window.setInterval(()=>{if(this.stateValue==="IDLE"||!this.isPlaying)return;let e=this.videoElement.getVideoPlaybackQuality?.(),t=e?.droppedVideoFrames??0;t>this.lastDroppedTotal&&this.emit({type:"DroppedFrames",count:t-this.lastDroppedTotal,elapsedMs:1e4}),this.lastDroppedTotal=t,this.emit({type:"QualitySnapshot",positionMs:Math.round(this.currentPositionMs),bufferedMs:Math.round(this.bufferedPositionMs),bandwidthEstimateBps:Math.round(this.hls?.bandwidthEstimate??0),droppedFramesTotal:e?.droppedVideoFrames??0})},1e4)}stopSnapshotTimer(){this.snapshotTimer!==null&&(clearInterval(this.snapshotTimer),this.snapshotTimer=null)}};function Ai(r){let e=r;return typeof e.serverUrl=="string"&&typeof e.networkId=="number"&&typeof e.profile=="string"&&typeof e.videoAssetId=="string"}function la(r){let e=()=>String(Math.floor(Math.random()*1e9)),t=new URLSearchParams({nw:String(r.networkId),prof:r.profile,csid:r.siteSectionId,caid:r.videoAssetId,vdur:String(Math.round(r.videoDurationMs/1e3)),resp:"vmap1 vast4",pvrn:e(),vprn:e(),...r.globalParameters});return`${r.serverUrl.replace(/\/$/,"")}/ad/g/1?${t.toString()}`}var Vd=null;async function Hd(r){let e=async i=>{try{return await fetch(i,{mode:"no-cors",cache:"no-store"}),!0}catch{return!1}},t=[e("https://imasdk.googleapis.com/js/sdkloader/ima3.js"),e("https://pubads.g.doubleclick.net/gampad/ads?ad_type=probe")];if(r)try{let i=new URL(r).origin;i!=="https://pubads.g.doubleclick.net"&&t.push(e(i+"/"))}catch{}return(await Promise.all(t)).some(i=>!i)}function zg(){return window.google?.ima?Promise.resolve(window.google.ima):(Vd??=new Promise((r,e)=>{let t=document.createElement("script");t.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",t.async=!0,t.onload=()=>{let i=window.google?.ima;i?r(i):e(new Error("IMA SDK loaded but google.ima missing"))},t.onerror=()=>e(new Error("failed to load the IMA SDK (blocked by an ad blocker?)")),document.head.appendChild(t)}),Vd)}var da=class{constructor(e={}){this.options=e}video=null;container=null;callbacks=null;ima=null;adDisplayContainer=null;adsLoader=null;adsManager=null;lastAd=null;lastBreakType=null;tagUrl=null;autostart=!0;started=!1;destroyed=!1;requestGeneration=0;verdictTimer=null;gotVerdict=!1;attach(e,t,i){this.video=e,this.container=t,this.callbacks=i}requestAds(e,t){this.autostart=t;let i=Ai(e)?la(e):e.adTagUri;if(typeof i!="string"||!i){this.callbacks?.onAdError({code:900,phase:"LOAD",message:"ImaAdsProvider needs an AdTagConfig with adTagUri"}),this.callbacks?.onContentResumeRequested();return}this.tagUrl=i;let s=++this.requestGeneration;this.gotVerdict=!1,this.verdictTimer!==null&&clearTimeout(this.verdictTimer),this.verdictTimer=window.setTimeout(()=>{this.destroyed||this.gotVerdict||s!==this.requestGeneration||Hd(this.tagUrl??void 0).then(n=>{this.destroyed||this.gotVerdict||(this.gotVerdict=!0,this.callbacks?.onAdError(n?{code:902,phase:"LOAD",message:"ads blocked by the browser (ad blocker detected)"}:{code:901,phase:"LOAD",message:"ad request produced no response in time"}),this.callbacks?.onContentResumeRequested())})},6e3),zg().then(n=>{this.destroyed||s!==this.requestGeneration||(this.ima=n,this.startSession(n,i))}).catch(n=>{this.settleVerdict(),this.callbacks?.onAdError({code:902,phase:"LOAD",message:n.message}),this.callbacks?.onContentResumeRequested()})}settleVerdict(){this.gotVerdict=!0,this.verdictTimer!==null&&(clearTimeout(this.verdictTimer),this.verdictTimer=null)}startSession(e,t){let i=this.video,s=this.container,n=this.options.vpaidMode??"enabled";e.settings.setVpaidMode(n==="insecure"?e.ImaSdkSettings.VpaidMode.INSECURE:n==="disabled"?e.ImaSdkSettings.VpaidMode.DISABLED:e.ImaSdkSettings.VpaidMode.ENABLED),this.adDisplayContainer??=new e.AdDisplayContainer(s,i),this.adDisplayContainer.initialize(),this.adsLoader?.destroy();let a=new e.AdsLoader(this.adDisplayContainer);this.adsLoader=a,a.addEventListener(e.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,d=>{this.settleVerdict();let c=new e.AdsRenderingSettings;c.uiElements=[],c.restoreCustomPlaybackStateOnAdBreakComplete=!0;let h=d.getAdsManager(i,c);this.adsManager=h,this.bindManager(e,h),this.callbacks?.onAdCuePoints(h.getCuePoints());let u=s.getBoundingClientRect();h.init(u.width,u.height,e.ViewMode.NORMAL),this.autostart&&(this.started=!0,h.start())}),a.addEventListener(e.AdErrorEvent.Type.AD_ERROR,d=>{this.settleVerdict();let c=d.getError();this.callbacks?.onAdError({code:c.getErrorCode(),phase:"LOAD",message:c.getMessage()}),this.callbacks?.onContentResumeRequested(),this.maybeFlagAdBlock()});let o=new e.AdsRequest;o.adTagUrl=t,o.setAdWillAutoPlay(this.autostart),o.setAdWillPlayMuted(i.muted);let l=s.getBoundingClientRect();o.linearAdSlotWidth=Math.round(l.width)||640,o.linearAdSlotHeight=Math.round(l.height)||360,o.nonLinearAdSlotWidth=Math.round(l.width)||640,o.nonLinearAdSlotHeight=150,a.requestAds(o)}bindManager(e,t){let i=e.AdEvent.Type,s=()=>this.callbacks,n=()=>{if(!this.lastBreakType)return;let a=this.lastBreakType;this.lastBreakType=null,s()?.onAdBreakCompleted(a)};t.addEventListener(i.CONTENT_PAUSE_REQUESTED,()=>s()?.onContentPauseRequested()),t.addEventListener(i.CONTENT_RESUME_REQUESTED,()=>{n(),s()?.onContentResumeRequested()}),t.addEventListener(i.STARTED,a=>{let o=a.getAd();if(!o)return;let l=o.getAdPodInfo(),d=l.getPodIndex()===0?"PREROLL":l.getPodIndex()===-1?"POSTROLL":"MIDROLL",c=o.getSkipTimeOffset()>=0,h={adId:o.getAdId(),positionInPod:l.getAdPosition(),podSize:l.getTotalAds(),breakType:d,isSkippable:c,skipOffsetMs:c?Math.round(o.getSkipTimeOffset()*1e3):-1,durationMs:Math.round(o.getDuration()*1e3),providerRendersUi:!0};this.lastAd=h,this.lastBreakType=d,h.positionInPod===1&&s()?.onAdBreakStarted(d,h.podSize),s()?.onAdStarted(h)}),t.addEventListener(i.AD_PROGRESS,a=>{let o=a.getAdData();this.lastAd&&o?.duration&&s()?.onAdProgress(this.lastAd,Math.round((o.currentTime??0)*1e3),Math.round(o.duration*1e3))}),t.addEventListener(i.PAUSED,()=>{this.lastAd&&s()?.onAdPaused(this.lastAd)}),t.addEventListener(i.RESUMED,()=>{this.lastAd&&s()?.onAdResumed(this.lastAd)}),t.addEventListener(i.SKIPPED,()=>{this.lastAd&&s()?.onAdSkipped(this.lastAd)}),t.addEventListener(i.COMPLETE,()=>{this.lastAd&&s()?.onAdCompleted(this.lastAd)}),i.AD_BREAK_ENDED&&t.addEventListener(i.AD_BREAK_ENDED,n),t.addEventListener(i.ALL_ADS_COMPLETED,()=>{n(),this.lastAd=null,s()?.onAllAdsCompleted?.()}),t.addEventListener(e.AdErrorEvent.Type.AD_ERROR,a=>{let o=a.getError();s()?.onAdError({code:o.getErrorCode(),phase:"PLAY",message:o.getMessage()}),s()?.onContentResumeRequested(),this.maybeFlagAdBlock()})}adBlockFlagged=!1;maybeFlagAdBlock(){this.adBlockFlagged||Hd(this.tagUrl??void 0).then(e=>{e&&!this.adBlockFlagged&&!this.destroyed&&(this.adBlockFlagged=!0,this.callbacks?.onAdError({code:902,phase:"LOAD",message:"ads blocked by the browser (ad blocker detected)"}))})}startPendingBreak(){return!this.adsManager||this.started?!1:(this.started=!0,this.adsManager.start(),!0)}contentDidComplete(){this.adsLoader?.contentComplete()}pause(){this.adsManager?.pause()}resume(){this.adsManager?.resume()}skip(){this.adsManager?.skip()}click(){}resize(e,t,i){this.ima&&this.adsManager&&this.adsManager.resize(e,t,i?this.ima.ViewMode.FULLSCREEN:this.ima.ViewMode.NORMAL)}destroy(){this.requestGeneration++,this.verdictTimer!==null&&(clearTimeout(this.verdictTimer),this.verdictTimer=null),this.adsManager?.destroy(),this.adsManager=null,this.adsLoader?.destroy(),this.adsLoader=null,this.adDisplayContainer?.destroy(),this.adDisplayContainer=null,this.lastAd=null,this.lastBreakType=null,this.autostart=!0,this.started=!1}};var Xg="https://mssl.fwmrm.net/libs/adm/7.5.0/AdManager.js",ca=null;function Qg(r){return window.tv?.freewheel?.SDK?Promise.resolve(window.tv.freewheel.SDK):(ca??=new Promise((e,t)=>{let i=document.createElement("script");i.src=r,i.async=!0,i.onload=()=>{let s=window.tv?.freewheel?.SDK;s?e(s):t(new Error("AdManager.js loaded but tv.freewheel.SDK missing"))},i.onerror=()=>{ca=null,t(new Error("failed to load FreeWheel AdManager.js (blocked by an ad blocker?)"))},document.head.appendChild(i)}),ca)}var ha=class{constructor(e={}){this.options=e}usesContentVideoElement=!0;video=null;container=null;callbacks=null;sdk=null;context=null;cfg=null;generation=0;destroyed=!1;prerollSlots=[];midrollSlots=[];postrollSlots=[];catchUpQueue=[];flow="PREROLLS";contentGateOpened=!1;pendingStart=!1;currentSlot=null;currentBreakType=null;currentAd=null;currentInstance=null;adIndexInSlot=0;totalAdsInSlot=0;requestTimer=null;watchdogTimer=null;progressTimer=null;lastContentPosMs=0;videoListeners=[];attach(e,t,i){this.video=e,this.container=t,this.callbacks=i}requestAds(e,t){if(!Ai(e)){this.callbacks?.onAdError({code:900,phase:"LOAD",message:"FreewheelAdsProvider needs a FreewheelConfig"}),this.callbacks?.onContentResumeRequested();return}this.cfg=e,this.pendingStart=!t;let i=++this.generation,s=e.requestTimeoutMs??5e3;this.requestTimer=window.setTimeout(()=>{this.destroyed||i!==this.generation||this.fail({code:901,phase:"LOAD",message:"FreeWheel request produced no response in time"})},s+2e3),Qg(this.options.adManagerUrl??Xg).then(n=>{this.destroyed||i!==this.generation||(this.sdk=n,this.submitRequest(n,e))}).catch(n=>{this.destroyed||i!==this.generation||this.fail({code:902,phase:"LOAD",message:n.message})})}submitRequest(e,t){let i=this.video,s=this.container;if(!i||!s)return;if(!i.parentNode){this.fail({code:900,phase:"LOAD",message:"FreewheelAdsProvider needs the video element mounted in the DOM"});return}let n=new e.AdManager;n.setNetwork(t.networkId),n.setServer(t.serverUrl.replace(/\/$/,"")+"/ad/g/1");let a=n.newContext();this.context=a,a.setProfile(t.profile),a.setSiteSection(t.siteSectionId,t.networkId),a.setVideoAsset(t.videoAssetId,t.videoDurationMs/1e3,t.networkId),a.setContentVideoElement?.(i);for(let[l,d]of Object.entries(t.globalParameters??{}))a.addKeyValue(l,d),(l.startsWith("_fw_")||l.includes("."))&&a.setParameter(l,d,e.PARAMETER_LEVEL_GLOBAL);let o=()=>String(Math.floor(Math.random()*1e9));a.addKeyValue("pvrn",o()),a.addKeyValue("vprn",o()),a.setParameter("renderer.video.timeoutMillisecondsBeforeStart",String(t.adStartTimeoutMs??1e4),e.PARAMETER_LEVEL_GLOBAL),a.addEventListener(e.EVENT_REQUEST_COMPLETE,l=>this.onRequestComplete(l)),a.addEventListener(e.EVENT_SLOT_ENDED,l=>this.onSlotEnded(l)),a.addEventListener(e.EVENT_AD_IMPRESSION,l=>this.onAdImpression(l)),e.EVENT_AD_PAUSE&&a.addEventListener(e.EVENT_AD_PAUSE,()=>{this.currentAd&&this.callbacks?.onAdPaused(this.currentAd)}),e.EVENT_AD_RESUME&&a.addEventListener(e.EVENT_AD_RESUME,()=>{this.currentAd&&this.callbacks?.onAdResumed(this.currentAd)}),e.EVENT_ERROR&&a.addEventListener(e.EVENT_ERROR,l=>{this.callbacks?.onAdError({code:301,phase:"PLAY",message:`FreeWheel error: ${JSON.stringify(l.errorInfo??l.type??"unknown")}`})}),this.bindContentWatchers(i),a.submitRequest()}onRequestComplete(e){if(this.requestTimer!==null&&(clearTimeout(this.requestTimer),this.requestTimer=null),this.destroyed)return;if(e.success===!1){this.fail({code:300,phase:"LOAD",message:"FreeWheel request failed"});return}let t=this.sdk,i=this.context;if(!t||!i)return;let s=o=>(o.getAdInstances?.()?.length??1)>0,n=i.getTemporalSlots().filter(s),a=o=>n.filter(l=>o!==void 0&&l.getTimePositionClass()===o);this.prerollSlots=a(t.TIME_POSITION_CLASS_PREROLL),this.postrollSlots=a(t.TIME_POSITION_CLASS_POSTROLL),this.midrollSlots=[...a(t.TIME_POSITION_CLASS_MIDROLL),...a(t.TIME_POSITION_CLASS_OVERLAY)].sort((o,l)=>o.getTimePosition()-l.getTimePosition()),this.publishCuePoints(),!this.pendingStart&&this.playNextPreroll()}publishCuePoints(){let e=this.midrollSlots.map(t=>t.getTimePosition());(this.prerollSlots.length||this.currentBreakType==="PREROLL")&&e.unshift(0),this.postrollSlots.length&&e.push(-1),this.callbacks?.onAdCuePoints(e)}playNextPreroll(){let e=this.prerollSlots.shift();if(!e){this.flow="CONTENT",this.openContentGateOnce();return}this.flow="PREROLLS",this.playSlot(e,"PREROLL")}openContentGateOnce(){this.contentGateOpened||(this.contentGateOpened=!0,this.callbacks?.onContentResumeRequested())}playSlot(e,t){this.currentSlot=e,this.currentBreakType=t,this.adIndexInSlot=0,this.totalAdsInSlot=e.getAdInstances?.()?.length??0,this.armWatchdog(e),this.callbacks?.onContentPauseRequested(),this.callbacks?.onAdBreakStarted(t,this.totalAdsInSlot),e.play()}onSlotEnded(e){let t=this.currentSlot;if(!t||e.slot&&e.slot.getCustomId()!==t.getCustomId())return;this.cancelWatchdog(),this.stopProgressTicker(),this.currentAd&&this.callbacks?.onAdCompleted(this.currentAd),this.currentAd=null,this.currentInstance=null,this.currentSlot=null;let i=this.currentBreakType;switch(this.currentBreakType=null,this.video&&(this.video.controls=!1),i&&this.callbacks?.onAdBreakCompleted(i),this.flow){case"PREROLLS":this.playNextPreroll();break;case"MIDROLL":this.flow="CONTENT",this.callbacks?.onContentResumeRequested();break;case"CATCH_UP":{let s=this.catchUpQueue.shift();s?this.playSlot(s,"MIDROLL"):(this.flow="CONTENT",this.callbacks?.onContentResumeRequested());break}case"POSTROLLS":this.playNextPostroll();break;default:break}}onAdImpression(e){let t=this.currentSlot,i=this.currentBreakType;if(!t||!i)return;this.cancelWatchdog(),this.currentAd&&this.callbacks?.onAdCompleted(this.currentAd),this.adIndexInSlot++;let s=e.adInstance??t.getAdInstances?.()?.[this.adIndexInSlot-1]??null,n=l=>l!==void 0&&l>=1&&l<=600?l*1e3:null,a=n(s?.getActiveCreativeRendition?.()?.getDuration?.())??n(s?.getDuration?.())??this.cfg?.fallbackAdDurationMs??15e3,o={adId:String(s?.getAdId?.()??`fw-${this.adIndexInSlot}`),positionInPod:this.adIndexInSlot,podSize:Math.max(this.totalAdsInSlot,this.adIndexInSlot),breakType:i,isSkippable:!1,skipOffsetMs:-1,durationMs:a,providerRendersUi:!0};this.currentAd=o,this.currentInstance=s,this.callbacks?.onAdStarted(o),this.startProgressTicker(o,t,a)}bindContentWatchers(e){this.unbindContentWatchers();let t=(s,n)=>{e.addEventListener(s,n),this.videoListeners.push([s,n])},i=0;t("timeupdate",()=>{let s=e.currentTime*1e3;if(e.seeking||(this.lastContentPosMs=s),this.flow!=="CONTENT"||this.currentSlot)return;let n=this.cfg?.midrollToleranceMs??1e3,a=this.midrollSlots.find(o=>Math.abs(o.getTimePosition()*1e3-s)<=n);a&&(this.midrollSlots=this.midrollSlots.filter(o=>o!==a),this.publishCuePoints(),this.flow="MIDROLL",this.playSlot(a,"MIDROLL"))}),t("seeking",()=>{i=this.lastContentPosMs}),t("seeked",()=>{if(this.flow!=="CONTENT"||this.currentSlot)return;let s=e.currentTime*1e3;if(Math.abs(s-i)<(this.cfg?.seekThresholdMs??2e3))return;let n=Math.min(i,s),a=Math.max(i,s),o=this.midrollSlots.filter(c=>{let h=c.getTimePosition()*1e3;return h>n&&h<=a});if(!o.length)return;this.midrollSlots=this.midrollSlots.filter(c=>!o.includes(c)),this.publishCuePoints();let l=this.cfg?.seekCatchUpPolicy??"MOST_RECENT";if(l==="NONE")return;let d=[...o].sort((c,h)=>h.getTimePosition()-c.getTimePosition());this.catchUpQueue=l==="MOST_RECENT"?[d[0]]:d,this.flow="CATCH_UP",this.playSlot(this.catchUpQueue.shift(),"MIDROLL")}),t("play",()=>{!this.currentSlot&&this.sdk?.VIDEO_STATE_PLAYING!==void 0&&this.context?.setVideoState?.(this.sdk.VIDEO_STATE_PLAYING)}),t("pause",()=>{!this.currentSlot&&this.sdk?.VIDEO_STATE_PAUSED!==void 0&&this.context?.setVideoState?.(this.sdk.VIDEO_STATE_PAUSED)})}unbindContentWatchers(){let e=this.video;e&&this.videoListeners.forEach(([t,i])=>e.removeEventListener(t,i)),this.videoListeners=[]}contentDidComplete(){this.destroyed||this.flow==="DONE"||(this.sdk?.VIDEO_STATE_COMPLETED!==void 0&&this.context?.setVideoState?.(this.sdk.VIDEO_STATE_COMPLETED),this.flow="POSTROLLS",this.playNextPostroll())}playNextPostroll(){let e=this.postrollSlots.shift();if(!e){this.flow="DONE",this.callbacks?.onAllAdsCompleted?.(),this.callbacks?.onContentResumeRequested();return}this.playSlot(e,"POSTROLL")}armWatchdog(e){this.cancelWatchdog();let t=(this.cfg?.adStartTimeoutMs??1e4)+2e3;this.watchdogTimer=window.setTimeout(()=>{this.destroyed||this.currentSlot!==e||this.currentAd||this.abandonSlot(e,`no ad rendered within ${t}ms`)},t)}cancelWatchdog(){this.watchdogTimer!==null&&(clearTimeout(this.watchdogTimer),this.watchdogTimer=null)}abandonSlot(e,t){this.callbacks?.onAdError({code:301,phase:"PLAY",message:`slot abandoned: ${t}`});try{e.stop?.()}catch{}window.setTimeout(()=>{this.currentSlot===e&&this.onSlotEnded({slot:e})},500)}startProgressTicker(e,t,i){this.stopProgressTicker();let s=performance.now();this.progressTimer=window.setInterval(()=>{if(this.destroyed||this.currentAd!==e){this.stopProgressTicker();return}let n=t.getPlayheadTime?.(),a=n!==void 0&&n>=0?n*1e3:performance.now()-s;this.callbacks?.onAdProgress(e,Math.min(a,i),i)},300)}stopProgressTicker(){this.progressTimer!==null&&(clearInterval(this.progressTimer),this.progressTimer=null)}startPendingBreak(){return!this.pendingStart||(this.pendingStart=!1,!this.prerollSlots.length)?!1:(this.playNextPreroll(),!0)}pause(){this.currentSlot?.pause?.()}resume(){this.currentSlot?.resume?.()}skip(){this.currentInstance?.getRendererController?.()?.skipCurrentAd?.()}click(){}resize(){}fail(e){this.callbacks?.onAdError(e),this.flow="CONTENT",this.openContentGateOnce()}destroy(){this.generation++,this.requestTimer!==null&&(clearTimeout(this.requestTimer),this.requestTimer=null),this.cancelWatchdog(),this.stopProgressTicker(),this.unbindContentWatchers();try{this.currentSlot?.stop?.()}catch{}try{this.context?.dispose?.()}catch{}this.context=null,this.video&&(this.video.controls=!1),this.cfg=null,this.prerollSlots=[],this.midrollSlots=[],this.postrollSlots=[],this.catchUpQueue=[],this.currentSlot=null,this.currentBreakType=null,this.currentAd=null,this.currentInstance=null,this.flow="PREROLLS",this.contentGateOpened=!1,this.pendingStart=!1}};var ws={foreground:"#FFFFFF",foregroundMuted:"rgba(255,255,255,0.70)",foregroundFaint:"rgba(255,255,255,0.38)",trackPlayed:"#FFFFFF",trackBuffered:"rgba(255,255,255,0.38)",trackRemaining:"rgba(255,255,255,0.22)",thumb:"#FFFFFF",thumbHalo:"rgba(255,255,255,0.20)",pressed:"rgba(255,255,255,0.12)",liveEdge:"#F2453E",liveBehind:"rgba(255,255,255,0.60)",adAccent:"#F6C445",menuSurface:"rgba(23,24,26,0.94)",menuSelected:"rgba(255,255,255,0.10)",menuBorder:"rgba(255,255,255,0.10)",chipSurface:"rgba(0,0,0,0.55)"},xi={trackHeight:3,trackHeightActive:5,thumbSize:12,thumbSizeActive:18,thumbHaloSize:34,scrubTouchHeight:48,iconSize:24,playButtonSize:56,playGlyphSize:28,seekButtonSize:48,seekGlyphSize:24,clusterGap:20,bottomBarHeight:48,edgeInset:12,bottomScrimHeight:140,topScrimHeight:96,menuMinWidth:224,menuMaxWidth:320,menuItemHeight:48,menuCorner:14,chipHeight:24,adCueMarkerSize:6},Ms={...xi,bottomBarHeight:56,edgeInset:24};var Zg={play:{fills:["M8.5 6.5 18 12 8.5 17.5Z"]},pause:{fills:["M8.3 5.5 L9.3 5.5 A1.3 1.3 0 0 1 10.6 6.8 L10.6 17.2 A1.3 1.3 0 0 1 9.3 18.5 L8.3 18.5 A1.3 1.3 0 0 1 7 17.2 L7 6.8 A1.3 1.3 0 0 1 8.3 5.5 Z","M14.7 5.5 L15.7 5.5 A1.3 1.3 0 0 1 17 6.8 L17 17.2 A1.3 1.3 0 0 1 15.7 18.5 L14.7 18.5 A1.3 1.3 0 0 1 13.4 17.2 L13.4 6.8 A1.3 1.3 0 0 1 14.7 5.5 Z"]},replay:{strokes:["M20 12a8 8 0 1 1-2.34-5.66","M13.6 6.6 17.66 6.34 17.9 2.3"]},seekBack:{strokes:["M16.36 6.37A7.6 7.6 0 1 1 7.64 6.37","M11.7 6.1 7.64 6.37 7.9 2.3"]},seekForward:{strokes:["M7.64 6.37A7.6 7.6 0 1 0 16.36 6.37","M12.3 6.1 16.36 6.37 16.1 2.3"]},volumeOn:{fills:["M4 9h3.2l4.4-3.6a1 1 0 0 1 1.6.8v11.6a1 1 0 0 1-1.6.8L7.2 15H4a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1z"],strokes:["M16.6 9.4a3.6 3.6 0 0 1 0 5.2","M19.2 7a7.2 7.2 0 0 1 0 10"]},volumeMute:{fills:["M4 9h3.2l4.4-3.6a1 1 0 0 1 1.6.8v11.6a1 1 0 0 1-1.6.8L7.2 15H4a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1z"],strokes:["m16.6 9.6 5 4.8","m21.6 9.6-5 4.8"]},speed:{strokes:["M4.2 17.5a9 9 0 0 1 15.6 0","M12 13.2 16.4 9.3"]},quality:{strokes:["M3 7.5h5","M12.2 7.5H21","M8.0 7.5 a2.1 2.1 0 1 0 4.2 0 a2.1 2.1 0 1 0 -4.2 0 Z","M3 16.5h8.8","M16 16.5H21","M11.8 16.5 a2.1 2.1 0 1 0 4.2 0 a2.1 2.1 0 1 0 -4.2 0 Z"]},audioTrack:{strokes:["M9 17.5V7l10-2v10.5","M9 17.5a2.4 2.4 0 1 1-4.8 0a2.4 2.4 0 1 1 4.8 0z","M19 15.5a2.4 2.4 0 1 1-4.8 0a2.4 2.4 0 1 1 4.8 0z"]},subtitles:{strokes:["M5.5 5 L18.5 5 A2.5 2.5 0 0 1 21 7.5 L21 16.5 A2.5 2.5 0 0 1 18.5 19 L5.5 19 A2.5 2.5 0 0 1 3 16.5 L3 7.5 A2.5 2.5 0 0 1 5.5 5 Z","M7.5 10.5h9","M7.5 14.5h5"]},fullscreenEnter:{strokes:["M9 4H4v5","M15 4h5v5","M15 20h5v-5","M9 20H4v-5"]},fullscreenExit:{strokes:["M3.5 8.5h5v-5","M20.5 8.5h-5v-5","M20.5 15.5h-5v5","M3.5 15.5h5v5"]},check:{strokes:["M5 12.6 9.8 17.4 19 7.2"]}};function Ot(r,e,t,i=1.8){let s=Zg[r];if(!s)return"";let n=(s.strokes??[]).map(o=>`<path d="${o}" fill="none" stroke="${t}" stroke-width="${i}" stroke-linecap="round" stroke-linejoin="round"/>`).join(""),a=(s.fills??[]).map(o=>`<path d="${o}" fill="${t}"/>`).join("");return`<svg width="${e}" height="${e}" viewBox="0 0 24 24" aria-hidden="true">${a}${n}</svg>`}function Os(r,e,t){return`<svg width="${r}" height="${r}" viewBox="0 0 32 32" aria-hidden="true">
38
+ `),d=[],c=e?xu(e.baseTime,e.timescale):0,h="00:00.000",u=0,f=0,g=!1,m,p=!0;o.oncue=function(v){let T=t[i],E=t.ccOffset,S=(u-c)/9e4;if(g){if(T!=null&&T.new&&(E=t.ccOffset=T.start),S){if(!e){m=new Error(Do+"MPEGTS");return}E=S-t.presentationOffset}}else if(e)E=-e.baseTime/e.timescale;else{m=new Error(Do+"without X-TIMESTAMP-MAP");return}let b=v.endTime-v.startTime,A=Ve((v.startTime+E-f)*9e4,s*9e4)/9e4;v.startTime=Math.max(A,0),v.endTime=Math.max(A+b,0);let x=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(x)),v.id?i&&(v.id=`hlsjscc${i}_${v.id}`):v.id=aa(v.startTime,v.endTime,x),v.endTime>0&&d.push(v)},o.onparsingerror=function(v){m=v},o.onflush=function(){if(m){a(m);return}n(d)},l.forEach(v=>{if(p)if(v.startsWith("X-TIMESTAMP-MAP=")){p=!1,g=!0,v.slice(16).split(",").forEach(T=>{T.startsWith("LOCAL:")?h=T.slice(6):T.startsWith("MPEGTS:")&&(u=parseInt(T.slice(7)))});try{f=Xf(h)/1e3}catch(T){m=T}return}else v===""&&(p=!1);o.parse(v+`
39
+ `)}),o.flush()}var hr="stpp.ttml.im1t",Rd=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Pd=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Zf={left:"start",center:"center",right:"end",start:"start",end:"end"};function Co(r,e,t,i){let s=Q(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=s.map(o=>He(o)),a=Au(e.baseTime,1,e.timescale);try{n.forEach(o=>t(Jf(o,a)))}catch(o){i(o)}}function Jf(r,e){let s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((h,u)=>(h[u]=s.getAttribute(`ttp:${u}`)||n[u],h),{}),o=s.getAttribute("xml:space")!=="preserve",l=wo(ln(s,"styling","style")),d=wo(ln(s,"layout","region")),c=ln(s,"body","[begin]");return[].map.call(c,h=>{let u=_d(h,o);if(!u||!h.hasAttribute("begin"))return null;let f=cn(h.getAttribute("begin"),a),g=cn(h.getAttribute("dur"),a),m=cn(h.getAttribute("end"),a);if(f===null)throw Mo(h);if(m===null){if(g===null)throw Mo(h);m=f+g}let p=new ra(f-e,m-e,u);p.id=aa(p.startTime,p.endTime,p.text);let v=d[h.getAttribute("region")],T=l[h.getAttribute("style")],E=eg(v,T,l),{textAlign:S}=E;if(S){let b=Zf[S];b&&(p.lineAlign=b),p.align=S}return ce(p,E),p}).filter(h=>h!==null)}function ln(r,e,t){let i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function wo(r){return r.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function _d(r,e){return[].slice.call(r.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+`
40
+ `:(n=i.childNodes)!=null&&n.length?_d(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function eg(r,e,t){let i="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,l)=>{let d=dn(e,i,l)||dn(r,i,l)||dn(s,i,l);return d&&(o[l]=d),o},{})}function dn(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Mo(r){return new Error(`Could not parse ttml timestamp ${r}`)}function cn(r,e){if(!r)return null;let t=xd(r);return t===null&&(Rd.test(r)?t=tg(r,e):Pd.test(r)&&(t=ig(r,e))),t}function tg(r,e){let t=Rd.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function ig(r,e){let t=Pd.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}function oa(r,e,t,i="",s="disabled"){let n=r.ownerDocument.createElement("track");return n.kind=e,n.label=t,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=s,r.appendChild(n),n}function sg(r){return r.forced&&Yc()?"forced":r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function ur(r,e){let t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){oe.debug(`[texttrack-utils]: ${i}`);try{let s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,r.addCue(s)}catch(s){oe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}t==="disabled"&&(r.mode=t)}function fr(r,e,t,i){let s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){let n=rg(r.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&r.removeCue(n[a])}s==="disabled"&&(r.mode=s)}function ng(r,e){if(e<=r[0].startTime)return 0;let t=r.length-1;if(e>r[t].endTime)return-1;let i=0,s=t,n;for(;i<=s;)if(n=Math.floor((s+i)/2),e<r[n].startTime)s=n-1;else if(e>r[n].startTime&&i<t)i=n+1;else return n;return r[i].startTime-e<e-r[s].startTime?i:s}function rg(r,e,t){let i=[],s=ng(r,e);if(s>-1)for(let n=s,a=r.length;n<a;n++){let o=r[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}var gr=class extends Ei{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,i=!1;if(this.currentTrack){var s;let o=(s=this.currentTrack.trackNode)==null?void 0:s.track.mode;o==="showing"?(t=this.trackId,i=!0):o==="hidden"&&(t=this.trackId)}if(!i)for(let o=0;o<this.tracksInGroup.length;o++){var n;let l=(n=this.tracksInGroup[o].trackNode)==null?void 0:n.track.mode;if(l==="showing"){t=o;break}else t<0&&l==="hidden"&&(t=o)}if(t>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[t].trackNode)==null?void 0:a.track.mode)==="showing"}this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(i=>{i.trackNode||(i.trackNode=oa(this.media,sg(i),i.name,i.lang))});let t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;t?.mode==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){let i=t.media;this.media=i;let s=this.trackId;this.queuedDefaultTrack>-1&&(s=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(s),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let i=this.media;if(!i)return;let s=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!s&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(n=>{let a=n.trackNode;a&&(a.track.mode="hidden",a.remove(),n.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:s,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,s=this.groupIds,n=this.currentTrack;if(!i||s?.length!==i?.length||i!=null&&i.some(a=>s?.indexOf(a)===-1)){this.groupIds=i;let a=[];if(this.tracks.forEach(c=>{(c.textCodec===hr?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(c.groupId)>-1?(c.id=a.length,a.push(c)):c.trackNode&&(c.trackNode.remove(),c.trackNode=void 0))}),a.length===this.tracksInGroup.length){let c=!1;for(let h=0;h<a.length;h++)if(a[h]!==this.tracksInGroup[h]){c=!0;break}if(!c)return}a.length&&this.selectDefaultTrack&&!a.some(c=>c.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;let c=ot(o,a);if(c>-1)n=a[c];else{let h=ot(o,this.tracks);n=this.tracks[h]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,d),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){let n=t[s];if(!(i&&!n.default||!i&&!e)&&(!e||kt(n,e)))return s}if(e){for(let s=0;s<t.length;s++){let n=t[s];if(Ti(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){let n=t[s];if(Ti(e.attrs,n.attrs,["LANGUAGE"]))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===te.SUBTITLE_TRACK&&t.context.id===this.trackId&&ui(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let i=this.currentTrack;if(i&&kt(e,i))return i;let s=ot(e,this.tracksInGroup);if(s>-1){let n=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),n}else{if(i)return null;{let n=ot(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,s=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(y.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;let e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){let i=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",s=t.trackNode.track;s.mode!==i&&(s.mode=i)}})}setSubtitleTrack(e,t=!1){let i=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=i.length||!B(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let s=this.currentTrack,n=i[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),!n){s&&this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:e});return}let a=!!n.details&&!n.details.live;if(n===s&&a)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));let{id:o,groupId:l="",name:d,type:c,url:h}=n;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:d,type:c,url:h});let u=this.switchParams(n.url,s?.details,n.details);this.loadPlaylist(u)}},Wi=2,ag=100,mr=class extends ss{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(ag),this.mediaSource=t.mediaSource;let i=this.media=t.media;de(i,"playing",this.onMediaPlaying),de(i,"waiting",this.onMediaWaiting),de(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(le(i,"playing",this.onMediaPlaying),le(i,"waiting",this.onMediaWaiting),le(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;let t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var i,s;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,c=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(c){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}));return}if(!J.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}let h=J.bufferInfo(a,e,0),u=this.fragmentTracker;u&&this.hls&&No(h,e,u,this.hls);let f=h.nextStart||0;if(o&&u&&this.hls){let A=Oo(this.hls.inFlightFragments,e),x=h.len>Wi,R=!f||A||f-e>Wi&&!u.getPartialFragment(e);if(x||R)return;this.moved=!1}let g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&u){if(!(h.len>0)&&!f)return;let x=Math.max(f,h.start||0)-e,P=!!(g!=null&&g.live)?g.targetduration*2:Wi,I=Jt(e,u);if(x>0&&(x<=P||I)){a.paused||this._trySkipBufferHole(I);return}}let m=n.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting,T=this.stalled;if(T===null)if(v>0&&p-v<m)T=this.stalled=v;else{this.stalled=p;return}let E=p-T;if(!o&&(E>=m||v&&this.moved)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-(g?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return;if(a.currentTime!==e){let A=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${A} > ${e}`);return}}let b=J.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(b,E,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){let n=J.bufferedInfo(J.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=J.timeRangesToArray(s),o=J.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=J.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,c=a[o+1].start;if((l===-1||l>o)&&c-d<1&&e-d<2){let h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${c} buffered index: ${l}`);this.warn(h.message),this.media.currentTime+=1e-6;let u=Jt(e,this.fragmentTracker);u&&"fragment"in u?u=u.fragment:u||(u=void 0);let f=J.bufferInfo(this.media,e,0);this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:u,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,i){var s,n;let{fragmentTracker:a,media:o}=this,l=(s=this.hls)==null?void 0:s.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,c=Jt(i,a);if((c||d!=null&&d.live&&i<d.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;let h=e.buffered,u=this.adjacentTraversal(e,i);(h&&h.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||u))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,s=e.nextStart;if(i&&s){let n=i.getFragAtPos(t,H.MAIN),a=i.getFragAtPos(s,H.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${fe(e)})`);this.warn(a.message),t.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:i,hls:s}=this,n=s?.config;if(!i||!t||!n)return 0;let a=i.currentTime,o=J.bufferInfo(i,a,0);No(o,a,t,s);let l=a<o.start?o.start:o.nextStart;if(l){let c=o.len<=n.maxBufferHole,h=o.len>0&&o.len<1&&i.readyState<3,u=l-a;if(u>0&&(c||h)){if(u>n.maxBufferHole){let v=!1;if(a===0){let T=t.getAppendedFrag(0,H.MAIN);T&&l<T.end&&(v=!0)}if(!v&&e){var d;if(!((d=s.loadLevelObj)!=null&&d.details)||Oo(s.inFlightFragments,l))return 0;let E=!1,S=e.end;for(;S<l;){let b=Jt(S,t),A=b?b.duration:0;if(A>0)S+=A;else{E=!0;break}}if(E)return 0}}let{nudgeMaxRetry:f,skipBufferHolePadding:g}=n,m=++this.skipRetry>f,p=Math.max(l,a)+g;if(m||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${p}`),this.moved=!0,i.currentTime=p),!(e!=null&&e.gap)||m){let v=new Error(m?`Playhead still not moving after seeking over buffer hole from ${a} to ${p} after ${n.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${p}`),T={type:W.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:m,error:v,reason:v.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?T.part=e:T.frag=e),s.trigger(y.ERROR,T)}return p}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:s}=this,n=t?.config;if(!i||!n)return 0;let a=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){let o=a+(s+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Oo(r,e){let t=Fo(r.main);if(t&&t.start<=e)return t;let i=Fo(r.audio);return i&&i.start<=e?i:null}function Fo(r){if(!r)return null;switch(r.state){case _.IDLE:case _.STOPPED:case _.ENDED:case _.ERROR:return null}return r.frag}function Jt(r,e){return e.getAppendedFrag(r,H.MAIN)||e.getPartialFragment(r)}function No(r,e,t,i){let s=i.latestLevelDetails,n=Jt(e,t);if(ds(i.config)&&!r.nextStart&&s&&n&&i.interstitialsManager){let a="type"in n?n:n.fragment,o=Il(s,a.sn);o?.level===a.level&&Gl(o,i.interstitialsManager.playerQueue,e)&&(r.nextStart=o.start)}}var og=.25;function pr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function hn(r,e,t,i,s){let n=new r(e,t,"");try{n.value=i,s&&(n.type=s)}catch{n=new r(e,t,fe(s?Y({type:s},i):i))}return n}var $i=(()=>{let r=pr();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),yr=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(y.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return oa(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=pr();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===Me.emsg&&!i||!s)continue;let d=el(n[o].data),c=n[o].pts,h=c+n[o].duration;h>$i&&(h=$i),h-c<=0&&(h=c+og);for(let f=0;f<d.length;f++){let g=d[f];if(!tl(g)){this.updateId3CueEnds(c,l);let m=hn(a,c,h,g,l);m&&this.id3Track.track.addCue(m)}}}}updateId3CueEnds(e,t){var i;let s=(i=this.id3Track)==null?void 0:i.track.cues;if(s)for(let n=s.length;n--;){let a=s[n];a.type===t&&a.startTime<e&&a.endTime===$i&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;s==="audio"?d=c=>c.type===Me.audioId3&&l:s==="video"?d=c=>c.type===Me.emsg&&o:d=c=>c.type===Me.audioId3&&l||c.type===Me.emsg&&o,fr(n.track,t,i,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=pr();if(i&&s&&!a){let{fragmentStart:m,fragmentEnd:p}=e,v=this.assetCue;v?(v.startTime=m,v.endTime=p):o&&(v=this.assetCue=hn(o,m,p,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,c=Object.keys(d),h=this.dateRangeCuesAppended;if(l&&t){var u;if((u=l.track.cues)!=null&&u.length){let m=Object.keys(h).filter(p=>c.indexOf(p)===-1);for(let p=m.length;p--;){var f;let v=m[p],T=(f=h[v])==null?void 0:f.cues;delete h[v],T&&Object.keys(T).forEach(E=>{let S=T[E];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(S)}catch{}}})}}else h=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(!(c.length===0||!B(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<c.length;m++){let p=c[m],v=d[p],T=v.startTime,E=h[p],S=E?.cues||{},b=E?.durationKnown||!1,A=$i,{duration:x,endDate:R}=v;if(R&&x!==null)A=T+x,b=!0;else if(v.endOnNext&&!b){let I=c.reduce((k,D)=>{if(D!==v.id){let F=d[D];if(F.class===v.class&&F.startDate>v.startDate&&(!k||v.startDate<k.startDate))return F}return k},null);I&&(A=I.startTime,b=!0)}let P=Object.keys(v.attr);for(let I=0;I<P.length;I++){let k=P[I];if(!Lh(k))continue;let D=S[k];if(D)b&&!(E!=null&&E.durationKnown)?D.endTime=A:Math.abs(D.startTime-T)>.01&&(D.startTime=T,D.endTime=A);else if(o){let F=v.attr[k];Rh(k)&&(F=il(F));let $=hn(o,T,A,{key:k,data:F},Me.dateRange);$&&($.id=p,this.id3Track.track.addCue($),S[k]=$,a&&(k==="X-ASSET-LIST"||k==="X-ASSET-URL")&&$.addEventListener("enter",this.onEventCueEnter))}}h[p]={cues:S,dateRange:v,durationKnown:b}}}}};function kd(){return self.SourceBuffer||self.WebKitSourceBuffer}function Dd(){if(!bt())return!1;let e=kd();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function lg(){if(!Dd())return!1;let r=bt();return typeof r?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(hi(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(hi(e,"audio"))))}function dg(){var r;let e=kd();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}var st={DISABLED:0,SWITCHING:1,SWITCHED:2},cg=100,Ts=class extends mi{constructor(e,t,i){super(e,t,i,"stream-controller",H.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=st.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let s=this.media,n=s?s.currentTime:null;if(n===null||!B(n)||(this.log(`Media seeked to ${n}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(s,n,H.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${n} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(cg),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),e=i),this.state=_.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=_.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case _.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e?.[t],s=i?.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=_.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=_.IDLE;break}break}case _.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===_.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let m={type:this.targetBufferType()};this.hls.trigger(y.BUFFER_EOS,m),this.state=_.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=a.details;if(!d||this.state===_.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=_.WAITING_LEVEL,this.startFragRequested=!1;return}let c=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(c>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);let u=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(u,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&ve(f)&&this.fragmentTracker.getState(f)!==ye.OK){var g;let p=((g=this.backtrackFragment)!=null?g:f).sn-d.startSN,v=d.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,u)){if(!f.gap){let p=this.audioOnly&&!this.altAudio?he.AUDIO:he.VIDEO,v=(p===he.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p)}f=this.getNextFragmentLoopLoading(f,d,o,H.MAIN,h)}f&&(this.exceedsMaxBuffer(o,h,f)||this.loadFragment(f,a,u))}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);s===ye.NOT_LOADED||s===ye.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==st.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===st.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let i=this.fragPlaying;if(i){let s=i.level;this.hls.trigger(y.FRAG_CHANGED,{frag:i,previousFrag:e}),e?.level!==s&&this.hls.trigger(y.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===st.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;de(i,"playing",this.onMediaPlaying),de(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(le(i,"playing",this.onMediaPlaying),le(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=st.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!dg(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==_.IDLE)return;let s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=_.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let d=t.levelInfo,c=this.fragCurrent;c&&(this.state===_.FRAG_LOADING||this.state===_.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let h=0;if(o.live||(i=d.details)!=null&&i.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;h=this.alignPlaylists(o,d.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,h),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:a}),this.state===_.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=_.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,g)=>{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let s=this.hls.liveSyncPosition,n=this.playhead,a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!l)){let c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||n<o-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s}`),this.config.liveSyncMode==="buffered"){var d;let h=J.bufferInfo(i,s,0);if(!((d=h.buffered)!=null&&d.length)){i.currentTime=s;return}if(h.start<=n){i.currentTime=s;return}let{nextStart:f}=J.bufferedInfo(h.buffered,n,0);f&&(i.currentTime=f)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let d=o.videoCodec,c=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new vs(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=g!==-1,{decryptRange:p,byteRange:v}=is(i,s,this.iframesOnly),T=new gi(i.level,i.sn,i.stats.chunkCount,v?v.end-v.start:n.byteLength,g,m,i.duration,this.iframesOnly,p),E=this.initPTS[i.cc];f.push(n,h,u,d,i,s,l.totalduration,c,T,E)}onAudioTrackSwitching(e,t){let i=this.hls,s=this.altAudio!==st.DISABLED;if(es(t.url,i))this.altAudio=st.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=st.DISABLED,this.fragmentTracker.removeAllFragments(),i.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,t)}),i.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=es(t.url,this.hls);if(i){let s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?st.SWITCHED:st.DISABLED,this.tick()}onBufferCreated(e,t){let i=t.tracks,s,n,a=!1;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){let d=i[o];d&&(this.videoBuffer=d.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:s}=t,n=i.type===H.MAIN;if(n){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===_.PARSED&&(this.state=_.IDLE);return}let l=!1;if(ve(i)&&(l=!!i.gap&&!i.tagList.some(d=>d[0]==="GAP")),this.fragBufferedComplete(i,s),l){var a;i.stats.retry++;let d=(a=this.levels)==null?void 0:a[i.level];d&&d.fragmentError++}}let o=this.media;o&&(!this._hasEnoughToStart&&J.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===te.LEVEL&&(this.state=_.IDLE);break;case L.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=_.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==he.AUDIO||!this.altAudio){let i=(t===he.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let s=this.timelineOffset;s&&i&&(i+=s);let n=this.getLevelDetails(),a=J.getBuffered(e),o=a.length?a.start(0):0,l=o-i,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{let{hls:s}=this,n=i?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=_.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(y.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:c,text:h,id3:u,initSegment:f}=s,{details:g}=d,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=_.PARSING,f){let p=f.tracks;if(p){let S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,p,S,n),i.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:p})}let v=f.initPTS,T=f.timescale,E=this.initPTS[o.cc];if(B(v)&&(!E||E.baseTime!==v||E.timescale!==T)){let S=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:T,trackId:S};let b=this.initPTS.slice(0);i.trigger(y.INIT_PTS_FOUND,{timestampOffsets:b,frag:o,id:t,initPTS:v,timescale:T,trackId:S})}}if(c&&g){m&&c.type==="audiovideo"&&this.logMuxedErr(o);let p=g.fragments[o.sn-1-g.startSN],v=o.sn===g.startSN,T=!p||o.cc>p.cc;if(s.independent!==!1){let{startPTS:E,endPTS:S,startDTS:b,endDTS:A}=c;if(l)l.elementaryStreams[c.type]={startPTS:E,endPTS:S,startDTS:b,endDTS:A};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!T&&(this.couldBacktrack=!0),c.dropped&&c.independent){let x=this.getMainFwdBufferInfo(),R=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,P=c.firstKeyFramePTS?c.firstKeyFramePTS:E;if(!v&&R<P-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(c.type,o.start,S,o.start,A,!0)}else v&&E-(g.appliedTimelineOffset||0)>Wi&&(o.gap=!0);o.setElementaryStreamInfo(c.type,E,S,b,A),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n,v||T)}else if(v||T)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:p,endPTS:v,startDTS:T,endDTS:E}=m;l&&(l.elementaryStreams[he.AUDIO]={startPTS:p,endPTS:v,startDTS:T,endDTS:E}),o.setElementaryStreamInfo(he.AUDIO,p,v,T,E),this.bufferFragmentData(m,o,l,n)}if(g&&u!=null&&u.samples.length){let p={id:t,frag:o,details:g,samples:u.samples};i.trigger(y.FRAG_PARSING_METADATA,p)}if(g&&h){let p={id:t,frag:o,details:g,samples:h.samples};i.trigger(y.FRAG_PARSING_USERDATA,p)}}logMuxedErr(e){this.warn(`${ve(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==_.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,c=Hi(n.codec,d);if(c==="mp4a"&&(c="mp4a.40.5"),this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&!Wc()&&(c="mp4a.40.5")}c&&c.indexOf("mp4a.40.5")!==-1&&jc()&&n.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),d&&d!==c&&this.log(`Swapping manifest audio codec "${d}" for "${c}"`),n.levelCodec=c,n.id=H.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${c||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=H.MAIN;let d=a.codec;if(d?.length===4)switch(d){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(y.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let h=t[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:d,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,H.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=_.IDLE}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return B(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(B(t)){let i=this.getLevelDetails(),s=this.currentFrag||(i?qt(null,i.fragments,t):null);if(s){let n=s.programDateTime;if(n!==null){let a=n+(t-s.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Ss=class extends Ts{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{let t=this.media;t!=null&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:i}=t,s=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=s,this.startPosition=e,this.state){case _.STOPPED:case _.ENDED:case _.ERROR:this.state=_.IDLE}this.state===_.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,t]):this.nextOp=[s,t],this.hls.off(y.BUFFERED_TO_END,this.onBufferedToEnd);let n=this.media;i&&n&&this.seekTo(s)&&(this.currentOp=[s,t],this.nextOp=void 0,this.flushPipeline(s,!0))}seekTo(e){let t=this.media;if(t){var i;let s=(i=this.getLevelDetails())==null?void 0:i.edge,n=s!==void 0?s:t.duration;if(e>=n&&(e=n-.01),J.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let i=this.cached;i.push(e),this.cachedSize+=t.buffer.byteLength;let s=this.hls.config.iframeCacheLimit;for(;this.cachedSize>s&&i.length>1;){let n=i.shift();if(n.data)this.cachedSize-=n.data.byteLength,n.data=void 0;else{this.cached=i.filter(a=>!!a.data),this.cachedSize=i.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:i,payload:s}=e;this.cacheFragmentData&&!i&&s!=null&&s.byteLength&&!t.data&&ve(t)&&this.cacheSet(t,new Uint8Array(s.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);if((s===ye.NOT_LOADED||s===ye.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,i)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let i=e.decryptdata;return i?.keyFormat!=="identity"||!!i.key}replayCachedFragment(e){let t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;let i=e.stats=new ri;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=t.byteLength,i.chunkCount=1,this.state=_.FRAG_LOADING;let s={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(s),this.hls.trigger(y.FRAG_LOADED,s),this._handleFragmentLoadComplete(s)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:i,nextOp:s}=this;this.currentOp=this.nextOp=void 0,this.state=_.STOPPED,i!=null&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!s),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?ls(J.getBuffered(this.media)):"none"}`)),s&&this.loadMediaAt.apply(this,s)}flushPipeline(e,t){if(t){let i=this.media;if(i){let s=J.bufferInfo(i,e,0),n=s.len?s.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,H.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(y.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(y.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){let e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,i){let s=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,i||s||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let i=t.duration;return{len:i,start:e,end:e+i,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,H.MAIN);return!!(t!=null&&t.endList)}},vr=class extends Ss{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;let i=(t=this._img)==null?void 0:t.src;i&&self.URL.revokeObjectURL(i),this._img=e}loadMediaAt(e){if(!this.hls)return;let t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case _.STOPPED:case _.ENDED:case _.ERROR:this.state=_.IDLE}if(this.state===_.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===_.IDLE){let i=this.getBufferedAt(e);i&&(this.fragCurrent=i,this.updateImage(i,null))}}else{let i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}updateImage(e,t,i){let s=e.data;s||this.fragmentTracker.removeFragment(e);let n=this._img;if(n&&s){let a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,n.onload=()=>{if(!this.hls)return;let c=this.hls.levels[e.level];c!=null&&c.fragmentError&&(c.fragmentError=0,e.stats.retry=0);let h=self.performance.now(),u=t?t.stats:e.stats;u.buffering.end=e.stats.buffering.end=h,this.hls.trigger(y.FRAG_BUFFERED,{frag:e,part:t,stats:u,id:e.type,chunkMeta:i})},n.onerror=()=>{this.handleError("Image decode error",e,t,i)};let l=n.src;l&&self.URL.revokeObjectURL(l);let d=new Blob([s],{type:"image/jpeg"});n.src=self.URL.createObjectURL(d)}else this.state=_.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,i,s){if(!this.hls)return;let n=new Error(e);this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:s,frag:t,part:i,fatal:!1,error:n,err:n})}_bufferInitSegment(){}bufferFragmentData(e,t,i,s){super.bufferFragmentData(e,t,i,s,!0);let n=Q(new Uint8Array(e.data1),["mdat"]);if(n.length===0){this.handleError("Could not find I-Frame mdat",t,i,s);return}let a=t;this.cacheSet(a,n[0]),this.updateImage(a,i,s)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;let t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){let i=this.getAppendedFrag(t);if(i&&!Zt(i,this.fragPlaying))return this.fragPlaying=i,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},hg=10,ug="Image I-Frame player does not accept HTMLMediaElements",Bo={seekOnAppend:!0},Ui,un,Er=class extends Oe{constructor(e,t){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Ui||(Ui=fg(t)),un||(un=gg(Ui)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(y.MANIFEST_LOADING,this.clearAsset,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(y.MANIFEST_LOADING,this.clearAsset,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var i;let s=(i=this.hls)==null?void 0:i.pathwayPriority;t.length&&s&&this.iframeInstances.forEach(n=>{n.pathwayPriority=s})}onInitPtsFound(e,{id:t,timestampOffsets:i}){t===H.MAIN&&(this.initPTS=i)}onFragBuffered(e,t){var i;let s=this.hls;s&&s.hasEnoughToStart&&(((i=s.mainForwardBufferInfo)==null?void 0:i.len)||0)>hg&&this.iframeInstances.forEach(n=>{if(!n.loadingEnabled){var a;n.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(Ui,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;let i=(t=this.hls)==null?void 0:t.iframeVariants.filter(s=>s.imageCodec);return this.createInstance(un,i,e,"image-")}createInstance(e,t,i,s){let{hls:n}=this;if(!n)return null;let{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:d,loadLevel:c,bandwidthEstimate:h,sessionId:u}=n,{stats:f,variableList:g}=this;if(!(t!=null&&t.length)||!f||!a)return null;let m=`${s||""}iframe-player-${this.instanceCounter++}`,p=n.levels,v=d||p[c],T=bl(v,o.videoPreference),E=v?.pathwayId||".",S=Y(Y({},o),{},{loggerId:m,primarySessionId:u,videoPreference:T,abrEwmaDefaultEstimate:h,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),b=new e(S,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(A=>!A.url),this.iframeInstances.push(b),b.trigger(y.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:E},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),b}};function fg(r){return class extends r{constructor(t,i,s,n){t.streamController||(t.streamController=Ss),super(t),this._url=i,this.streamController.setInitPts(s),this.streamController.initDetails=n}loadSource(){}loadMediaAt(t,i=Bo){if(t<0)return;let s=Y(Y({},Bo),i);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,s)}}}function gg(r){return class extends r{constructor(t,i,s,n){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=vr),t.capLevelController=void 0,t.bufferController=void 0,super(t,i,s,n)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(ug)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}var St=.025,bs=function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r}({});function mg(r,e,t){return`${r.identifier}-${t+1}-${si(e)}`}var Tr=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return e<=0||isNaN(i)?!1:i===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return $o(t,e)?Yi(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=Yi(t,e);return t-i<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=B(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return $o(t,e)?Yi(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<St))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?bs.Range:bs.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return pg(this)}};function Yi(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<St)?e.start:e.start+e.duration}function $o(r,e){return e>r.start-St&&e<r.start+r.duration+St}function Cd(r,e,t){let i=new self.URL(r,t);return i.protocol!=="data:"&&Tt(i,"_HLS_primary_id",e),i}function fn(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function pg(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function $t(r){let e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Sr=class{constructor(e,t,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(y.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=i,this.assetItem=s;let a=()=>{this.hasDetails=!0};n.once(y.LEVEL_LOADED,a),n.once(y.AUDIO_TRACK_LOADED,a),n.once(y.SUBTITLE_TRACK_LOADED,a),n.on(y.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(y.BUFFER_APPENDED,()=>{let c=this.bufferedEnd;this.reachedPlayout(c)&&(this._bufferedEosTime=c,n.trigger(y.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Cd(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var i;if(!this.appendInPlace)return!1;if((i=this.hls)!=null&&i.bufferedToEnd)return!0;if(!e)return!1;let s=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=J.bufferInfo(e,n,.02);return this.getAssetTime(a.end)>=s-.02}reachedPlayout(e){let i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=J.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,i){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,i){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${$t(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},gn=.033,br=class extends Oe{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let s=this.items;if(s)for(s[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=s[i])!=null&&n.event;){var n;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let s=0;s<i.length;s++){let n=i[s];t&&t!=="primary"&&(n=n[t]);let a=n.start,o=i[s].event,l=o!=null&&o.cue.pre?o.duration:n.end;if(e===a||e>a&&e<l)return s}return-1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){let n=i[s].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return s}return-1}findEventIndex(e){let t=this.items;if(t)for(let s=t.length;s--;){var i;if(((i=t[s].event)==null?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){let i=e.assetList,s=i.length;if(s>1)for(let n=0;n<s;n++){let a=i[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===s-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let i=t.assetList,s=i[i.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t,i=0){let s=e.main.details,{dateRanges:n}=s,a=this.events,o=this.parseDateRanges(n,{url:s.url},t),l=Object.keys(n),d=a?a.filter(c=>l.indexOf(c.identifier)===-1):[];o.length&&o.sort((c,h)=>{let u=c.cue.pre,f=c.cue.post,g=h.cue.pre,m=h.cue.post;if(u&&!g)return-1;if(g&&!u||f&&!m)return 1;if(m&&!f)return-1;if(!u&&!g&&!f&&!m){let p=c.startTime,v=h.startTime;if(p!==v)return p-v}return c.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=o,d.forEach(c=>{this.removeEvent(c)}),this.updateSchedule(e,d,i)}updateSchedule(e,t=[],i=0,s=!1){let n=this.events||[];if(n.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(n,e,i);(s||t.length||a?.length!==o.length||o.some((d,c)=>Math.abs(d.playout.start-a[c].playout.start)>.005||Math.abs(d.playout.end-a[c].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,i){let s=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],l=e[o];if(l.isInterstitial){let d=this.eventMap[o];d?d.setDateRange(l):(d=new Tr(l,t),this.eventMap[o]=d,i===!1&&(d.appendInPlace=i)),s.push(d)}}return s}parseSchedule(e,t,i=0){let s=[],n=t.main.details,a=n.live?1/0:n.edge,o=0;if(e=e.filter(d=>!d.error&&!(d.cue.once&&d.hasPlayed)),e.length){this.resolveOffsets(e,t);let d=0,c=0;if(e.forEach((h,u)=>{let f=h.cue.pre,g=h.cue.post,m=e[u-1]||null,p=h.appendInPlace,v=g?a:h.startOffset,T=h.duration,E=h.timelineOccupancy===bs.Range?T:0,S=f&&n.live?i+(h.resumeOffset||0):0,b=S||h.resumptionOffset,A=m?.startTime===v,x=v+h.cumulativeDuration,R=p?x+T:v+b;if(f||!g&&v<=0){let I=c;c+=E,h.timelineStart=x;let k=o;o+=T,s.push({event:h,start:x,end:R,playout:{start:k,end:o},integrated:{start:I,end:c}})}else if(v<=a){if(!A){let D=v-d;if(D>gn){let F=d,G=c;c+=D;let $=o;o+=D;let C={previousEvent:e[u-1]||null,nextEvent:h,start:F,end:F+D,playout:{start:$,end:o},integrated:{start:G,end:c}};s.push(C)}else D>0&&m&&(m.cumulativeDuration+=D,s[s.length-1].end=v)}g&&(R=x),h.timelineStart=x;let I=c;c+=E;let k=o;o+=T,s.push({event:h,start:x,end:R,playout:{start:k,end:o},integrated:{start:I,end:c}})}else return;let P=S||h.resumeTime;g||P>a?d=a:!f&&R&&h.appendInPlaceStarted&&P-R>gn?d=R:d=P}),d<a){var l;let h=d,u=c,f=a-d;c+=f;let g=o;o+=f,s.push({previousEvent:((l=s[s.length-1])==null?void 0:l.event)||null,nextEvent:null,start:d,end:h+f,playout:{start:g,end:o},integrated:{start:u,end:c}})}this.setDurations(a,o,c)}else s.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return s}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){let i=t.main.details,s=i.live?1/0:i.edge,n=0,a=-1;e.forEach((o,l)=>{let d=o.cue.pre,c=o.cue.post,h=d?0:c?s:o.startTime;this.updateAssetDurations(o),a===h?o.cumulativeDuration=n:(n=0,a=h),!c&&o.snapOptions.in&&(o.resumeAnchor=qt(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<gn&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=B(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(i-s)>St?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),!1;let d=qt(null,o.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let c=a==="audio"?.175:0;return Math.abs(d.start-i)<St+c||Math.abs(d.end-i)<St+c?!1:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,s=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,s||(s=o.duration===null),n||(n=!!o.error);let d=o.error?0:o.duration||0;i+=d}s&&!n?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Ue(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}var Ar=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let i=e.assetListUrl,s;try{s=Cd(i,this.hls.sessionId,e.baseUrl)}catch(u){let f=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,u,i);this.hls.trigger(y.ERROR,f);return}t&&s.protocol!=="data:"&&Tt(s,"_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={type:te.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},d=n.interstitialAssetListLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(u,f,g,m)=>{let p=u.data,v=p?.ASSETS;if(!Array.isArray(v)){let T=this.assignAssetListError(e,L.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,m);this.hls.trigger(y.ERROR,T);return}e.assetListResponse=p,this.hls.trigger(y.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:m})},onError:(u,f,g,m)=>{let p=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${f.url})`),f.url,m,g);this.hls.trigger(y.ERROR,p)},onTimeout:(u,f,g)=>{let m=this.assignAssetListError(e,L.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,u,g);this.hls.trigger(y.ERROR,m)}};return o.load(l,c,h),this.hls.trigger(y.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,s,n,a){return e.error=i,{type:W.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:a,stats:n}}};function Uo(r){var e;r==null||(e=r.play())==null||e.catch(()=>{})}function Rt(r,e){return`[${r}] Advancing timeline position to ${e}`}var xr=class extends Oe{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;let s=i-this.timelinePos;if(Math.abs(s)<1/7056e5)return;let a=s<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=i,this.bufferedPos=i;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-s)&&this.updateSchedule(!0),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;let f=this.findItemIndex(o),g=this.schedule.findItemIndexAtTime(i);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&g>f){let m=this.schedule.findJumpRestrictedIndex(f+1,g);if(m>f){this.setSchedulePosition(m);return}}this.setSchedulePosition(g);return}let d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f))}return}let c=d.timelineStart,h=d.duration||0;if(a&&i<c||i>=c+h){var u;(u=o.event)!=null&&u.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d)}},this.onTimeupdate=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;let s=this.playingItem;if(!s||this.playingLastItem)return;if(i>=s.end){this.timelinePos=s.end;let o=this.findItemIndex(s);this.setSchedulePosition(o+1)}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n)},this.onScheduleUpdate=(i,s)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,c=i.map(m=>m.identifier),h=!!(o.length||c.length);(h||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
41
+ Schedule: ${l.map(m=>Ue(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`);let u=null,f=null;a&&(u=this.updateItem(a,this.timelinePos),this.itemsMatch(a,u)?this.playingItem=u:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);let g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),i.forEach(m=>{m.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){let p=m.assetItem.timelineStart,v=m.timelineOffset-p;if(v)try{m.timelineOffset=p}catch(T){Math.abs(v)>St&&this.warn(`${T} ("${m.assetId}" ${m.timelineOffset}->${p})`)}}}),h||s){if(this.hls.trigger(y.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:c}),this.isInterstitial(a)&&c.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(u,a),g&&f!==u&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Ar(e),this.schedule=new br(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(y.MEDIA_ENDED,this.onMediaEnded,this),e.on(y.ERROR,this.onError,this),e.on(y.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(y.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(y.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(y.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(y.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(y.MEDIA_ENDED,this.onMediaEnded,this),e.off(y.ERROR,this.onError,this),e.off(y.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){le(e,"play",this.onPlay),le(e,"pause",this.onPause),le(e,"seeking",this.onSeeking),le(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;de(i,"seeking",this.onSeeking),de(i,"timeupdate",this.onTimeupdate),de(i,"play",this.onPlay),de(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!s){this.clearScheduleState();let n=this.findItemIndex(i);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=h=>h&&e.getAssetPlayer(h.identifier),s=(h,u,f,g,m)=>{if(h){let p=h[u].start,v=h.event;if(v){if(u==="playout"||v.timelineOccupancy!==bs.Point){let T=i(f);T?.interstitial===v&&(p+=T.assetItem.startOffset+T[m])}}else{let T=g==="bufferedPos"?a():e[g];p+=T-h.start}return p}return 0},n=(h,u)=>{var f;if(h!==0&&u!=="primary"&&(f=e.schedule)!=null&&f.length){var g;let m=e.schedule.findItemIndexAtTime(h),p=(g=e.schedule.items)==null?void 0:g[m];if(p){let v=p[u].start-p.start;return h+v}}return h},a=()=>{let h=e.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var u,f;return(u=e.primaryDetails)!=null&&u.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[h])||0},l=(h,u)=>{var f,g;let m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${u}"`);let p=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(h,u),T=(g=e.schedule.items)==null?void 0:g[v],E=e.getBufferingPlayer(),S=E?.interstitial,b=S?.appendInPlace,A=p&&e.itemsMatch(p,T);if(p&&(b||A)){let x=i(e.playingAsset),R=x?.media||e.primaryMedia;if(R){let P=u==="primary"?R.currentTime:s(p,u,e.playingAsset,"timelinePos","currentTime"),I=h-P,k=(b?P:R.currentTime)+I;if(k>=0&&(!x||b||k<=x.duration)){R.currentTime=k;return}}}if(T){let x=h;if(u!=="primary"){let P=T[u].start,I=h-P;x=T.start+I}let R=!e.isInterstitial(T);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(R||T.event.appendInPlace)){let P=e.media||(b?E?.media:null);P&&(P.currentTime=x)}else if(p){let P=e.findItemIndex(p);if(v>P){let k=e.schedule.findJumpRestrictedIndex(P+1,v);if(k>P){e.setSchedulePosition(k);return}}let I=0;if(R)e.timelinePos=x,e.checkBuffer();else{let k=T.event.assetList,D=h-(T[u]||T).start;for(let F=k.length;F--;){let G=k[F];if(G.duration&&D>=G.startOffset&&D<G.startOffset+G.duration){I=F;break}}}e.setSchedulePosition(v,I)}}},d=()=>{let h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;let u=t();return e.isInterstitial(u)?u:null},c={get bufferedEnd(){let h=t(),u=e.bufferingItem;if(u&&u===h){var f;return s(u,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-u.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let h=d(),u=e.effectivePlayingItem;return u&&u===h?s(u,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(h){let u=d(),f=e.effectivePlayingItem;f&&f===u&&l(h+f.playout.start,"playout")},get duration(){let h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;let u=(h=d())==null?void 0:h.event.assetList;return u?u.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var h;let u=(h=d())==null?void 0:h.event;return u&&e.effectivePlayingAsset?u.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var h;return((h=e.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=e.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return d()?c:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let h=t();return e.findItemIndex(h)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let h=e.effectivePlayingItem;return e.findItemIndex(h)},primary:{get bufferedEnd(){return a()},get currentTime(){let h=e.timelinePos;return h>0?h:0},set currentTime(h){l(h,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){l(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){return n(e.seekableStart,"integrated")}},skip:()=>{let h=e.effectivePlayingItem,u=h?.event;if(u&&!u.restrictions.skip){let f=e.findItemIndex(h);if(u.appendInPlace){let g=h.playout.start+h.event.duration;l(g+.001,"playout")}else e.advanceAfterAssetEnded(u,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!i?!1:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);let n=(t=s)==null?void 0:t.currentTime;if(!(n===void 0||!B(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s){this.detachedData={media:s};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${fe(n)}`),this.detachedData=n}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource,c;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),c="Primary";else{let g=this.getBufferingPlayer();g?(n=g.transferMedia(),this.detachedData=n,c=`${g}`):d?c="detached MediaSource":c="detached media"}if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${fe(n)}`);else if(!this.detachedData||a.media===t){let g=this.playerQueue;g.length>1&&g.forEach(m=>{if(o&&m.interstitial.appendInPlace!==l){let p=m.interstitial;this.clearInterstitial(m.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${p}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let h=n&&"mediaSource"in n&&((s=n.mediaSource)==null?void 0:s.readyState)!=="closed";if(this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${c} (media.currentTime: ${t.currentTime})`),!h&&!o){e.attachMedia(t);return}let u=h&&n?Y({},n):{media:t},f=this.schedule;if(f&&o){let g=e.assetId===f.assetIdAtEnd;u.overrides={duration:f.duration,endOfStream:g||e.appendInPlace===!1}}if(!h&&l){let g=e,m=g.assetItem.timelineStart;if(m){let p=g.hls,v=Math.max(this.timelinePos-m,Number.EPSILON);p.startPosition!==v&&(this.log(`Set ${g} startPosition: ${v}`),p.config.startPosition=v,p.loadingEnabled&&p.startLoad(v))}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events,i=this.hls;if(!t||this.playbackDisabled||!this.media||!i)return;this.bufferedPos===-1&&(this.bufferedPos=0);let s=this.timelinePos,n=this.effectivePlayingItem;if(s===-1){if(!i.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}let a=i.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Rt("checkStart (preroll)",a));let o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(Rt("checkStart",a));let o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else i.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Rt("checkStart (playing item)",n.start));let a=e.findItemIndex(n);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){let i=e.event,s=i.findAssetIndex(t),n=fn(i,s);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=this.getNextItemIndex(e,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!B(e.resumeOffset)&&this.hls){let i=this.getLiveStartPos();if(t){let s=this.getBufferingPlayer(),n=s!=null&&s.interstitial.cue.pre?s.remaining:0;return i+n}return i}}getNextItemIndex(e,t){if(this.schedule){let i=this.livePrerollResumption(e.event,t);if(i!==void 0)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,i){let s=fn(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){let n=this.schedule.items;if(n){let a=n[t],o=a.event?this.getNextItemIndex(a):t+1,l=n.length;if(o>=l){this.setSchedulePosition(-1);return}let d=e.resumeTime;this.timelinePos<d&&(this.log(Rt("advanceAfterAssetEnded",d)),this.timelinePos=d,e.appendInPlace&&!n[o].event&&this.hls.startLoad(d+.01),this.checkBuffer(this.bufferedPos<d)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){let n=e.assetList[s];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let s=t.parentIdentifier,n=i.getEvent(s);if(n){let a=i.findEventIndex(s),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var i;let s=(i=this.schedule)==null?void 0:i.items;if(!s||this.playbackDisabled)return;let n=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Ue(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let h=a.event,u=this.playingAsset,f=u?.identifier,g=f?this.getAssetPlayer(f):null;if(g&&f&&(!this.eventItemsMatch(a,n)||t!==void 0&&f!==h.assetList[t].identifier)){var l;let m=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${h.assetList.length} ${$t(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(y.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:m,event:h,schedule:s.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(f,n),g.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Ue(a)}`),h.hasPlayed=!0,this.hls.trigger(y.INTERSTITIAL_ENDED,{event:h,schedule:s.slice(0),scheduleIndex:e}),h.cue.once&&this.hls)){var d;this.updateSchedule();let m=(d=this.schedule)==null?void 0:d.items;if(n&&m){let p=this.findItemIndex(n),v=this.livePrerollResumption(h);if(v!==void 0){let T=v,E=this.getNextItemIndex(a);if(!this.isInterstitial(s[E])){var c;let S=(c=this.primaryDetails)==null?void 0:c.fragments;if(h.snapOptions.in&&S){let b=qt(null,S,v);b&&(T=Math.min(Math.max(s[E].start,Yi(T,b)),s[E].end))}}if(this.log(Rt("live join (preroll)",T)),this.timelinePos=T,E!==p&&(E||E===0)){this.advanceSchedule(E,m,void 0,a,o);return}}this.advanceSchedule(p,m,t,a,o)}return}}this.advanceSchedule(e,s,t,a,o)}advanceSchedule(e,t,i,s,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(c=>{let h=c.interstitial,u=a.findEventIndex(h.identifier);(u<e||u>e+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let c=o.event;if(i===void 0){i=c.cue.pre?0:a.findAssetIndex(c,this.timelinePos);let g=fn(c,i-1);if(c.isAssetPastPlayoutLimit(g)||c.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(c,e,i);return}i=g}let h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let u=this.preloadAssets(c,i);if(this.eventItemsMatch(o,h||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ue(o)} ${c.appendInPlace?"append in place":""}`),c.hasPlayed=!1,this.hls.trigger(y.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${c}`);return}if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${c}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=c.assetList[i];if(!f){this.advanceAfterAssetEnded(c,e,i||0);return}if(u||(u=this.getAssetPlayer(f.identifier)),u===null||u.destroyed){let g=c.assetList.length;this.warn(`asset ${i+1}/${g} player destroyed ${c}`),u=this.createAssetPlayer(c,f,i),u.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(u,i,t,e,l),this.shouldPlay&&Uo(u.media)}else o?(this.resumePrimary(o,e,s),this.shouldPlay&&Uo(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var s,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Ue(e)}`);let a=this.timelinePos;if((s=this.detachedData)!=null&&s.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Rt("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!i)return;let o=(n=this.schedule)==null?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ue(e)}`),this.hls.trigger(y.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,i){let s=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;let n=this.endedItem||this.playingItem,a=n!=null&&n.event?this.livePrerollResumption(n.event,i):void 0;if(a!==void 0)return a;let o=this.primaryDetails;if(o){let{fragmentStart:l,edge:d}=o;if(s<l||s>d&&!i){let c=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${s} [${l}-${d}]) snapping to liveSync ${c}`),c||l}}}return this.log(`primary resumption itemStart: ${s}`),s}getLiveStartPos(){var e;let t=this.hls.startPosition,i=this.hls.liveSyncPosition||0,s=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||i&&i-t<s?i||0:t}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:J.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let s=this.primaryMedia;if(!s)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Rt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){let i=this.hls,{loadingEnabled:s,bufferingEnabled:n,startPosition:a}=i,o=i.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${s} bufferingEnabled: ${n}`),!t&&o||!s||Math.abs(a-e)>.1){let l=this.primaryDetails;if(l!=null&&l.live&&e+.5>=l.edge){let d=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${d?Ue(d):null}`),i.pauseBuffering(),this.bufferPastEdge=!0;return}i.startLoad(e,t)}else n||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(y.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(y.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let s=Y(Y({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s;let n=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,n===-1?0:n),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){let o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+.5<o.edge){this.bufferPastEdge=!1;let d=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${d?Ue(d):null}`),d?.end===1/0){let h=this.playingItem,u=this.isInterstitial(h)&&h.event.appendInPlace;this.hls.startLoad(Math.max(l,d.start),u)}else{let h=this.getBufferingPlayer();h&&h.bufferedInPlaceToEnd(this.primaryMedia,h.currentTime)&&h.hls&&h.hls.trigger(y.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=Y(Y({},this.altSelection),{},{audio:i});return}let n=Y(Y({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=Y(Y({},this.altSelection),{},{subtitles:i});return}let n=Y(Y({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(e,t){let i=wa(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=wa(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){let s=t[i];if(s.cue.post){let n=this.getEventItem(s.identifier);n&&this.eventItemsMatch(n,this.bufferingItem)&&this.bufferedToItem(n,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let i=this.findItemIndex(t);this.setSchedulePosition(i+1)}else this.shouldPlay=!1}updateItem(e,t){var i;let s=(i=this.schedule)==null?void 0:i.items;if(e&&s){let n=this.findItemIndex(e,t);return s[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});let i=e.end+.25,s=J.bufferInfo(this.primaryMedia,i,0);(s.end>i||(s.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Ue(e)} (was ${Ue(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;let i=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(i)&&i.event.identifier===e)return i}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,i;let s=this.mediaSelection;if(!s)return;let n=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(i=this.schedule)==null||i.updateSchedule(s,[],n,e)}checkBuffer(e){var t;let i=(t=this.schedule)==null?void 0:t.items;if(!i)return;let s=J.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){let s=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;let c=this.findItemIndex(n),h=Math.min(c+1,t.length-1),u=t[h];if((l===-1&&n&&e>=n.end||(d=u.event)!=null&&d.appendInPlace&&e+.01>=u.start)&&(l=h),this.isInterstitial(n)){let f=n.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>c&&l>o)this.bufferedToItem(u);else{let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&u.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(u)&&this.preloadAssets(u.event,0)}}else i&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(s=>{let n=this.getAssetPlayer(s.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:s,events:n}=i;if(!s||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ue(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((c,h)=>{let u=this.getAssetPlayer(c.identifier);u&&(h===d&&u.loadSource(),u.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(y.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;let s=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(s,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(n,e,!0):this.startLoadingPrimaryAt(n);else{let o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(n,l)}}}}bufferedToEvent(e,t){let i=e.event,s=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(s||!n){let a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let i=e.assetUrl,s=e.assetList.length,n=s===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart,d=this.playingItem,c=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let h,u=0;if((!c||c.interstitial.cue.pre)&&this.primaryLive&&(u=this.getLiveStartPos(),c&&(u+=c.remaining)),u&&!(e.cue.pre||e.cue.post)){let g=u-l;g>0&&(h=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${u?` live-start: ${u} start-offset: ${h} (timeline-start: ${l})`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);let f=this.assetListLoader.loadAssetList(e,h);f&&(e.assetListLoader=f)}else if(!a&&s){for(let d=t;d<s;d++){let c=e.assetList[d],h=this.getAssetPlayerQueueIndex(c.identifier);(h===-1||this.playerQueue[h].destroyed)&&!c.error&&this.createAssetPlayer(e,c,d)}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let i=this.primaryDetails;if(i&&e>=i.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,s,n,a){let o={parentIdentifier:e.identifier,identifier:mg(e,a,t),duration:n,startOffset:i,timelineStart:s,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){let s=this.hls,n=s.userConfig,a=s.loadLevelObj||s.levels[s.currentLevel],o=bl(a,n.videoPreference),l=s.audioTracks[s.audioTrack],d=s.subtitleTracks[s.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){let S=this.timelinePos-t.timelineStart;if(S>=0){let b=t.duration;b&&S<b&&(c=S)}}let h=t.identifier,u=Y(Y({},n),{},{maxMaxBufferLength:Math.min(15,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));let f=u.cmcd;f!=null&&f.sessionId&&f.contentId&&(u.cmcd=ce({},f,{contentId:si(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);let g=new Sr(this.HlsPlayerClass,u,e,t);this.playerQueue.push(g),e.assetList[i]=t;let m=!0,p=S=>{if(S.live){let x=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:!0,type:W.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:x},P=this.findEventIndex(e.identifier);this.handleAssetItemError(R,e,P,i,x.message);return}let b=S.edge-S.fragmentStart,A=t.duration;(m||A===null||b>A)&&(m=!1,this.log(`Interstitial asset "${h}" duration change ${A} > ${b}`),t.duration=b,this.updateSchedule())};g.on(y.LEVEL_UPDATED,(S,{details:b})=>p(b)),g.on(y.LEVEL_PTS_UPDATED,(S,{details:b})=>p(b)),g.on(y.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(S,b)=>{let A=this.getAssetPlayer(h);if(A&&b.tracks){A.off(y.BUFFER_CODECS,v),A.tracks=b.tracks;let x=this.primaryMedia;this.bufferingAsset===A.assetItem&&x&&!A.media&&this.bufferAssetPlayer(A,x)}};g.on(y.BUFFER_CODECS,v);let T=()=>{let S=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${S}`),!S||!this.schedule)return;let b=this.getEventItem(e.identifier);b&&this.advanceAssetBuffering(b,S.assetItem)};g.on(y.BUFFERED_TO_END,T);let E=S=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;let A=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,A,S)};return g.once(y.MEDIA_ENDED,E(i)),g.once(y.PLAYOUT_LIMIT_REACHED,E(1/0)),g.on(y.ERROR,(S,b)=>{if(!this.schedule)return;let A=this.getAssetPlayer(h);if(b.details===L.BUFFER_STALLED_ERROR){if(A!=null&&A.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(b.details===L.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(b,e,this.findEventIndex(e.identifier),i,`Asset player error ${b.error} ${e}`)}),g.on(y.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;let b=new Error(`Asset player destroyed unexpectedly ${h}`),A={fatal:!0,type:W.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(A,e,this.findEventIndex(e.identifier),i,b.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${$t(t)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(i!==-1){let s=this.playerQueue[i];this.log(`clear ${s} toSegment: ${t&&Ue(t)}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(i,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,n){let{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=o,c?.identifier!==l&&(c&&(this.clearAssetPlayer(c.identifier,i[s]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${$t(o)}`),this.hls.trigger(y.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var i;if(!this.schedule)return;let{interstitial:s,assetItem:n}=e,a=this.getEventItem(s.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=n,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,n);return}let o=this.getBufferingPlayer();if(o===e)return;let l=s.appendInPlace;if(l&&o?.interstitial.appendInPlace===!1)return;let d=o?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(l&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!Xo(d,e.tracks)){let c=new Error(`Asset ${$t(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),h={fatal:!0,type:W.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:c},u=s.findAssetIndex(n);this.handleAssetItemError(h,s,this.findEventIndex(s.identifier),u,c.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let s=i.currentTime,n=t.findAssetIndex(e,s),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||s-a.timelineStart,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${s})`),l&&(d/i.playbackRate<.5||o.bufferedInPlaceToEnd(i,o.currentTime))&&o.hls){let c=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,c,n)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let i=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(i),t.currentTime=e):this.log(`Cannot ${i}`)}}handleAssetItemError(e,t,i,s,n){if(e.details===L.BUFFER_STALLED_ERROR)return;let a=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&$t(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,c=this.schedule.items,h=ce({},e,{fatal:!1,errorAction:ti(!0),asset:a,assetListIndex:s,event:t,schedule:c,scheduleIndex:i,player:d});if(this.hls.trigger(y.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;let u=this.playingAsset,f=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(m=>!m.error))t.error=g;else for(let m=s;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):u?.identifier===o?this.advanceAfterAssetEnded(t,i,s):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,s=this.playingItem,n=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Ue(i)} startPosition: ${a} seekableStart: ${n} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,n);let d=this.updateItem(i,o);this.itemsMatch(i,d)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||!this.isInterstitial(s))return;let l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var i,s;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;let l=n.timelineStart,d=n.duration,c=0;o.forEach((g,m)=>{let p=parseFloat(g.DURATION);this.createAsset(n,m,c,l+c,p,g.URI),c+=p}),n.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${d}) ${n}`);let h=this.waitingItem,u=h?.event.identifier===a;this.updateSchedule();let f=(s=this.bufferingItem)==null?void 0:s.event;if(u){let g=this.findEventIndex(a),m=this.getEventItem(a);if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(m)}this.setSchedulePosition(g)}else if(f?.identifier===a){let g=n.assetList[0];if(g){let m=this.getAssetPlayer(g.identifier);if(f.appendInPlace){let p=this.primaryMedia;m&&p&&this.bufferAssetPlayer(m,p)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case L.ASSET_LIST_PARSING_ERROR:case L.ASSET_LIST_LOAD_ERROR:case L.ASSET_LIST_LOAD_TIMEOUT:{let i=t.interstitial;i&&(this.updateSchedule(!0),this.primaryFallback(i));break}case L.BUFFER_STALLED_ERROR:{let i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}let s=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${s?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Ir=class{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;let{media:i}=this,s=this.levelDetails;if(!i||!s||!this.hls)return;this.currentTime=i.currentTime;let n=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;let{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=n;if(!o||l===1||!s.live)return;let d=this.targetLatency;if(d===null)return;let c=a-d,h=Math.min(this.maxLatency,d+s.targetduration),u=c<h,f=ds(n)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(u&&c>.05&&this.forwardBufferLength>1&&!f){let g=Math.min(2,Math.max(1,l)),m=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,p=Math.min(g,Math.max(1,m));this.changeMediaPlaybackRate(i,p)}else i.playbackRate!==1&&i.playbackRate!==0&&this.changeMediaPlaybackRate(i,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;let t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;let i=this.levelDetails;return i?t.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:i,partHoldBack:s,targetduration:n}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,d=this.hls.userConfig,c=l&&s||i;(this._targetLatencyUpdated||d.liveSyncDuration||d.liveSyncDurationCount||c===0)&&(c=a!==void 0?a:o*n);let h=n;return c+Math.min(this.stallCount*t.liveSyncOnStallIncrease,h)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;let i=this.levelDetails;if(i===null)return null;let s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null||!this.hls)return 0;let t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.ERROR,this.onError,this),e.on(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.ERROR,this.onError,this),e.off(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var i;let s=this.hls,n=this.media||t.event.appendInPlace&&(s==null||(i=s.interstitialsManager)==null?void 0:i.playerQueue.reduce((a,o)=>a||o.media,null));s&&n&&n.playbackRate>1&&n.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)}onError(e,t){var i;t.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Go=500,Lr=class extends mi{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",H.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=_.IDLE,this.setInterval(Go),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:i,part:s,success:n}=t;if(!n)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o,l=(s||i).start;for(let c=0;c<a.length;c++)if(l>=a[c].start&&l<=a[c].end){o=a[c];break}let d=l+(s||i).duration;if(o?o.end=d:(o={start:l,end:d},a.push(o)),!s||d>=i.end){let c=this.fragmentTracker.fragBuffered(i);s&&c&&(c.range.subs={time:[{startPTS:i.start,endPTS:d}],partial:!0}),ve(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:i,endOffset:s}=t;if(i===0&&s!==Number.POSITIVE_INFINITY){let n=s-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(i,n,H.SUBTITLE)}}onError(e,t){let i=t.frag;i?.type===H.SUBTITLE&&(t.details===L.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==_.STOPPED&&(this.state=_.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&id(this.levels,t)){this.levels=t.map(i=>new Ct(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let s=new Ct(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,H.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let s=this.levels[this.currentTrackId];if(!(s!=null&&s.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==_.STOPPED&&this.setInterval(Go)}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:s,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=this.mainDetails,c=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;if(!d){this.startFragRequested=!1;return}if(l.details){var h;c=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}a.alignedSliding||(os(d,a,this),c=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,d&&!this.startFragRequested&&this.setStartPosition(d,c),o===s&&(this.hls.trigger(y.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:i,payload:s}=e;!i||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,i)}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e;this.fragContextChanged(t)||!(i!=null&&i.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(i,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&Vt(t.method))}decryptPayload(e,t,i){let s=t.decryptdata,n=performance.now();this.decrypter.decrypt(new Uint8Array(e),s.key.buffer,s.iv.buffer,Yr(s.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(y.FRAG_DECRYPTED,{frag:t,part:i,payload:a,stats:{tstart:n,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:i}),i||(this.warn(`${a.name}: ${a.message}`),this.state=_.IDLE)})}doTick(){if(this.state===_.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:i,levels:s}=this,n=s[i],a=n?.details;if(!a||this.waitForLive(n)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}let{config:o}=this,l=this.playhead,d=J.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:c,len:h}=d,u=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(h>u||h&&!this.buffering)return;let f=this.getNextFragment(c,a);if(!f)return;if(ve(f)){var t;let g=f.sn-a.startSN,m=a.fragments[g-1];f.cc===m?.cc&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(m)===ye.NOT_LOADED&&(f=m)}this.loadFragment(f,n,c)}}loadFragment(e,t,i){let s=this.fragmentTracker.getState(e);(s===ye.NOT_LOADED||s===ye.PARTIAL)&&super.loadFragment(e,t,i)}get mediaBufferTimeRanges(){return new Rr(this.tracksBuffered[this.currentTrackId]||[])}},Rr=class{constructor(e){this.buffered=void 0;let t=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return e[s][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}},yg={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},wd=r=>String.fromCharCode(yg[r]||r),Je=15,Ze=42,vg={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Eg={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Tg={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Sg={25:2,26:4,29:6,30:8,31:10,27:13,28:15},bg=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Pr=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;oe.log(`${this.time} [${e}] ${i}`)}}},Pt=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},_r=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),As=class{constructor(){this.styles=_r}get foreground(){return this.styles.foreground}set foreground(e){let t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){let t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=_r}setStyles(e){let t=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(e,"foreground")?e.foreground:t.foreground,underline:i.call(e,"underline")?e.underline:t.underline,italics:i.call(e,"italics")?e.italics:t.italics,background:i.call(e,"background")?e.background:t.background,flash:i.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},kr=class{constructor(){this.uchar=" ",this.penState=new As}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}},Dr=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new As,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ze;t++)this.chars.push(new kr);this.logger=e}equals(e){let t=this.chars,i=e.chars;for(let s=0;s<Ze;s++){let n=t[s],a=i[s];if(n.uchar!==a.uchar)return!1;let o=n.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<Ze;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<Ze;t++){let i=e[t];if(i.uchar!==" ")return!1;let s=i.penState.styles;if(s!==_r&&(s.foreground!=="white"||s.underline||s.italics||s.background!=="black"||s.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Ze&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ze-1)}moveCursor(e){let t=Math.min(this.pos+e,Ze);if(e>1)for(let i=this.pos+1;i<t;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=wd(e);if(this.pos>=Ze){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ze;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<Ze;i++){let s=this.chars[i].uchar;s!==" "&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},ni=class{constructor(e){this.rows=[],this.currRow=Je-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Je;t++)this.rows.push(new Dr(e));this.logger=e}reset(){for(let e=0;e<Je;e++)this.rows[e].clear();this.currRow=Je-1}equals(e){let t=!0;for(let i=0;i<Je;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<Je;t++){let i=this.rows[t].chars,s=e.rows[t].chars;for(let n=0;n<Ze;n++){let a=i[n],o=s[n];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Je;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+fe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Je;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d])}}this.currRow=t;let i=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground}let s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+fe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],i="",s=-1;for(let n=0;n<Je;n++){let a=this.rows[n].getTextString();a&&(s=n+1,e?t.push("Row "+s+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
42
+ `)),i}getTextAndFormat(){return this.rows}},Cr=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new ni(i),this.nonDisplayedMemory=new ni(i),this.lastOutputScreen=new ni(i),this.currRollUpRow=this.displayedMemory.rows[Je-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Je-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(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"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{let i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+fe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},xs=class{constructor(e,t,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=xg(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Pr,this.field=e,this.outputFilters=[null,t,i]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var i;this.outputFilters[e]=t,(i=this.channels[e])==null||i.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new Cr(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){let s=t[i]&127,n=t[i+1]&127,a=!1,o=null;if(s===0&&n===0)continue;this.logger.log(3,()=>"["+Pt([t[i],t[i+1]])+"] -> ("+Pt([s,n])+")");let l=this.cmdHistory;if(s>=16&&s<=31){if(Ag(s,n,l)){Gi(null,null,l),this.logger.log(3,()=>"Repeated command ("+Pt([s,n])+") is dropped");continue}Gi(s,n,this.cmdHistory),a=this.parseCmd(s,n),a||(a=this.parseMidrow(s,n)),a||(a=this.parsePAC(s,n)),a||(a=this.parseBackgroundAttributes(s,n))}else Gi(null,null,l);if(!a&&(o=this.parseChars(s,n),o)){let c=this.currentChannel;c&&c>0?this.getChannel(c).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Pt([s,n])+" orig: "+Pt([t[i],t[i+1]]))}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(i||s))return!1;let n=e===20||e===21||e===23?1:2,a=this.getChannel(n);return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let s=this.channels[i];return s?(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Pt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i,s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(s||n))return!1;let a=e<=23?1:2;return t>=64&&t<=95?i=a===1?vg[e]:Tg[e]:i=a===1?Eg[e]:Sg[e],this.getChannel(a).setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0}interpretPAC(e,t){let i,s={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(e,t){let i,s=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+wd(a)+"' in channel "+i),s=[a]}else e>=32&&e<=127&&(s=t===0?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+Pt(s).join(",")),s}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(i||s))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=bg[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));let o=e<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}Gi(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}};function Gi(r,e,t){t.a=r,t.b=e}function Ag(r,e,t){return t.a===r&&t.b===e}function xg(){return{a:null,b:null}}var Gt=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},wr=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Vo(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Gt(this,"textTrack1"),t=new Gt(this,"textTrack2"),i=new Gt(this,"textTrack3"),s=new Gt(this,"textTrack4");this.cea608Parser1=new xs(1,e,t),this.cea608Parser2=new xs(3,i,s)}addCues(e,t,i,s,n){let a=!1;for(let l=n.length;l--;){let d=n[l],c=Ig(d[0],d[1],t,i);if(c>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],i),a=!0,c/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let l=this.cueCache[e];if(l){let d=this.Cues.newCue(null,t,i,s);d.length&&l.push.apply(l,d)}else{let d=this.captionsTracks[e].track;this.Cues.newCue(d,t,i,s)}}else{var o;let l=this.Cues.newCue(null,t,i,s),d=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:d})}}onInitPtsFound(e,{id:t,timestampOffsets:i}){let{unparsedVttFrags:s}=this;t===H.MAIN&&(this.initPTS=i),s.length&&(this.unparsedVttFrags=[],s.forEach(n=>{this.initPTS[n.frag.cc]?this.onFragLoaded(y.FRAG_LOADED,n):this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,cueCache:s,media:n}=this,{label:a,languageCode:o}=t[e];n&&(s[e]=[],i[e]=oa(n,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){let{captionsTracks:s,cueCache:n}=this;for(let a in s)s[a].remove(),delete n[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Vo(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!id(this.tracks,i)){let s=i.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:s})}this.tracks=i}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;let n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){var i,s;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,c=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(d!==o+1||d===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=c}}onFragLoaded(e,t){let{frag:i,payload:s}=t;if(i.level<this.tracks.length&&i.type===H.SUBTITLE)if(s.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o?.textCodec===hr?this._parseIMSC1(t):this._parseVTTs(t)}}else{let n="part"in t?t.part:null;this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:n,error:new Error("Empty subtitle payload")})}}_parseIMSC1(e){let{frag:t,payload:i}=e,s="part"in e?e.part:null,n=this.hls;Co(i,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:s})},a=>{n.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),n.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:s,error:a})})}_parseVTTs(e){var t;let{frag:i,payload:s}=e,n="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:o}=this,l=a.length-1;if(!a[i.cc]&&l===-1){o.push(e);return}let d=this.hls,c=(t=i.initSegment)==null?void 0:t.data,h=c?Ye(c,new Uint8Array(s)).buffer:s;Qf(h,this.initPTS[i.cc],this.vttCCs,i.cc,(n&&!c?n:i).start,u=>{this._appendCues(u,i.level),d.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:n})},u=>{let f=u.message.startsWith("Missing initPTS");if(d.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${u}`),f){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);d.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:n,error:u})})}_fallbackToIMSC1(e){let{frag:t,payload:i}=e,s=this.tracks[t.level];s.textCodec||Co(i,this.initPTS[t.cc],()=>{s.textCodec=hr,this._parseIMSC1(e)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){var s;let n=(s=this.tracks[t].trackNode)==null?void 0:s.track;if(!n||n.mode==="disabled")return;e.forEach(a=>ur(n,a))}else{let n=this.tracks[t];if(!n)return;let a=n.default?"default":"subtitles"+t;i.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:n})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===H.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:s}=t;if(!(i.type===H.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<s.length;n++){let a=s[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var i;let{type:s,timeRanges:n}=t;if(s==="video"&&(i=n[s])!=null&&i.length){let{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var d;let c=(d=a[l])==null?void 0:d.track;if(c){let h=o[l];for(let u=0;u<h.length;u++)ur(c,h[u])}delete o[l]})}}}onBufferFlushing(e,t){let{startOffset:i,endOffset:s,endOffsetSubtitles:n,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<s)){if(!a||a==="video"){let{captionsTracks:l,cueCache:d}=this;Object.keys(l).forEach(c=>fr(l[c].track,i,s)),Object.keys(d).forEach(c=>{let h=d[c];for(let u=h.length;u--;){let f=h[u];f.startTime>=i&&f.endTime<=s&&h.splice(u,1)}})}this.config.renderTextTracksNatively&&i===0&&n!==void 0&&this.tracks.forEach(l=>{var d;let c=(d=l.trackNode)==null?void 0:d.track;c&&fr(c,i,n)})}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,s=2;for(let n=0;n<i;n++){let a=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&a)!==0){let c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(l))}}return t}};function Ig(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function Vo(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var Lg=/\s/,Rg={newCue(r,e,t,i){let s=[],n,a,o,l,d,c=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,d="",!n.isEmpty()){var h;for(let m=0;m<n.chars.length;m++)Lg.test(n.chars[m].uchar)&&o?l++:(d+=n.chars[m].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Ld(d.trim()),g=aa(e,t,f);r!=null&&(h=r.cues)!=null&&h.getCueById(g)||(a=new c(e,t,f),a.id=g,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),s.forEach(u=>ur(r,u))),s}},Is=class{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new ri}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,i){let s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ai(e,t,!0))this.retry(e);else{var i;oe.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Ur(e,i.retry),i.retry++,oe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function Pg(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var _g=/(\d+)-(\d+)\/(\d+)/,Ls=class extends Is{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||wg}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:e,context:t,stats:i}=this;if(!e||!t)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;let s=kg(t,this.controller.signal),n=t.responseType==="arraybuffer",a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=o&&B(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(vi(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var h;this.response=c;let u=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(u-i.loading.start)),!c.ok){let{status:g,statusText:m}=c;throw new Mr(m||"fetch, bad network response",g,c)}i.loading.first=u,i.total=Cg(c.headers)||i.total;let f=(h=this.callbacks)==null?void 0:h.onProgress;return f&&B(e.highWaterMark)?this.loadProgressively(c,i,t,e.highWaterMark,f):n?c.arrayBuffer():t.responseType==="json"?c.json():c.text()}).then(c=>{var h,u;let f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);let g=c[a];g&&(i.loaded=i.total=g);let m={url:f.url,data:c,code:f.status},p=(h=this.callbacks)==null?void 0:h.onProgress;p&&!B(e.highWaterMark)&&p(i,t,c,f),(u=this.callbacks)==null||u.onSuccess(m,i,t,f)}).catch(c=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;let h=c&&c.code||0,u=c?c.message:null,f=e.loadPolicy.errorRetry,g=i.retry,m={url:t.url,data:void 0,code:h};if(ai(f,g,!1,m))this.retry(f);else{var p;oe.error(`${h} while loading ${t.url}`),(p=this.callbacks)==null||p.onError({code:h,text:u},t,c?c.details:null,i)}})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,n){let a=new cs,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=d.value,h=c.length;return t.loaded+=h,h<s||a.dataLength?(a.push(c),a.dataLength>=s&&n(t,i,a.flush().buffer,e)):n(t,i,c.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function kg(r,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ce({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function Dg(r){let e=_g.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Cg(r){let e=r.get("Content-Range");if(e){let i=Dg(e);if(B(i))return i}let t=r.get("Content-Length");if(t)return parseInt(t)}function wg(r,e){return new self.Request(r.url,e)}var Mr=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},Mg=(r,e,t)=>Math.max(e,Math.min(r,t)),Og=/^age:\s*[\d.]+\s*$/im,Rs=class extends Is{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n.call(this,i,t.url,t)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n.call(this,i,t.url,t)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(let o in s)e.setRequestHeader(o,s[o]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&B(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let s=t.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let d=t.status,c=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let g=c??t.response;if(g!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);let m=t.responseType==="arraybuffer"?g.byteLength:g.length;i.loaded=i.total=m,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let p=(a=this.callbacks)==null?void 0:a.onProgress;p&&p(i,e,g,t);let v={url:t.responseURL,data:g,code:d};e.rangeEnd&&m!==e.rangeEnd-e.rangeStart&&oe.warn(`Payload length ${m} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(v,i,e,t);return}}let h=n.loadPolicy.errorRetry,u=i.retry,f={url:e.url,data:void 0,code:d};if(ai(h,u,!1,f))this.retry(h);else{var l;oe.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,i)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Og.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},Fg={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Ng=Y(Y({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Rs,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Cl,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:Fg},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,streamController:Ts,abrController:In,bufferController:Qn,capLevelController:Zn,errorController:Ln,fpsController:ar,id3TrackController:yr,gapController:mr,latencyController:Ir},Bg()),{},{subtitleStreamController:Lr,subtitleTrackController:gr,timelineController:wr,audioStreamController:Yn,audioTrackController:jn,emeController:Es,cmcdController:nr,contentSteeringController:rr,iframeController:Er,interstitialsController:xr});function Bg(){return{cueHandler:Rg,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function $g(r,e,t){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(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){let a=e.liveMaxUnchangedPlaylistRefresh,o=Mg(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}let i=Or(r),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(c=>{let h=`${a}Loading${c}`,u=e[h];if(u!==void 0&&l){d.push(h);let f=i[o].default;switch(e[o]={default:f},c){case"TimeOut":f.maxLoadTimeMs=u,f.maxTimeToFirstByteMs=u;break;case"MaxRetry":f.errorRetry.maxNumRetry=u,f.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":f.errorRetry.retryDelayMs=u,f.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=u,f.timeoutRetry.maxRetryDelayMs=u;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${fe(e[o])}`)}),Y(Y({},i),e)}function Or(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(Or):Object.keys(r).reduce((e,t)=>(e[t]=Or(r[t]),e),{}):r}function Ug(r,e){let t=r.loader;t!==Ls&&t!==Rs?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Pg()&&(r.loader=Ls,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Fr=class extends Ei{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.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,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,s=[],n={},a={},o=!1,l=!1,d=!1,c=!1;t.levels.forEach(h=>{let u=h.attrs,f=Ho(h,i),{audioCodec:g,videoCodec:m,imageCodec:p,width:v,height:T}=h;if(!f){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}o||(o=!!(v&&T)),l||(l=!!m),d||(d=!!g),c||(c=!!p);let{CODECS:E,"FRAME-RATE":S,"HDCP-LEVEL":b,"PATHWAY-ID":A,RESOLUTION:x,"VIDEO-RANGE":R}=u,I=`${`${A||"."}-`}${h.bitrate}-${x}-${S}-${E}-${R}-${b}`;if(n[I])if(n[I].uri!==h.url&&!h.attrs["PATHWAY-ID"]){let k=a[I]+=1;h.attrs["PATHWAY-ID"]=new Array(k+1).join(".");let D=this.createLevel(h);n[I]=D,s.push(D)}else h.iframes||(n[I].addGroupId("audio",u.AUDIO),n[I].addGroupId("text",u.SUBTITLES));else{let k=this.createLevel(h);n[I]=k,a[I]=1,s.push(k)}}),this.filterAndSortMediaOptions(s,t,o,l,d,c)}createLevel(e){let t=new Ct(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!Od(i.videoCodec,this.hls.config.preferManagedMediaSource)){let s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=yl(s,[])}return t}filterAndSortMediaOptions(e,t,i,s,n,a){var o;let l=[],d=[],c=e,h=((o=t.stats)==null?void 0:o.parsing)||{},u=this.hls.config.preferManagedMediaSource;if((i||s)&&n&&(c=c.filter(({videoCodec:b,videoRange:A,width:x,height:R})=>(!!b||!!(x&&R))&&oh(A))),s&&a&&(c=c.filter(b=>!b.imageCodec)),c.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",A=b;t.levels.length&&(A=`one or more CODECS in variant not supported: ${fe(t.levels.map(R=>R.attrs.CODECS).filter((R,P,I)=>I.indexOf(R)===P))}`,this.warn(A),b+=` (${A})`);let x=new Error(b);this.hls.trigger(y.ERROR,{type:W.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:x,reason:A})}}),h.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(b=>!b.audioCodec||Md(b.audioCodec,u)),Ko(l)),t.subtitles&&(d=t.subtitles,Ko(d));let f=c.slice(0);c.sort((b,A)=>{if(b.attrs["HDCP-LEVEL"]!==A.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(A.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&b.height!==A.height)return b.height-A.height;if(b.frameRate!==A.frameRate)return b.frameRate-A.frameRate;if(b.videoRange!==A.videoRange)return Zi.indexOf(b.videoRange)-Zi.indexOf(A.videoRange);if(b.videoCodec!==A.videoCodec){let x=Pa(b.videoCodec),R=Pa(A.videoCodec);if(x!==R)return R-x}if(b.uri===A.uri&&b.codecSet!==A.codecSet){let x=Xi(b.codecSet),R=Xi(A.codecSet);if(x!==R)return R-x}return b.averageBitrate!==A.averageBitrate?b.averageBitrate-A.averageBitrate:0});let g=f[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==f.length)){for(let b=0;b<f.length;b++)if(f[b].pathwayId===c[0].pathwayId){g=f[b];break}}this._levels=c;for(let b=0;b<c.length;b++)if(c[b]===g){var m;this._firstLevel=b;let A=g.bitrate,x=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${A}`),((m=this.hls.userConfig)==null?void 0:m.abrEwmaDefaultEstimate)===void 0){let R=Math.min(A,this.hls.config.abrEwmaDefaultEstimateMax);R>x&&x===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=R)}break}let p=t.iframeVariants.filter(b=>Ho(b,u));this._iframeVariants=p;let v=n&&!s,T=this.hls.config,E=!!(T.audioStreamController&&T.audioTrackController),S={levels:c,audioTracks:l,subtitleTracks:d,iframeVariants:p,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:E&&!v&&l.some(b=>!!b.url)};h.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,S)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:c,reason:c.message}),h)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let c=this.switchParams(a.uri,s?.details,d);this.loadPlaylist(c)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===te.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===H.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;let{level:s,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(s,t,l)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(y.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let s=this.hls.config.abrSwitchInterval;if(s>0){let n=performance.now(),a=n-this.lastABRSwitchTime,o=s*1e3;if(this.lastABRSwitchTime>-1&&a<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms < ${o}ms / ${s}s)`);return}this.lastABRSwitchTime=n,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms >= ${o}ms / ${s}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));$l(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(y.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function Md(r,e){return ci(r,"audio",e)}function Od(r,e){return ci(r,"video",e)}function Ho(r,e){let{audioCodec:t,videoCodec:i}=r;t&&(r.audioCodec=t=Qi(t,e)||void 0),i&&(i=r.videoCodec=Zc(i));let{unknownCodecs:s}=r;return!(s?.length||0||t&&!Md(t,e)||i&&!Od(i,e))}function Ko(r){let e={};r.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var Nr=class extends Oe{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyLoaderInfo){let s=this.keyLoaderInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,i){return this.emeController?this.emeController.loadClear(e,t,i):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(i=>this.loadInternal(e,t,i)):this.loadInternal(e,t)}loadInternal(e,t,i){i&&e.setKeyFormat(i);let s=e.decryptdata;if(!s){let a=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(mt(e,L.KEY_LOAD_ERROR,a))}let n=e;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(n):t?t.then(()=>this.loadKeyEME(n)):this.loadKeyEME(n);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(n);default:return Promise.reject(mt(e,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let i=Cc(e.initSegment.data);if(i.length){let s=i[0],n=e.decryptdata.uri;if(s.some(a=>a!==0))this.log(`Using keyId found in init segment ${Ie(s)} keyUri: ${n}`),wt.setKeyIdForUri(n,s);else{let a=wt.addKeyIdForUri(n);this.log(`Patching empty keyId with ${Ie(a)} keyUri: ${n}`),s=a}e.decryptdata.keyId=s}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(mt(e,L.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,i=t.uri;if(!i)return Promise.reject(mt(e,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let s=this.keyLoaderInfo[i];if(s){if(s.decryptdata.key)return t.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then(d=>(t.key=s.decryptdata.key,Y(Y({},d),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ie(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);let n=this.config,a=n.loader,o=new a(n);e.keyLoader=o;let l=this.keyLoaderInfo[i]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((d,c)=>{let h={type:te.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:i},u=n.keyLoadPolicy.default,f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,p,v,T)=>{let{frag:E,keyInfo:S,url:b}=v;if(!E.decryptdata||S!==this.keyLoaderInfo[b])return c(mt(E,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),T));S.decryptdata.key=E.decryptdata.key=new Uint8Array(m.data),E.keyLoader=S.loader=S.keyLoadPromise=null,d({frag:E,keyInfo:S})},onError:(m,p,v,T)=>{this.resetLoader(p),c(mt(e,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),v,Y({url:i,data:void 0},m)))},onTimeout:(m,p,v)=>{this.resetLoader(p),c(mt(e,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(m,p,v)=>{this.resetLoader(p),c(mt(e,L.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};o.load(h,f,g)})}resetLoader(e){let{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[s],n&&n.destroy()}};function mt(r,e=L.KEY_LOAD_ERROR,t,i,s){return new We({type:W.NETWORK_ERROR,details:e,fatal:!1,frag:r,response:s,error:t,networkDetails:i||null})}function qo(r){let{type:e}=r;switch(e){case te.AUDIO_TRACK:return H.AUDIO;case te.SUBTITLE_TRACK:return H.SUBTITLE;default:return H.MAIN}}function mn(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Br=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:te.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:te.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:te.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let i=this.loaders[te.LEVEL];if(i){let s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[te.LEVEL])}}load(e){var t;let i=this.hls.config,s=this.getInternalLoader(e);if(s){let d=this.hls.logger,c=s.context;if(c?.levelOrTrack===e.levelOrTrack&&(c.url===e.url||c.deliveryDirectives&&!e.deliveryDirectives)){c.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${c.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===te.MANIFEST?n=i.manifestLoadPolicy.default:n=ce({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),B((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===te.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===te.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===te.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let c=d.partTarget,h=d.targetduration;if(c&&h){let u=Math.max(c*3,h*.8)*1e3;n=ce({},n,{maxTimeToFirstByteMs:Math.min(u,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,n.maxTimeToFirstByteMs)})}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,c,h,u)=>{let f=this.getInternalLoader(h);this.resetInternalLoader(h.type);let g=d.data;c.parsing.start=performance.now(),Et.isMediaPlaylist(g)||h.type!==te.MANIFEST?this.handleTrackOrLevelPlaylist(d,c,h,u||null,f):this.handleMasterPlaylist(d,c,h,u)},onError:(d,c,h,u)=>{this.handleNetworkError(c,h,!1,d,u)},onTimeout:(d,c,h)=>{this.handleNetworkError(c,h,!0,void 0,d)}};s.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){let n=this.hls,a=e.data,o=mn(e,i),l=Et.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}let{contentSteering:d,levels:c,iframeVariants:h,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,c.forEach(E=>{let{unknownCodecs:S}=E;if(S){let{preferManagedMediaSource:b}=this.hls.config,{audioCodec:A,videoCodec:x}=E;for(let R=S.length;R--;){let P=S[R];ci(P,"audio",b)?(E.audioCodec=A=A?`${A},${P}`:P,Kt.audio[A.substring(0,4)]=2,S.splice(R,1)):ci(P,"video",b)&&(E.videoCodec=x=x?`${x},${P}`:P,Kt.video[x.substring(0,4)]=2,S.splice(R,1))}}});let{AUDIO:p=[],SUBTITLES:v,"CLOSED-CAPTIONS":T}=Et.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(S=>!S.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new pe({}),bitrate:0,url:""})),n.trigger(y.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:v,iframeVariants:h,captions:T,contentSteering:d,url:o,stats:t,networkDetails:s,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,s,n){let a=this.hls,{id:o,level:l,type:d}=i,c=mn(e,i),h=B(l)?l:B(o)?o:0,u=qo(i),f=Et.parseLevelPlaylist(e.data,c,h,u,0,this.variableList);if(d===te.MANIFEST){let g={attrs:new pe({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=t.loading.start+Fl(f,0),a.trigger(y.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:c,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:t.type===te.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===te.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===te.AUDIO_TRACK||e.type===te.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=L.UNKNOWN,d=!1,c=this.getInternalLoader(e);switch(e.type){case te.MANIFEST:l=i?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,d=!0;break;case te.LEVEL:l=i?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,d=!1;break;case te.AUDIO_TRACK:l=i?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case te.SUBTITLE_TRACK:l=i?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,d=!1;break}c&&this.resetInternalLoader(e.type);let h={type:W.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:n};if(s){let u=e.url;t&&"url"in t&&(u=t.url),h.response=Y({url:u,data:void 0},s)}this.hls.trigger(y.ERROR,h)}handlePlaylistLoaded(e,t,i,s,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:c,id:h,groupId:u,deliveryDirectives:f}=s,g=mn(t,s),m=qo(s),p=typeof s.level=="number"&&m===H.MAIN?d:void 0;c&&"iframes"in c&&c.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);let v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:t,context:s,level:p,parent:m,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){let T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:W.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:t,context:s,level:p,parent:m,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case te.MANIFEST:case te.LEVEL:if(p){if(!c)p=0;else if(c!==o.levels[p]){let T=o.levels.indexOf(c);T>-1&&(p=T)}}o.trigger(y.LEVEL_LOADED,{details:e,levelInfo:c||o.levels[0],level:p||0,id:h||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===te.MANIFEST,context:s});break;case te.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,track:c,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:f,context:s});break;case te.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,track:c,id:h||0,groupId:u||"",stats:i,networkDetails:n,deliveryDirectives:f,context:s});break}}},xt=class r{static get version(){return pi}static isMSESupported(){return Dd()}static isSupported(){return lg()}static getMediaSource(){return bt()}static get Events(){return y}static get MetadataSchema(){return Me}static get ErrorTypes(){return W}static get ErrorDetails(){return L}static get DefaultConfig(){return r.defaultConfig?r.defaultConfig:Ng}static set DefaultConfig(e){r.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new zr,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=rc(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),i=this.config=$g(r.DefaultConfig,e,t);this.userConfig=e,i.progressive&&Ug(i,t);let{streamController:s,abrController:n,bufferController:a,capLevelController:o,errorController:l,fpsController:d,id3TrackController:c,iframeController:h,gapController:u}=i,f=new l(this),g=this.abrController=new n(this),m=new Rn(this),p=i.interstitialsController,v=p?this.interstitialsController=new p(this,r):null,T=a?this.bufferController=new a(this,m):null,E=o?this.capLevelController=new o(this):null,S=d?new d(this):null,b=i.cmcdController,A=b?this.cmcdController=new b(this):null,x=new Br(this),R=i.contentSteeringController,P=R?new R(this):null,I=this.levelController=new Fr(this,P),k=c?new c(this):void 0,D=new Nr(this.config,this.logger),F=this.streamController=new s(this,m,D),G=this.gapController=u?new u(this,m):void 0;E&&E.setStreamController(F);let $=[x,I,F];v&&$.splice(1,0,v),P&&$.splice(1,0,P),this.networkControllers=$;let C=[g];T&&C.push(T),G&&C.push(G),E&&C.push(E),S&&(S.setStreamController(F),C.push(S)),k&&C.push(k),C.push(m),this.audioTrackController=this.createController(i.audioTrackController,$);let M=i.audioStreamController;M&&$.push(this.audioStreamController=new M(this,m,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,$);let w=i.subtitleStreamController;w&&$.push(this.subtititleStreamController=new w(this,m,D)),this.createController(i.timelineController,C),D.emeController=this.emeController=this.createController(i.emeController,C),A&&C.push(A),this.latencyController=this.createController(i.latencyController,C),this.coreComponents=C,this.iframeController=h?new h(this,r):void 0,$.push(f);let N=f.onErrorOut;typeof N=="function"&&this.on(y.ERROR,N,f),this.on(y.MANIFEST_LOADED,x.onManifestLoaded,x)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;let s=e===y.ERROR;this.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(y.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,this.iframeController=void 0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(y.ERROR,{type:W.OTHER_ERROR,details:L.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(y.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(y.MEDIA_DETACHING,e),this._media=null,this.trigger(y.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,i={transferMedia:t};return this.trigger(y.MEDIA_DETACHING,i),this.trigger(y.MEDIA_DETACHED,i),t}loadSource(e){var t;this.stopLoad();let i=this.media,s=this._url,n=this._url=$r.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),i&&s&&(s!==n||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(y.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==_.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[H.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[H.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[H.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=this.started,i=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Zo()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=this.capLevelController,i=!!e;t&&i!==this.config.capLevelToPlayerSize&&(i?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){ah(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let n=s;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){let{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){let e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=Sl(t);return vl(e,i,navigator.mediaCapabilities)}};xt.defaultConfig=void 0;var Em=.045,Fd={textSizeFraction:.045,foregroundColor:"#FFFFFF",backgroundColor:"rgba(0,0,0,0.5)",windowColor:"rgba(0,0,0,0)",edgeType:"NONE",edgeColor:"#000000",applyEmbeddedStyles:!0,fontFamily:null},ue={NETWORK_CONNECTION_FAILED:2e3,NETWORK_TIMEOUT:2001,NETWORK_HTTP_STATUS:2002,SOURCE_MALFORMED:3e3,SOURCE_UNSUPPORTED:3001,SOURCE_NOT_FOUND:3002,DRM_LICENSE_FAILED:4e3,DRM_LICENSE_HTTP_STATUS:4001,DRM_TOKEN_FETCH_FAILED:4002,DRM_PROVISIONING_FAILED:4003,DRM_SESSION_EXPIRED:4004,DRM_UNSUPPORTED:4005,DECODER_INIT_FAILED:5e3,DECODING_FAILED:5001,AUDIO_OUTPUT_FAILED:5002,BEHIND_LIVE_WINDOW:6e3,UNKNOWN:9e3},Tm="1.1.0";var Gg={2e3:"NETWORK_CONNECTION_FAILED",2001:"NETWORK_TIMEOUT",2002:"NETWORK_HTTP_STATUS",3e3:"SOURCE_MALFORMED",3001:"SOURCE_UNSUPPORTED",3002:"SOURCE_NOT_FOUND",4e3:"DRM_LICENSE_FAILED",4001:"DRM_LICENSE_HTTP_STATUS",4002:"DRM_TOKEN_FETCH_FAILED",4003:"DRM_PROVISIONING_FAILED",4004:"DRM_SESSION_EXPIRED",4005:"DRM_UNSUPPORTED",5e3:"DECODER_INIT_FAILED",5001:"DECODING_FAILED",5002:"AUDIO_OUTPUT_FAILED",6e3:"BEHIND_LIVE_WINDOW",9e3:"UNKNOWN"};function Ee(r,e,t,i,s,n){return{code:r,category:e,message:t,retryable:i,codeName:Gg[r]??`HTTP_${r}`,...s!==void 0?{httpStatusCode:s}:{},...n!==void 0?{cause:n}:{}}}function Nd(r){switch(r?.code){case MediaError.MEDIA_ERR_NETWORK:return Ee(ue.NETWORK_CONNECTION_FAILED,"Network",r.message||"network error while fetching media",!0);case MediaError.MEDIA_ERR_DECODE:return Ee(ue.DECODING_FAILED,"Renderer",r.message||"media decode failed",!0);case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return Ee(ue.SOURCE_UNSUPPORTED,"Source",r.message||"source not supported by this browser",!1);default:return Ee(ue.UNKNOWN,"Unknown",r?.message||"unknown playback error",!0,void 0,r)}}function Bd(r){let e=r.response?.code,t=r.details;if(e&&e>=400){let i=e===404?ue.SOURCE_NOT_FOUND:ue.NETWORK_HTTP_STATUS;return Ee(i,e===404?"Source":"Network",`${t} (HTTP ${e})`,e>=500,e,r.error)}if(r.type==="keySystemError"||t.startsWith("keySystem"))return t.includes("NoAccess")||t.includes("NoConfiguredLicense")?Ee(ue.DRM_UNSUPPORTED,"Drm","no supported DRM key system in this browser",!1,void 0,r.error):t.includes("ServerCertificate")?Ee(ue.DRM_PROVISIONING_FAILED,"Drm",t,!0,void 0,r.error):t.includes("LicenseRequestFailed")?Ee(e?ue.DRM_LICENSE_HTTP_STATUS:ue.DRM_LICENSE_FAILED,"Drm",t,!0,e,r.error):t.includes("SessionUpdateFailed")||t.includes("NoKeys")||t.includes("StatusInternalError")?Ee(ue.DRM_LICENSE_FAILED,"Drm",t,!0,void 0,r.error):t.includes("Expired")?Ee(ue.DRM_SESSION_EXPIRED,"Drm",t,!0,void 0,r.error):Ee(ue.DRM_LICENSE_FAILED,"Drm",t,!0,void 0,r.error);if(r.type==="networkError"){let i=t.includes("Timeout")||t.includes("TIMEOUT");return Ee(i?ue.NETWORK_TIMEOUT:ue.NETWORK_CONNECTION_FAILED,"Network",t,!0,void 0,r.error)}return r.type==="mediaError"?t.includes("Parsing")||t.includes("PARSING")||t.includes("manifest")?Ee(ue.SOURCE_MALFORMED,"Source",t,!1,void 0,r.error):Ee(ue.DECODING_FAILED,"Renderer",t,!0,void 0,r.error):t.includes("levelSwitch")||t.includes("liveBackBuffer")?Ee(ue.BEHIND_LIVE_WINDOW,"Live",t,!0,void 0,r.error):Ee(ue.UNKNOWN,"Unknown",t,!r.fatal,void 0,r.error)}var Vg="MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV4yKAojBJAh5bd1bJWOc75e4psyXk2HXRlis9YZMcG0fYB5RfkQISQ5hlNVHZisVGAAGV9Dg9tYRY8BbnJTzhg==",$d=new Map;function da(r,e,t=Vg){let i=`${r??""}|${e}|${t}`,s=$d.get(i);return s||(s=Hg(r,e,t),$d.set(i,s)),s}async function Hg(r,e,t){if(!r)return{licensed:!1,reason:"no license key set"};let i=r.split(".");if(i.length!==3||i[0]!=="OGP1")return{licensed:!1,reason:"malformed license key"};let s=Ud(i[1]),n=Ud(i[2]);if(!s||!n)return{licensed:!1,reason:"malformed payload"};if(!globalThis.crypto?.subtle)return{licensed:!1,reason:"license verification requires a secure context (https or localhost)"};if(!await Kg(s,n,t))return{licensed:!1,reason:"invalid signature"};let a;try{a=JSON.parse(new TextDecoder().decode(s))}catch{return{licensed:!1,reason:"unreadable payload"}}if(!(Array.isArray(a.apps)?a.apps:[]).some(d=>Wg(e,d)))return{licensed:!1,reason:`license not valid for ${e}`};let l=typeof a.exp=="string"?a.exp:"";return Yg(l)?{licensed:!1,reason:`license expired ${l}`}:{licensed:!0,licensee:typeof a.to=="string"?a.to:"unknown",edition:typeof a.ed=="string"?a.ed:"standard",exp:l}}async function Kg(r,e,t){try{let i=Gd(t);if(!i)return!1;let s=await crypto.subtle.importKey("spki",la(i),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),n=qg(e);return n?await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,la(n),la(r)):!1}catch{return!1}}function qg(r){let e=0;if(r[e++]!==48)return null;let t=r[e++];t&128&&(e+=t&127);let i=()=>{if(r[e++]!==2)return null;let o=r[e++];if(o&128)return null;let l=e;for(e+=o;o>32&&r[l]===0;)l++,o--;if(o>32)return null;let d=new Uint8Array(32);return d.set(r.slice(l,l+o),32-o),d},s=i(),n=i();if(!s||!n)return null;let a=new Uint8Array(64);return a.set(s,0),a.set(n,32),a}function Wg(r,e){if(e.startsWith("*.")){let t=e.slice(2);return t.length>0&&(r===t||r.endsWith("."+t))}return r===e}function Yg(r){if(!r)return!0;let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`>r}function Ud(r){let e=r.replaceAll("-","+").replaceAll("_","/");for(;e.length%4!==0;)e+="=";return Gd(e)}function Gd(r){try{let e=atob(r),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}catch{return null}}function la(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}async function Cs(r,e,t=8e3){let i;for(let s=1;s<=3;s++)try{return await jg(r(e),t)}catch(n){i=n,s<3&&await zg(500*s)}throw i}function jg(r,e){return new Promise((t,i)=>{let s=setTimeout(()=>i(new Error(`DRM token provider timed out after ${e} ms`)),e);r.then(n=>{clearTimeout(s),t(n)},n=>{clearTimeout(s),i(n)})})}var zg=r=>new Promise(e=>setTimeout(e,r));function Hd(r,e,t,i,s){let n=!1,a=null,o=0,l=[],d=Vd(e.certificateUrl,void 0,"certificate"),c=async u=>{let{initDataType:f,initData:g}=u;if(!(n||!g))try{if(!a){a=await(await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[f],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'}]}])).createMediaKeys();let v=await d;await a.setServerCertificate(v),await r.setMediaKeys(a)}let m=a.createSession();l.push(m),m.addEventListener("message",p=>{(async()=>{try{let v=o>0;o++;let T={};if(e.tokenProvider)try{T=await Cs(e.tokenProvider,{licenseUrl:e.licenseUrl,renewal:v})}catch(S){throw{ogError:Ee(ue.DRM_TOKEN_FETCH_FAILED,"Drm",`DRM token provider failed: ${S instanceof Error?S.message:"error"}`,!0,void 0,S)}}let E=await Vd(e.licenseUrl,{method:"POST",headers:{"Content-Type":"application/octet-stream",...e.headers,...T},body:p.message},"license");n||(await m.update(E),v?s?.():i?.())}catch(v){h(v)}})()}),await m.generateRequest(f,g)}catch(m){h(m)}},h=u=>{n||(u&&typeof u=="object"&&"ogError"in u?t(u.ogError):t(Ee(ue.DRM_LICENSE_FAILED,"Drm",u instanceof Error?u.message:"FairPlay key exchange failed",!0,void 0,u)))};return r.addEventListener("encrypted",c),()=>{n=!0,r.removeEventListener("encrypted",c),l.forEach(u=>void u.close().catch(()=>{}))}}async function Vd(r,e,t){let i;try{i=await fetch(r,{...e,signal:AbortSignal.timeout(15e3)})}catch(s){throw{ogError:Ee(t==="certificate"?ue.DRM_PROVISIONING_FAILED:ue.DRM_LICENSE_FAILED,"Drm",`FairPlay ${t} request failed: ${s instanceof Error?s.message:"network error"}`,!0,void 0,s)}}if(!i.ok)throw{ogError:Ee(ue.DRM_LICENSE_HTTP_STATUS,"Drm",`FairPlay ${t} HTTP ${i.status}`,i.status>=500,i.status)};return i.arrayBuffer()}var Xg=/(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?/;function Kd(r){let e=Xg.exec(r.trim());if(!e)return null;let t=Number(e[1]??0),i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4].padEnd(3,"0")):0;return((t*60+i)*60+s)*1e3+n}function Qg(r,e){let t=[],i=r.split(/\r?\n/);for(let s=0;s<i.length;s++){let n=i[s];if(!n.includes("-->"))continue;let[a,o]=n.split("-->"),l=Kd(a??""),d=Kd(o??""),c=(i[s+1]??"").trim();if(l===null||d===null||!c)continue;let[h,u]=c.split("#"),f;try{f=new URL(h,e).toString()}catch{continue}let g=/xywh=(\d+),(\d+),(\d+),(\d+)/.exec(u??"");t.push({startMs:l,endMs:d,frame:g?{url:f,x:Number(g[1]),y:Number(g[2]),width:Number(g[3]),height:Number(g[4])}:{url:f,x:0,y:0,width:0,height:0}})}return t}var ws=class{constructor(e){this.vttUrl=e}cues=null;loading=null;ensureLoaded(){return this.loading??=fetch(this.vttUrl).then(e=>e.ok?e.text():Promise.reject(new Error(`HTTP ${e.status}`))).then(e=>{this.cues=Qg(e,this.vttUrl)}).catch(()=>{this.cues=[]}),this.loading}async frameAt(e){await this.ensureLoaded();let t=this.cues??[],i=t.find(s=>e>=s.startMs&&e<s.endMs)??t[t.length-1];return i&&e>=0?i.frame:null}};var Ms=class{readySeen=!1;seekInFlight=!1;loadStartMs=0;firstFrameEmitted=!0;onNewLoad(e){this.readySeen=!1,this.seekInFlight=!1,this.loadStartMs=e,this.firstFrameEmitted=!1}onSeek(){this.seekInFlight=!0}onSeekCompleted(){this.seekInFlight=!1}onReady(){this.readySeen=!0,this.seekInFlight=!1}bufferReason(){return this.readySeen?this.seekInFlight?"SEEK":"REBUFFER":"INITIAL"}takeFirstFrameStartupMs(e){return this.firstFrameEmitted?null:(this.firstFrameEmitted=!0,e-this.loadStartMs)}};var Zg=12;function Jg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}function em(r){if(!r)return"";try{let e=new Intl.DisplayNames(["en"],{type:"language"}).of(r);return!e||e===r?r:e.charAt(0).toUpperCase()+e.slice(1)}catch{return r}}var Mt=class{videoElement;hls=null;item=null;stateValue="IDLE";listeners=new Set;analyticsListeners=new Set;adListeners=new Set;progressTimer=null;snapshotTimer=null;opts;startedOnce=!1;didDispatchPause=!1;seekTargetMs=null;atLiveEdgeValue=!0;wasEnded=!1;licensedValue=!1;licenseListeners=new Set;loadGeneration=0;lastBitrate=-1;sideloadedDefaultId=null;nativeLoadListeners=[];detachDrm=null;sawEncrypted=!1;drmKeysAnnounced=!1;drmLicenseRequests=0;thumbnailTrack=null;lastDroppedTotal=0;sessionIdValue=null;sessionTracker=new Ms;breakResume=null;adsProvider=null;adContainer=null;attachedAdsProvider=null;pendingAdConfig=null;completedAdSessions=new Set;currentAdSessionKey=null;lastLoadedItem=null;lastStablePositionMs=0;pendingContentAutoplay=!0;isPlayingAdFlag=!1;adsPendingFlag=!1;adPausedFlag=!1;adProgressValue=null;adCuePointsValue=[];lastAdInfo=null;suppressAdBreakTransition=!1;hlsConfig=null;fallbackToMutedAutoplay=!1;holdPlayback=!1;constructor(e={}){this.opts={progressUpdateIntervalMs:e.progressUpdateIntervalMs??250,seekForwardIncrementMs:e.seekForwardIncrementMs??1e4,seekBackwardIncrementMs:e.seekBackwardIncrementMs??1e4,...e.licenseKey!==void 0?{licenseKey:e.licenseKey}:{}},this.hlsConfig=e.hlsConfig??null,this.fallbackToMutedAutoplay=e.fallbackToMutedAutoplay??!1,this.videoElement=document.createElement("video"),this.videoElement.playsInline=!0,this.videoElement.preload=e.preload??"auto",this.videoElement.crossOrigin="anonymous",this.bindVideoEvents(),da(this.opts.licenseKey,location.hostname).then(t=>{this.licensedValue=t.licensed,this.licenseListeners.forEach(i=>i(t.licensed))})}get state(){return this.stateValue}get isPlaying(){return!this.videoElement.paused&&!this.videoElement.ended&&this.stateValue!=="IDLE"}get currentItem(){return this.item}get currentPositionMs(){return Math.max(0,this.videoElement.currentTime*1e3)}get durationMs(){let e=this.videoElement.duration;return Number.isFinite(e)?e*1e3:0}get bufferedPositionMs(){let e=this.videoElement.buffered,t=this.videoElement.currentTime;for(let i=0;i<e.length;i++)if(e.start(i)<=t&&t<=e.end(i))return e.end(i)*1e3;return this.currentPositionMs}get playbackSpeed(){return this.videoElement.playbackRate}set playbackSpeed(e){this.videoElement.playbackRate=e}get volume(){return this.videoElement.volume}set volume(e){this.videoElement.volume=Math.min(1,Math.max(0,e)),this.emit({type:"VolumeChanged",volume:this.videoElement.volume,muted:this.videoElement.muted})}get isMuted(){return this.videoElement.muted}set isMuted(e){this.videoElement.muted!==e&&(this.videoElement.muted=e,this.emit({type:"VolumeChanged",volume:this.videoElement.volume,muted:e}))}get isLooping(){return this.videoElement.loop}setLooping(e){this.videoElement.loop=e}setBufferRole(e){let t=e==="STANDBY";this.videoElement.preload=t?"metadata":"auto",this.hls&&(this.hls.config.maxBufferLength=t?10:30,this.hls.config.maxMaxBufferLength=t?10:600,this.hls.config.maxBufferSize=t?8e6:6e7,this.hls.config.backBufferLength=t?0:1/0)}volumeControlMode="PLAYER";get isLicensed(){return this.licensedValue}get seekForwardIncrementMs(){return this.opts.seekForwardIncrementMs}get seekBackwardIncrementMs(){return this.opts.seekBackwardIncrementMs}get isPlayingAd(){return this.isPlayingAdFlag}get adsPending(){return this.adsPendingFlag}get adPaused(){return this.adPausedFlag}get adProgress(){return this.adProgressValue}get adCuePoints(){return this.adCuePointsValue}get currentLoadGeneration(){return this.loadGeneration}get sessionId(){return this.sessionIdValue}subtitleStyle={...Fd};subtitleTextScale=1;onLicenseChanged(e){this.licenseListeners.add(e)}addListener(e){this.listeners.add(e)}removeListener(e){this.listeners.delete(e)}addAnalyticsListener(e){this.analyticsListeners.add(e)}removeAnalyticsListener(e){this.analyticsListeners.delete(e)}addAdListener(e){this.adListeners.add(e)}removeAdListener(e){this.adListeners.delete(e)}dispatch(e){this.listeners.forEach(e)}emit(e){this.sessionIdValue!==null&&(e.sessionId=this.sessionIdValue);let t=this.item?.url;t!==void 0&&(e.assetUrl=t),this.analyticsListeners.forEach(i=>i(e))}emitViewAnalytics(e){this.emit(e)}playlistItems=[];playlistPosition=-1;pendingPlaylistAdvanceAfterAds=!1;playlistAdvanceFallback=null;adScheduleSettled=!0;get playlist(){return this.playlistItems.slice()}get currentPlaylistIndex(){return this.playlistPosition}get nextPlaylistItem(){return this.playlistPosition<0?null:this.playlistItems[this.playlistPosition+1]??null}load(e,t={}){this.playlistItems=[],this.playlistPosition=-1,this.loadItemInternal(e,t)}loadPlaylist(e,t={}){let{startIndex:i=0,autoplay:s=!0}=t;if(e.length===0)throw new Error("loadPlaylist requires at least one item");let n=e[i];if(!n)throw new Error("startIndex out of range");this.playlistItems=e.slice(),this.playlistPosition=i,this.dispatch(a=>a.onPlaylistItemChanged?.(i,n)),this.loadItemInternal(n,{autoplay:s})}skipToNext(){let e=this.playlistPosition;e<0||!this.playlistItems[e+1]||(this.dispatch(t=>t.onPlaylistItemSkipped?.(e,e+1)),this.maybeAdvancePlaylist())}releasePendingPlaylistAdvance(){this.pendingPlaylistAdvanceAfterAds&&(this.pendingPlaylistAdvanceAfterAds=!1,this.playlistAdvanceFallback!==null&&(clearTimeout(this.playlistAdvanceFallback),this.playlistAdvanceFallback=null),setTimeout(()=>this.maybeAdvancePlaylist(),0))}maybeAdvancePlaylist(){let e=this.playlistPosition+1,t=this.playlistPosition>=0?this.playlistItems[e]:void 0;t&&(this.playlistPosition=e,this.dispatch(i=>i.onPlaylistItemChanged?.(e,t)),this.loadItemInternal(t,{autoplay:!0}))}loadItemInternal(e,t={}){this.pendingPlaylistAdvanceAfterAds=!1,this.playlistAdvanceFallback!==null&&(clearTimeout(this.playlistAdvanceFallback),this.playlistAdvanceFallback=null),this.adScheduleSettled=!0,this.videoElement.poster=e.posterUrl??"";let{startPositionMs:i=0,autoplay:s=!0}=t;if(this.lastLoadedItem=e,this.lastStablePositionMs=i,this.loadGeneration++,this.teardownSource(),this.item=e,this.sessionIdValue=Jg(),this.sessionTracker.onNewLoad(performance.now()),this.startedOnce=!1,this.didDispatchPause=!1,this.wasEnded=!1,this.lastBitrate=-1,this.sawEncrypted=!1,this.drmKeysAnnounced=!1,this.drmLicenseRequests=0,this.lastDroppedTotal=0,this.thumbnailTrack=e.thumbnailTrackUrl?new ws(e.thumbnailTrackUrl):null,this.resetAdSession(),this.breakResume=null,this.stateValue="IDLE",this.setState("BUFFERING"),this.emit({type:"BufferStart",reason:this.sessionTracker.bufferReason()}),this.attachSource(e,i),this.beginAdsIfNeeded(e,s),s&&!this.adsPendingFlag&&!this.holdPlayback){let n=this.loadGeneration;this.videoElement.play().catch(a=>{this.fallbackToMutedAutoplay&&n===this.loadGeneration&&a instanceof DOMException&&a.name==="NotAllowedError"&&!this.videoElement.muted&&(this.videoElement.muted=!0,this.videoElement.play().then(()=>{this.dispatch(o=>o.onMutedAutoplayFallback?.()),this.emit({type:"MutedAutoplayFallback"})}).catch(()=>{}))})}this.startProgressTimer(),this.startSnapshotTimer()}retry(){let e=this.lastLoadedItem;if(!e)return;let t=(e.streamType??"VOD")==="VOD";this.loadItemInternal(e,{startPositionMs:t?this.lastStablePositionMs:0})}attachSource(e,t){let i=e.url;if((/\.m3u8($|\?)/i.test(i)||i.includes("format=m3u8"))&&xt.isSupported()){let n=e.drm,a={};n?.widevine&&(a["com.widevine.alpha"]={licenseUrl:n.widevine.licenseUrl,...n.widevine.serverCertificateUrl?{serverCertificateUrl:n.widevine.serverCertificateUrl}:{}}),n?.playready&&(a["com.microsoft.playready"]={licenseUrl:n.playready.licenseUrl});let o={...n?.widevine?.headers,...n?.playready?.headers},l=new xt({...this.hlsConfig,renderTextTracksNatively:!0,...Object.keys(a).length>0?{emeEnabled:!0,drmSystems:a,licenseXhrSetup:async d=>{d.timeout=15e3;let c=this.drmLicenseRequests>0;this.drmLicenseRequests++;let h={};if(n?.tokenProvider)try{h=await Cs(n.tokenProvider,{licenseUrl:n.widevine?.licenseUrl??n.playready?.licenseUrl??"",renewal:c})}catch(u){let f=Ee(ue.DRM_TOKEN_FETCH_FAILED,"Drm",`DRM token provider failed: ${u instanceof Error?u.message:"error"}`,!0,void 0,u);throw this.dispatch(g=>g.onError?.(f)),this.emit({type:"Error",error:f}),u}for(let[u,f]of Object.entries({...o,...h}))d.setRequestHeader(u,f);c&&this.dispatch(u=>u.onDrmSessionRenewed?.("PROACTIVE"))}}:{}});this.hls=l,this.bindHlsEvents(l),l.loadSource(i),l.attachMedia(this.videoElement)}else{if(e.drm?.fairplay){let a=e.drm.tokenProvider?{...e.drm.fairplay,tokenProvider:e.drm.tokenProvider}:e.drm.fairplay;this.detachDrm=Hd(this.videoElement,a,o=>{this.dispatch(l=>l.onError?.(o)),this.emit({type:"Error",error:o})},()=>{this.drmKeysAnnounced||(this.drmKeysAnnounced=!0,this.emit({type:"DrmKeysLoaded"}))},()=>this.dispatch(o=>o.onDrmSessionRenewed?.("PROACTIVE")))}this.videoElement.src=i;let n=()=>{};this.videoElement.addEventListener("loadedmetadata",n,{once:!0}),this.nativeLoadListeners.push(["loadedmetadata",n])}if(t>0){let n=()=>{this.videoElement.currentTime=t/1e3};this.videoElement.addEventListener("loadedmetadata",n,{once:!0}),this.nativeLoadListeners.push(["loadedmetadata",n])}this.attachSideloadedSubtitles(e),this.armFirstFrame()}armFirstFrame(){let e=this.loadGeneration,t=this.videoElement,i=()=>{if(e!==this.loadGeneration||this.breakResume!==null)return;let s=this.sessionTracker.takeFirstFrameStartupMs(performance.now());s!==null&&this.emit({type:"PlaybackStarted",startupMs:Math.round(s)})};typeof t.requestVideoFrameCallback=="function"?t.requestVideoFrameCallback(i):(t.addEventListener("loadeddata",i,{once:!0}),this.nativeLoadListeners.push(["loadeddata",i]))}adSessionKey(e){let t=e.adBreaks?.adTagUri;return t?`${e.url}|${t}`:null}beginAdsIfNeeded(e,t){!e.adBreaks||!this.adsProvider||(this.currentAdSessionKey=this.adSessionKey(e),!(this.currentAdSessionKey&&this.completedAdSessions.has(this.currentAdSessionKey))&&(this.pendingContentAutoplay=t,this.adScheduleSettled=!1,this.adsPendingFlag=t,this.adContainer?this.startAdsSession(e.adBreaks):this.pendingAdConfig=e.adBreaks))}startAdsSession(e){let t=this.adsProvider,i=this.adContainer;!t||!i||(this.attachedAdsProvider!==t&&(t.attach(this.videoElement,i,this.adCallbacks),this.attachedAdsProvider=t),t.requestAds(e,this.pendingContentAutoplay))}resetAdSession(){this.attachedAdsProvider&&this.attachedAdsProvider!==this.adsProvider&&(this.attachedAdsProvider.destroy(),this.attachedAdsProvider=null),this.adsProvider?.destroy(),this.adContainer&&this.adContainer.replaceChildren(),this.pendingAdConfig=null,this.lastAdInfo=null,this.adCuePointsValue=[],this.adProgressValue=null,this.adPausedFlag=!1,this.adsPendingFlag=!1,this.suppressAdBreakTransition=!1,this.isPlayingAdFlag=!1}dispatchAd(e){this.adListeners.forEach(e)}adCallbacks={onContentPauseRequested:()=>{this.adsPendingFlag=!1,this.isPlayingAdFlag=!0,this.suppressAdBreakTransition=this.isPlaying,this.videoElement.pause(),this.adsProvider?.usesContentVideoElement&&(this.breakResume={positionMs:this.stateValue==="ENDED"?0:this.currentPositionMs,wasEnded:this.stateValue==="ENDED"},this.teardownSource())},onContentResumeRequested:()=>{if(this.adsPendingFlag=!1,this.isPlayingAdFlag=!1,this.adPausedFlag=!1,this.adProgressValue=null,this.breakResume&&this.item){let{positionMs:e,wasEnded:t}=this.breakResume;if(this.breakResume=null,this.videoElement.controls=!1,this.teardownSource(),!t)this.attachSource(this.item,e);else return}this.pendingContentAutoplay&&this.stateValue!=="ENDED"&&!this.holdPlayback?this.videoElement.play().catch(()=>{}):this.suppressAdBreakTransition=!1},onAdCuePoints:e=>{this.adCuePointsValue=e},onAllAdsCompleted:()=>{this.currentAdSessionKey&&this.completedAdSessions.add(this.currentAdSessionKey),this.adScheduleSettled=!0,this.releasePendingPlaylistAdvance()},onAdBreakStarted:(e,t)=>{this.playlistAdvanceFallback!==null&&(clearTimeout(this.playlistAdvanceFallback),this.playlistAdvanceFallback=null),this.dispatchAd(i=>i.onAdBreakStarted?.(e,t))},onAdStarted:e=>{this.lastAdInfo=e,this.adPausedFlag=!1,this.adProgressValue={positionMs:0,durationMs:e.durationMs,adIndex:e.positionInPod,adCount:e.podSize},this.dispatchAd(t=>t.onAdStarted?.(e))},onAdProgress:(e,t,i)=>{this.adProgressValue={positionMs:t,durationMs:i,adIndex:e.positionInPod,adCount:e.podSize},this.dispatchAd(s=>s.onAdProgress?.(e,t,i))},onAdPaused:e=>{this.adPausedFlag=!0,this.dispatchAd(t=>t.onAdPaused?.(e))},onAdResumed:e=>{this.adPausedFlag=!1,this.dispatchAd(t=>t.onAdResumed?.(e))},onAdSkipped:e=>{this.adProgressValue=null,this.dispatchAd(t=>t.onAdSkipped?.(e))},onAdCompleted:e=>{this.adProgressValue=null,this.dispatchAd(t=>t.onAdCompleted?.(e))},onAdBreakCompleted:e=>{if(e==="POSTROLL")this.adCuePointsValue=this.adCuePointsValue.filter(t=>t>=0);else{let t=this.videoElement.currentTime,i=this.adCuePointsValue.filter(s=>s>=0).sort((s,n)=>Math.abs(s-t)-Math.abs(n-t))[0];i!==void 0&&(this.adCuePointsValue=this.adCuePointsValue.filter(s=>s!==i))}this.dispatchAd(t=>t.onAdBreakCompleted?.(e))},onAdError:e=>{this.dispatchAd(t=>t.onAdError?.(e)),this.releasePendingPlaylistAdvance()}};play(){if(!this.holdPlayback){if(this.isPlayingAdFlag){this.adsProvider?.resume();return}this.adsProvider?.startPendingBreak()||(this.stateValue==="ENDED"&&(this.videoElement.currentTime=0),this.videoElement.play().catch(()=>{}))}}pause(){if(this.isPlayingAdFlag){this.adsProvider?.pause();return}this.videoElement.pause()}skipAd(){this.adsProvider?.skip()}clickAd(){this.adsProvider?.click()}get adCuePositionsMs(){return this.adCuePointsValue.map(e=>{if(e>=0)return Math.round(e*1e3);let t=this.durationMs;return t>0?Math.round(t):-1}).filter(e=>e>=0)}get hasThumbnails(){return this.thumbnailTrack!==null}getThumbnail(e){return this.thumbnailTrack?.frameAt(e)??Promise.resolve(null)}attachAdContainer(e){if(this.adContainer=e,this.pendingAdConfig){let t=this.pendingAdConfig;this.pendingAdConfig=null,this.startAdsSession(t)}}notifyAdViewResize(e,t,i){this.adsProvider?.resize(e,t,i)}seekTo(e){let t=this.currentPositionMs;this.seekTargetMs=e,this.dispatch(s=>s.onSeekStarted?.(t,e)),this.emit({type:"Seek",fromMs:Math.round(t),toMs:Math.round(e)});let i=this.wasEnded&&!this.holdPlayback;this.wasEnded&&(this.wasEnded=!1),this.videoElement.currentTime=e/1e3,i&&this.videoElement.play().catch(()=>{})}seekForward(){this.seekTo(Math.min(this.durationMs||1/0,this.currentPositionMs+this.opts.seekForwardIncrementMs))}seekBackward(){this.seekTo(Math.max(0,this.currentPositionMs-this.opts.seekBackwardIncrementMs))}seekToLiveEdge(){let e=this.videoElement.seekable;e.length>0&&this.seekTo(e.end(e.length-1)*1e3)}release(){this.resetAdSession(),this.teardownSource(),this.stopProgressTimer(),this.stopSnapshotTimer(),this.listeners.clear(),this.analyticsListeners.clear(),this.adListeners.clear(),this.videoElement.remove()}teardownSource(){this.detachDrm?.(),this.detachDrm=null,this.hls?.destroy(),this.hls=null;for(let[e,t]of this.nativeLoadListeners)this.videoElement.removeEventListener(e,t);this.nativeLoadListeners=[],this.videoElement.controls=!1,this.videoElement.removeAttribute("src"),[...this.videoElement.querySelectorAll("track")].forEach(e=>e.remove()),this.sideloadedDefaultId=null}get audioTracks(){if(this.hls)return this.hls.audioTracks.map((t,i)=>{let s=parseInt(String(t.channels??"2"),10)||2,a=!t.name||/^stream[_-]?\d+$/i.test(t.name)||t.name===t.lang?`${em(t.lang??"")||`Audio ${i+1}`}${s>2?" (5.1)":""}`:t.name;return{id:`a${i}`,label:a,language:t.lang||"",channelCount:s,isSelected:this.hls.audioTrack===i}});let e=this.videoElement.audioTracks;if(e&&typeof e=="object"&&"length"in e){let t=e,i=[];for(let s=0;s<t.length;s++){let n=t[s];i.push({id:`a${s}`,label:n.label||n.language||`Audio ${s+1}`,language:n.language,channelCount:2,isSelected:n.enabled})}return i}return[]}selectAudioTrack(e){let t=parseInt(e.slice(1),10),i=this.audioTracks.find(s=>s.id===e);if(this.hls)this.hls.audioTrack=t;else{let s=this.videoElement.audioTracks;if(s){let n=s;for(let a=0;a<n.length;a++)n[a].enabled=a===t}}i&&this.emit({type:"AudioTrackChanged",id:e,language:i.language||null})}get textTracks(){let e=[],t=this.videoElement.textTracks;for(let i=0;i<t.length;i++){let s=t[i];if(s.kind!=="subtitles"&&s.kind!=="captions")continue;let n=s.id?.startsWith("ext-");e.push({id:n?s.id:`t${i}`,label:s.label||s.language||`Subtitles ${i+1}`,language:s.language||"",isSelected:s.mode==="showing"})}return e}selectTextTrack(e){let t=this.videoElement.textTracks;for(let i=0;i<t.length;i++){let s=t[i];if(s.kind!=="subtitles"&&s.kind!=="captions")continue;let n=s.id?.startsWith("ext-")?s.id:`t${i}`;s.mode=e!==null&&n===e?"showing":"disabled"}if(this.hls&&e!==null&&e.startsWith("t")){let i=parseInt(e.slice(1),10),s=-1,n=-1,a=this.videoElement.textTracks;for(let o=0;o<=i&&o<a.length;o++){let l=a[o].kind;(l==="subtitles"||l==="captions")&&n++,o===i&&(s=n)}s>=0&&s<this.hls.subtitleTracks.length&&(this.hls.subtitleTrack=s)}else this.hls&&e===null&&(this.hls.subtitleTrack=-1);if(e===null)this.emit({type:"TextTrackChanged",id:null,language:null});else{let i=this.textTracks.find(s=>s.id===e);i&&this.emit({type:"TextTrackChanged",id:e,language:i.language||null})}}get videoQualities(){if(!this.hls)return[];let e=this.hls.currentLevel,t=this.hls.autoLevelEnabled,i=this.hls.levels.map((s,n)=>({id:`q${n}`,width:s.width,height:s.height,bitrate:s.bitrate,isSelected:!t&&e===n}));return i.unshift({id:"auto",width:0,height:0,bitrate:0,isSelected:t}),i}selectVideoQuality(e){this.hls&&(this.hls.currentLevel=e==="auto"?-1:parseInt(e.slice(1),10))}get liveInfo(){let e=this.item?.streamType??"VOD";if(e==="VOD"||!this.item)return null;let t=this.videoElement.seekable;if(t.length===0)return null;let i=t.start(0),s=t.end(t.length-1),n=this.videoElement.currentTime,a=Math.max(0,s-n),o=Math.max(0,(s-i)*1e3),l=null,d=this.videoElement.getStartDate?.();return d&&!Number.isNaN(d.getTime())?l=d.getTime()+n*1e3:this.hls?.playingDate&&(l=this.hls.playingDate.getTime()),{streamType:e,dvrWindowMs:o,atLiveEdge:a<=Zg,latencyMs:Math.round(a*1e3),playheadWallClockMs:l}}setState(e){this.stateValue!==e&&(this.stateValue=e,this.dispatch(t=>t.onStateChanged?.(e)))}bindVideoEvents(){let e=this.videoElement,t=()=>this.breakResume!==null;e.addEventListener("waiting",()=>{t()||this.stateValue!=="IDLE"&&(this.setState("BUFFERING"),this.emit({type:"BufferStart",reason:this.sessionTracker.bufferReason()}))}),e.addEventListener("seeking",()=>{t()||this.sessionTracker.onSeek()}),e.addEventListener("canplay",()=>{t()||(this.sessionTracker.onReady(),this.stateValue==="BUFFERING"&&(this.setState("READY"),this.emit({type:"BufferEnd"})),this.sawEncrypted&&!this.drmKeysAnnounced&&(this.drmKeysAnnounced=!0,this.emit({type:"DrmKeysLoaded"})))}),e.addEventListener("encrypted",()=>{this.sawEncrypted=!0}),e.addEventListener("playing",()=>{if(!t()){if(this.sessionTracker.onReady(),this.holdPlayback){e.pause();return}if(this.isPlayingAdFlag&&(this.hls!==null&&e.currentSrc.startsWith("blob:")||this.item!==null&&e.currentSrc===this.item.url)){e.pause();return}if(this.stateValue==="BUFFERING"&&(this.setState("READY"),this.emit({type:"BufferEnd"})),this.suppressAdBreakTransition){this.suppressAdBreakTransition=!1,this.didDispatchPause=!1;return}this.dispatch(i=>i.onIsPlayingChanged?.(!0)),this.startedOnce?this.didDispatchPause&&this.dispatch(i=>i.onResume?.()):(this.startedOnce=!0,this.dispatch(i=>i.onPlay?.())),this.didDispatchPause=!1,this.emit({type:"Play"})}}),e.addEventListener("pause",()=>{t()||e.ended||this.stateValue==="IDLE"||this.suppressAdBreakTransition||this.isPlayingAdFlag||(this.didDispatchPause=!0,this.dispatch(i=>i.onIsPlayingChanged?.(!1)),this.dispatch(i=>i.onPause?.()),this.emit({type:"Pause"}))}),e.addEventListener("seeked",()=>{if(t())return;this.sessionTracker.onSeekCompleted();let i=this.currentPositionMs;this.seekTargetMs=null,this.dispatch(s=>s.onSeekCompleted?.(i))}),e.addEventListener("ended",()=>{t()||this.wasEnded||(this.wasEnded=!0,this.setState("ENDED"),this.dispatch(i=>i.onPlaybackCompleted?.()),this.emit({type:"Complete"}),this.adsProvider?.contentDidComplete(),!this.isPlayingAdFlag&&this.adScheduleSettled?this.maybeAdvancePlaylist():(this.pendingPlaylistAdvanceAfterAds=!0,this.playlistAdvanceFallback!==null&&(clearTimeout(this.playlistAdvanceFallback),this.playlistAdvanceFallback=null),this.isPlayingAdFlag||(this.playlistAdvanceFallback=setTimeout(()=>{this.playlistAdvanceFallback=null,this.pendingPlaylistAdvanceAfterAds&&(this.pendingPlaylistAdvanceAfterAds=!1,this.maybeAdvancePlaylist())},8e3))))}),e.addEventListener("error",()=>{if(t()||this.hls)return;let i=Nd(e.error);this.dispatch(s=>s.onError?.(i)),this.emit({type:"Error",error:i})})}bindHlsEvents(e){e.on(xt.Events.LEVEL_SWITCHED,(t,i)=>{let s=e.levels[i.level];!s||s.bitrate===this.lastBitrate||(this.lastBitrate=s.bitrate,this.emit({type:"BitrateChanged",bitrate:s.bitrate,width:s.width,height:s.height,frameRate:s.frameRate||0}))}),e.on(xt.Events.ERROR,(t,i)=>{let s=Bd(i);i.fatal?(this.dispatch(n=>n.onError?.(s)),this.emit({type:"Error",error:s})):this.emit({type:"Error",error:s})})}attachSideloadedSubtitles(e){if((e.sideloadedSubtitles??[]).forEach((i,s)=>{let n=document.createElement("track");n.kind="subtitles",n.label=i.label,n.srclang=i.language,n.src=i.url,n.id=`ext-${s}`,this.videoElement.appendChild(n),i.isDefault&&(this.sideloadedDefaultId=`ext-${s}`),n.addEventListener("load",()=>{let a=n.track;a&&(a.mode=i.isDefault?"showing":"disabled")})}),this.sideloadedDefaultId){let i=this.sideloadedDefaultId,s=()=>this.selectTextTrack(i);this.videoElement.addEventListener("loadedmetadata",s,{once:!0}),this.nativeLoadListeners.push(["loadedmetadata",s])}}startProgressTimer(){this.stopProgressTimer(),this.progressTimer=window.setInterval(()=>{if(this.stateValue==="IDLE")return;this.stateValue==="READY"&&(this.lastStablePositionMs=Math.round(this.currentPositionMs)),this.dispatch(t=>t.onProgress?.(Math.round(this.currentPositionMs),Math.round(this.bufferedPositionMs),Math.round(this.durationMs)));let e=this.liveInfo;e&&e.atLiveEdge!==this.atLiveEdgeValue&&(this.atLiveEdgeValue=e.atLiveEdge,this.dispatch(t=>t.onLiveEdgeChanged?.(e.atLiveEdge)))},this.opts.progressUpdateIntervalMs)}stopProgressTimer(){this.progressTimer!==null&&(clearInterval(this.progressTimer),this.progressTimer=null)}startSnapshotTimer(){this.stopSnapshotTimer(),this.snapshotTimer=window.setInterval(()=>{if(this.stateValue==="IDLE"||!this.isPlaying)return;let e=this.videoElement.getVideoPlaybackQuality?.(),t=e?.droppedVideoFrames??0;t>this.lastDroppedTotal&&this.emit({type:"DroppedFrames",count:t-this.lastDroppedTotal,elapsedMs:1e4}),this.lastDroppedTotal=t;let i=this.liveInfo;this.emit({type:"QualitySnapshot",positionMs:Math.round(this.currentPositionMs),bufferedMs:Math.round(this.bufferedPositionMs),bandwidthEstimateBps:Math.round(this.hls?.bandwidthEstimate??0),droppedFramesTotal:e?.droppedVideoFrames??0,...i?{liveLatencyMs:i.latencyMs,atLiveEdge:i.atLiveEdge}:{}})},1e4)}stopSnapshotTimer(){this.snapshotTimer!==null&&(clearInterval(this.snapshotTimer),this.snapshotTimer=null)}};function Ai(r){let e=r;return typeof e.serverUrl=="string"&&typeof e.networkId=="number"&&typeof e.profile=="string"&&typeof e.videoAssetId=="string"}function ha(r){let e=()=>String(Math.floor(Math.random()*1e9)),t=new URLSearchParams({nw:String(r.networkId),prof:r.profile,csid:r.siteSectionId,caid:r.videoAssetId,vdur:String(Math.round(r.videoDurationMs/1e3)),resp:"vmap1 vast4",pvrn:e(),vprn:e(),...r.globalParameters});return`${r.serverUrl.replace(/\/$/,"")}/ad/g/1?${t.toString()}`}var qd=null;async function Wd(r){let e=async i=>{try{return await fetch(i,{mode:"no-cors",cache:"no-store"}),!0}catch{return!1}},t=[e("https://imasdk.googleapis.com/js/sdkloader/ima3.js"),e("https://pubads.g.doubleclick.net/gampad/ads?ad_type=probe")];if(r)try{let i=new URL(r).origin;i!=="https://pubads.g.doubleclick.net"&&t.push(e(i+"/"))}catch{}return(await Promise.all(t)).some(i=>!i)}function tm(){return window.google?.ima?Promise.resolve(window.google.ima):(qd??=new Promise((r,e)=>{let t=document.createElement("script");t.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",t.async=!0,t.onload=()=>{let i=window.google?.ima;i?r(i):e(new Error("IMA SDK loaded but google.ima missing"))},t.onerror=()=>e(new Error("failed to load the IMA SDK (blocked by an ad blocker?)")),document.head.appendChild(t)}),qd)}var ua=class{constructor(e={}){this.options=e}video=null;container=null;callbacks=null;ima=null;adDisplayContainer=null;adsLoader=null;adsManager=null;lastAd=null;lastBreakType=null;tagUrl=null;autostart=!0;started=!1;destroyed=!1;requestGeneration=0;verdictTimer=null;gotVerdict=!1;attach(e,t,i){this.video=e,this.container=t,this.callbacks=i}requestAds(e,t){this.autostart=t;let i=Ai(e)?ha(e):e.adTagUri;if(typeof i!="string"||!i){this.callbacks?.onAdError({code:900,phase:"LOAD",message:"ImaAdsProvider needs an AdTagConfig with adTagUri"}),this.callbacks?.onContentResumeRequested();return}this.tagUrl=i;let s=++this.requestGeneration;this.gotVerdict=!1,this.verdictTimer!==null&&clearTimeout(this.verdictTimer),this.verdictTimer=window.setTimeout(()=>{this.destroyed||this.gotVerdict||s!==this.requestGeneration||Wd(this.tagUrl??void 0).then(n=>{this.destroyed||this.gotVerdict||(this.gotVerdict=!0,this.callbacks?.onAdError(n?{code:902,phase:"LOAD",message:"ads blocked by the browser (ad blocker detected)"}:{code:901,phase:"LOAD",message:"ad request produced no response in time"}),this.callbacks?.onContentResumeRequested())})},6e3),tm().then(n=>{this.destroyed||s!==this.requestGeneration||(this.ima=n,this.startSession(n,i))}).catch(n=>{this.settleVerdict(),this.callbacks?.onAdError({code:902,phase:"LOAD",message:n.message}),this.callbacks?.onContentResumeRequested()})}settleVerdict(){this.gotVerdict=!0,this.verdictTimer!==null&&(clearTimeout(this.verdictTimer),this.verdictTimer=null)}startSession(e,t){let i=this.video,s=this.container,n=this.options.vpaidMode??"enabled";e.settings.setVpaidMode(n==="insecure"?e.ImaSdkSettings.VpaidMode.INSECURE:n==="disabled"?e.ImaSdkSettings.VpaidMode.DISABLED:e.ImaSdkSettings.VpaidMode.ENABLED),this.adDisplayContainer??=new e.AdDisplayContainer(s,i),this.adDisplayContainer.initialize(),this.adsLoader?.destroy();let a=new e.AdsLoader(this.adDisplayContainer);this.adsLoader=a,a.addEventListener(e.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,d=>{this.settleVerdict();let c=new e.AdsRenderingSettings;c.uiElements=[],c.restoreCustomPlaybackStateOnAdBreakComplete=!0;let h=d.getAdsManager(i,c);this.adsManager=h,this.bindManager(e,h),this.callbacks?.onAdCuePoints(h.getCuePoints());let u=s.getBoundingClientRect();h.init(u.width,u.height,e.ViewMode.NORMAL),this.autostart&&(this.started=!0,h.start())}),a.addEventListener(e.AdErrorEvent.Type.AD_ERROR,d=>{this.settleVerdict();let c=d.getError();this.callbacks?.onAdError({code:c.getErrorCode(),phase:"LOAD",message:c.getMessage()}),this.callbacks?.onContentResumeRequested(),this.maybeFlagAdBlock()});let o=new e.AdsRequest;o.adTagUrl=t,o.setAdWillAutoPlay(this.autostart),o.setAdWillPlayMuted(i.muted);let l=s.getBoundingClientRect();o.linearAdSlotWidth=Math.round(l.width)||640,o.linearAdSlotHeight=Math.round(l.height)||360,o.nonLinearAdSlotWidth=Math.round(l.width)||640,o.nonLinearAdSlotHeight=150,a.requestAds(o)}bindManager(e,t){let i=e.AdEvent.Type,s=()=>this.callbacks,n=()=>{if(!this.lastBreakType)return;let a=this.lastBreakType;this.lastBreakType=null,s()?.onAdBreakCompleted(a)};t.addEventListener(i.CONTENT_PAUSE_REQUESTED,()=>s()?.onContentPauseRequested()),t.addEventListener(i.CONTENT_RESUME_REQUESTED,()=>{n(),s()?.onContentResumeRequested()}),t.addEventListener(i.STARTED,a=>{let o=a.getAd();if(!o)return;let l=o.getAdPodInfo(),d=l.getPodIndex()===0?"PREROLL":l.getPodIndex()===-1?"POSTROLL":"MIDROLL",c=o.getSkipTimeOffset()>=0,h={adId:o.getAdId(),positionInPod:l.getAdPosition(),podSize:l.getTotalAds(),breakType:d,isSkippable:c,skipOffsetMs:c?Math.round(o.getSkipTimeOffset()*1e3):-1,durationMs:Math.round(o.getDuration()*1e3),providerRendersUi:!0};this.lastAd=h,this.lastBreakType=d,h.positionInPod===1&&s()?.onAdBreakStarted(d,h.podSize),s()?.onAdStarted(h)}),t.addEventListener(i.AD_PROGRESS,a=>{let o=a.getAdData();this.lastAd&&o?.duration&&s()?.onAdProgress(this.lastAd,Math.round((o.currentTime??0)*1e3),Math.round(o.duration*1e3))}),t.addEventListener(i.PAUSED,()=>{this.lastAd&&s()?.onAdPaused(this.lastAd)}),t.addEventListener(i.RESUMED,()=>{this.lastAd&&s()?.onAdResumed(this.lastAd)}),t.addEventListener(i.SKIPPED,()=>{this.lastAd&&s()?.onAdSkipped(this.lastAd)}),t.addEventListener(i.COMPLETE,()=>{this.lastAd&&s()?.onAdCompleted(this.lastAd)}),i.AD_BREAK_ENDED&&t.addEventListener(i.AD_BREAK_ENDED,n),t.addEventListener(i.ALL_ADS_COMPLETED,()=>{n(),this.lastAd=null,s()?.onAllAdsCompleted?.()}),t.addEventListener(e.AdErrorEvent.Type.AD_ERROR,a=>{let o=a.getError();s()?.onAdError({code:o.getErrorCode(),phase:"PLAY",message:o.getMessage()}),s()?.onContentResumeRequested(),this.maybeFlagAdBlock()})}adBlockFlagged=!1;maybeFlagAdBlock(){this.adBlockFlagged||Wd(this.tagUrl??void 0).then(e=>{e&&!this.adBlockFlagged&&!this.destroyed&&(this.adBlockFlagged=!0,this.callbacks?.onAdError({code:902,phase:"LOAD",message:"ads blocked by the browser (ad blocker detected)"}))})}startPendingBreak(){return!this.adsManager||this.started?!1:(this.started=!0,this.adsManager.start(),!0)}contentDidComplete(){this.adsLoader?.contentComplete()}pause(){this.adsManager?.pause()}resume(){this.adsManager?.resume()}skip(){this.adsManager?.skip()}click(){}resize(e,t,i){this.ima&&this.adsManager&&this.adsManager.resize(e,t,i?this.ima.ViewMode.FULLSCREEN:this.ima.ViewMode.NORMAL)}destroy(){this.requestGeneration++,this.verdictTimer!==null&&(clearTimeout(this.verdictTimer),this.verdictTimer=null),this.adsManager?.destroy(),this.adsManager=null,this.adsLoader?.destroy(),this.adsLoader=null,this.adDisplayContainer?.destroy(),this.adDisplayContainer=null,this.lastAd=null,this.lastBreakType=null,this.autostart=!0,this.started=!1}};var im="https://mssl.fwmrm.net/libs/adm/7.5.0/AdManager.js",fa=null;function sm(r){return window.tv?.freewheel?.SDK?Promise.resolve(window.tv.freewheel.SDK):(fa??=new Promise((e,t)=>{let i=document.createElement("script");i.src=r,i.async=!0,i.onload=()=>{let s=window.tv?.freewheel?.SDK;s?e(s):t(new Error("AdManager.js loaded but tv.freewheel.SDK missing"))},i.onerror=()=>{fa=null,t(new Error("failed to load FreeWheel AdManager.js (blocked by an ad blocker?)"))},document.head.appendChild(i)}),fa)}var ga=class{constructor(e={}){this.options=e}usesContentVideoElement=!0;video=null;container=null;callbacks=null;sdk=null;context=null;cfg=null;generation=0;destroyed=!1;prerollSlots=[];midrollSlots=[];postrollSlots=[];catchUpQueue=[];flow="PREROLLS";contentGateOpened=!1;pendingStart=!1;currentSlot=null;currentBreakType=null;currentAd=null;currentInstance=null;adIndexInSlot=0;totalAdsInSlot=0;requestTimer=null;watchdogTimer=null;progressTimer=null;lastContentPosMs=0;videoListeners=[];attach(e,t,i){this.video=e,this.container=t,this.callbacks=i}requestAds(e,t){if(!Ai(e)){this.callbacks?.onAdError({code:900,phase:"LOAD",message:"FreewheelAdsProvider needs a FreewheelConfig"}),this.callbacks?.onContentResumeRequested();return}this.cfg=e,this.pendingStart=!t;let i=++this.generation,s=e.requestTimeoutMs??5e3;this.requestTimer=window.setTimeout(()=>{this.destroyed||i!==this.generation||this.fail({code:901,phase:"LOAD",message:"FreeWheel request produced no response in time"})},s+2e3),sm(this.options.adManagerUrl??im).then(n=>{this.destroyed||i!==this.generation||(this.sdk=n,this.submitRequest(n,e))}).catch(n=>{this.destroyed||i!==this.generation||this.fail({code:902,phase:"LOAD",message:n.message})})}submitRequest(e,t){let i=this.video,s=this.container;if(!i||!s)return;if(!i.parentNode){this.fail({code:900,phase:"LOAD",message:"FreewheelAdsProvider needs the video element mounted in the DOM"});return}let n=new e.AdManager;n.setNetwork(t.networkId),n.setServer(t.serverUrl.replace(/\/$/,"")+"/ad/g/1");let a=n.newContext();this.context=a,a.setProfile(t.profile),a.setSiteSection(t.siteSectionId,t.networkId),a.setVideoAsset(t.videoAssetId,t.videoDurationMs/1e3,t.networkId),a.setContentVideoElement?.(i);for(let[l,d]of Object.entries(t.globalParameters??{}))a.addKeyValue(l,d),(l.startsWith("_fw_")||l.includes("."))&&a.setParameter(l,d,e.PARAMETER_LEVEL_GLOBAL);let o=()=>String(Math.floor(Math.random()*1e9));a.addKeyValue("pvrn",o()),a.addKeyValue("vprn",o()),a.setParameter("renderer.video.timeoutMillisecondsBeforeStart",String(t.adStartTimeoutMs??1e4),e.PARAMETER_LEVEL_GLOBAL),a.addEventListener(e.EVENT_REQUEST_COMPLETE,l=>this.onRequestComplete(l)),a.addEventListener(e.EVENT_SLOT_ENDED,l=>this.onSlotEnded(l)),a.addEventListener(e.EVENT_AD_IMPRESSION,l=>this.onAdImpression(l)),e.EVENT_AD_PAUSE&&a.addEventListener(e.EVENT_AD_PAUSE,()=>{this.currentAd&&this.callbacks?.onAdPaused(this.currentAd)}),e.EVENT_AD_RESUME&&a.addEventListener(e.EVENT_AD_RESUME,()=>{this.currentAd&&this.callbacks?.onAdResumed(this.currentAd)}),e.EVENT_ERROR&&a.addEventListener(e.EVENT_ERROR,l=>{this.callbacks?.onAdError({code:301,phase:"PLAY",message:`FreeWheel error: ${JSON.stringify(l.errorInfo??l.type??"unknown")}`})}),this.bindContentWatchers(i),a.submitRequest()}onRequestComplete(e){if(this.requestTimer!==null&&(clearTimeout(this.requestTimer),this.requestTimer=null),this.destroyed)return;if(e.success===!1){this.fail({code:300,phase:"LOAD",message:"FreeWheel request failed"});return}let t=this.sdk,i=this.context;if(!t||!i)return;let s=o=>(o.getAdInstances?.()?.length??1)>0,n=i.getTemporalSlots().filter(s),a=o=>n.filter(l=>o!==void 0&&l.getTimePositionClass()===o);this.prerollSlots=a(t.TIME_POSITION_CLASS_PREROLL),this.postrollSlots=a(t.TIME_POSITION_CLASS_POSTROLL),this.midrollSlots=[...a(t.TIME_POSITION_CLASS_MIDROLL),...a(t.TIME_POSITION_CLASS_OVERLAY)].sort((o,l)=>o.getTimePosition()-l.getTimePosition()),this.publishCuePoints(),!this.pendingStart&&this.playNextPreroll()}publishCuePoints(){let e=this.midrollSlots.map(t=>t.getTimePosition());(this.prerollSlots.length||this.currentBreakType==="PREROLL")&&e.unshift(0),this.postrollSlots.length&&e.push(-1),this.callbacks?.onAdCuePoints(e)}playNextPreroll(){let e=this.prerollSlots.shift();if(!e){this.flow="CONTENT",this.openContentGateOnce();return}this.flow="PREROLLS",this.playSlot(e,"PREROLL")}openContentGateOnce(){this.contentGateOpened||(this.contentGateOpened=!0,this.callbacks?.onContentResumeRequested())}playSlot(e,t){this.currentSlot=e,this.currentBreakType=t,this.adIndexInSlot=0,this.totalAdsInSlot=e.getAdInstances?.()?.length??0,this.armWatchdog(e),this.callbacks?.onContentPauseRequested(),this.callbacks?.onAdBreakStarted(t,this.totalAdsInSlot),e.play()}onSlotEnded(e){let t=this.currentSlot;if(!t||e.slot&&e.slot.getCustomId()!==t.getCustomId())return;this.cancelWatchdog(),this.stopProgressTicker(),this.currentAd&&this.callbacks?.onAdCompleted(this.currentAd),this.currentAd=null,this.currentInstance=null,this.currentSlot=null;let i=this.currentBreakType;switch(this.currentBreakType=null,this.video&&(this.video.controls=!1),i&&this.callbacks?.onAdBreakCompleted(i),this.flow){case"PREROLLS":this.playNextPreroll();break;case"MIDROLL":this.flow="CONTENT",this.callbacks?.onContentResumeRequested();break;case"CATCH_UP":{let s=this.catchUpQueue.shift();s?this.playSlot(s,"MIDROLL"):(this.flow="CONTENT",this.callbacks?.onContentResumeRequested());break}case"POSTROLLS":this.playNextPostroll();break;default:break}}onAdImpression(e){let t=this.currentSlot,i=this.currentBreakType;if(!t||!i)return;this.cancelWatchdog(),this.currentAd&&this.callbacks?.onAdCompleted(this.currentAd),this.adIndexInSlot++;let s=e.adInstance??t.getAdInstances?.()?.[this.adIndexInSlot-1]??null,n=l=>l!==void 0&&l>=1&&l<=600?l*1e3:null,a=n(s?.getActiveCreativeRendition?.()?.getDuration?.())??n(s?.getDuration?.())??this.cfg?.fallbackAdDurationMs??15e3,o={adId:String(s?.getAdId?.()??`fw-${this.adIndexInSlot}`),positionInPod:this.adIndexInSlot,podSize:Math.max(this.totalAdsInSlot,this.adIndexInSlot),breakType:i,isSkippable:!1,skipOffsetMs:-1,durationMs:a,providerRendersUi:!0};this.currentAd=o,this.currentInstance=s,this.callbacks?.onAdStarted(o),this.startProgressTicker(o,t,a)}bindContentWatchers(e){this.unbindContentWatchers();let t=(s,n)=>{e.addEventListener(s,n),this.videoListeners.push([s,n])},i=0;t("timeupdate",()=>{let s=e.currentTime*1e3;if(e.seeking||(this.lastContentPosMs=s),this.flow!=="CONTENT"||this.currentSlot)return;let n=this.cfg?.midrollToleranceMs??1e3,a=this.midrollSlots.find(o=>Math.abs(o.getTimePosition()*1e3-s)<=n);a&&(this.midrollSlots=this.midrollSlots.filter(o=>o!==a),this.publishCuePoints(),this.flow="MIDROLL",this.playSlot(a,"MIDROLL"))}),t("seeking",()=>{i=this.lastContentPosMs}),t("seeked",()=>{if(this.flow!=="CONTENT"||this.currentSlot)return;let s=e.currentTime*1e3;if(Math.abs(s-i)<(this.cfg?.seekThresholdMs??2e3))return;let n=Math.min(i,s),a=Math.max(i,s),o=this.midrollSlots.filter(c=>{let h=c.getTimePosition()*1e3;return h>n&&h<=a});if(!o.length)return;this.midrollSlots=this.midrollSlots.filter(c=>!o.includes(c)),this.publishCuePoints();let l=this.cfg?.seekCatchUpPolicy??"MOST_RECENT";if(l==="NONE")return;let d=[...o].sort((c,h)=>h.getTimePosition()-c.getTimePosition());this.catchUpQueue=l==="MOST_RECENT"?[d[0]]:d,this.flow="CATCH_UP",this.playSlot(this.catchUpQueue.shift(),"MIDROLL")}),t("play",()=>{!this.currentSlot&&this.sdk?.VIDEO_STATE_PLAYING!==void 0&&this.context?.setVideoState?.(this.sdk.VIDEO_STATE_PLAYING)}),t("pause",()=>{!this.currentSlot&&this.sdk?.VIDEO_STATE_PAUSED!==void 0&&this.context?.setVideoState?.(this.sdk.VIDEO_STATE_PAUSED)})}unbindContentWatchers(){let e=this.video;e&&this.videoListeners.forEach(([t,i])=>e.removeEventListener(t,i)),this.videoListeners=[]}contentDidComplete(){this.destroyed||this.flow==="DONE"||(this.sdk?.VIDEO_STATE_COMPLETED!==void 0&&this.context?.setVideoState?.(this.sdk.VIDEO_STATE_COMPLETED),this.flow="POSTROLLS",this.playNextPostroll())}playNextPostroll(){let e=this.postrollSlots.shift();if(!e){this.flow="DONE",this.callbacks?.onAllAdsCompleted?.(),this.callbacks?.onContentResumeRequested();return}this.playSlot(e,"POSTROLL")}armWatchdog(e){this.cancelWatchdog();let t=(this.cfg?.adStartTimeoutMs??1e4)+2e3;this.watchdogTimer=window.setTimeout(()=>{this.destroyed||this.currentSlot!==e||this.currentAd||this.abandonSlot(e,`no ad rendered within ${t}ms`)},t)}cancelWatchdog(){this.watchdogTimer!==null&&(clearTimeout(this.watchdogTimer),this.watchdogTimer=null)}abandonSlot(e,t){this.callbacks?.onAdError({code:301,phase:"PLAY",message:`slot abandoned: ${t}`});try{e.stop?.()}catch{}window.setTimeout(()=>{this.currentSlot===e&&this.onSlotEnded({slot:e})},500)}startProgressTicker(e,t,i){this.stopProgressTicker();let s=performance.now();this.progressTimer=window.setInterval(()=>{if(this.destroyed||this.currentAd!==e){this.stopProgressTicker();return}let n=t.getPlayheadTime?.(),a=n!==void 0&&n>=0?n*1e3:performance.now()-s;this.callbacks?.onAdProgress(e,Math.min(a,i),i)},300)}stopProgressTicker(){this.progressTimer!==null&&(clearInterval(this.progressTimer),this.progressTimer=null)}startPendingBreak(){return!this.pendingStart||(this.pendingStart=!1,!this.prerollSlots.length)?!1:(this.playNextPreroll(),!0)}pause(){this.currentSlot?.pause?.()}resume(){this.currentSlot?.resume?.()}skip(){this.currentInstance?.getRendererController?.()?.skipCurrentAd?.()}click(){}resize(){}fail(e){this.callbacks?.onAdError(e),this.flow="CONTENT",this.openContentGateOnce()}destroy(){this.generation++,this.requestTimer!==null&&(clearTimeout(this.requestTimer),this.requestTimer=null),this.cancelWatchdog(),this.stopProgressTicker(),this.unbindContentWatchers();try{this.currentSlot?.stop?.()}catch{}try{this.context?.dispose?.()}catch{}this.context=null,this.video&&(this.video.controls=!1),this.cfg=null,this.prerollSlots=[],this.midrollSlots=[],this.postrollSlots=[],this.catchUpQueue=[],this.currentSlot=null,this.currentBreakType=null,this.currentAd=null,this.currentInstance=null,this.flow="PREROLLS",this.contentGateOpened=!1,this.pendingStart=!1}};var Os={foreground:"#FFFFFF",foregroundMuted:"rgba(255,255,255,0.70)",foregroundFaint:"rgba(255,255,255,0.38)",trackPlayed:"#FFFFFF",trackBuffered:"rgba(255,255,255,0.38)",trackRemaining:"rgba(255,255,255,0.22)",thumb:"#FFFFFF",thumbHalo:"rgba(255,255,255,0.20)",pressed:"rgba(255,255,255,0.12)",liveEdge:"#F2453E",liveBehind:"rgba(255,255,255,0.60)",adAccent:"#F6C445",menuSurface:"rgba(23,24,26,0.94)",menuSelected:"rgba(255,255,255,0.10)",menuBorder:"rgba(255,255,255,0.10)",chipSurface:"rgba(0,0,0,0.55)"},xi={trackHeight:3,trackHeightActive:5,thumbSize:12,thumbSizeActive:18,thumbHaloSize:34,scrubTouchHeight:48,iconSize:24,playButtonSize:56,playGlyphSize:28,seekButtonSize:48,seekGlyphSize:24,clusterGap:20,bottomBarHeight:48,edgeInset:12,bottomScrimHeight:140,topScrimHeight:96,menuMinWidth:224,menuMaxWidth:320,menuItemHeight:48,menuCorner:14,chipHeight:24,adCueMarkerSize:6},Fs={...xi,bottomBarHeight:56,edgeInset:24};var nm={play:{fills:["M8.5 6.5 18 12 8.5 17.5Z"]},pause:{fills:["M8.3 5.5 L9.3 5.5 A1.3 1.3 0 0 1 10.6 6.8 L10.6 17.2 A1.3 1.3 0 0 1 9.3 18.5 L8.3 18.5 A1.3 1.3 0 0 1 7 17.2 L7 6.8 A1.3 1.3 0 0 1 8.3 5.5 Z","M14.7 5.5 L15.7 5.5 A1.3 1.3 0 0 1 17 6.8 L17 17.2 A1.3 1.3 0 0 1 15.7 18.5 L14.7 18.5 A1.3 1.3 0 0 1 13.4 17.2 L13.4 6.8 A1.3 1.3 0 0 1 14.7 5.5 Z"]},replay:{strokes:["M20 12a8 8 0 1 1-2.34-5.66","M13.6 6.6 17.66 6.34 17.9 2.3"]},seekBack:{strokes:["M16.36 6.37A7.6 7.6 0 1 1 7.64 6.37","M11.7 6.1 7.64 6.37 7.9 2.3"]},seekForward:{strokes:["M7.64 6.37A7.6 7.6 0 1 0 16.36 6.37","M12.3 6.1 16.36 6.37 16.1 2.3"]},volumeOn:{fills:["M4 9h3.2l4.4-3.6a1 1 0 0 1 1.6.8v11.6a1 1 0 0 1-1.6.8L7.2 15H4a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1z"],strokes:["M16.6 9.4a3.6 3.6 0 0 1 0 5.2","M19.2 7a7.2 7.2 0 0 1 0 10"]},volumeMute:{fills:["M4 9h3.2l4.4-3.6a1 1 0 0 1 1.6.8v11.6a1 1 0 0 1-1.6.8L7.2 15H4a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1z"],strokes:["m16.6 9.6 5 4.8","m21.6 9.6-5 4.8"]},speed:{strokes:["M4.2 17.5a9 9 0 0 1 15.6 0","M12 13.2 16.4 9.3"]},quality:{strokes:["M3 7.5h5","M12.2 7.5H21","M8.0 7.5 a2.1 2.1 0 1 0 4.2 0 a2.1 2.1 0 1 0 -4.2 0 Z","M3 16.5h8.8","M16 16.5H21","M11.8 16.5 a2.1 2.1 0 1 0 4.2 0 a2.1 2.1 0 1 0 -4.2 0 Z"]},audioTrack:{strokes:["M9 17.5V7l10-2v10.5","M9 17.5a2.4 2.4 0 1 1-4.8 0a2.4 2.4 0 1 1 4.8 0z","M19 15.5a2.4 2.4 0 1 1-4.8 0a2.4 2.4 0 1 1 4.8 0z"]},subtitles:{strokes:["M5.5 5 L18.5 5 A2.5 2.5 0 0 1 21 7.5 L21 16.5 A2.5 2.5 0 0 1 18.5 19 L5.5 19 A2.5 2.5 0 0 1 3 16.5 L3 7.5 A2.5 2.5 0 0 1 5.5 5 Z","M7.5 10.5h9","M7.5 14.5h5"]},fullscreenEnter:{strokes:["M9 4H4v5","M15 4h5v5","M15 20h5v-5","M9 20H4v-5"]},fullscreenExit:{strokes:["M3.5 8.5h5v-5","M20.5 8.5h-5v-5","M20.5 15.5h-5v5","M3.5 15.5h5v5"]},check:{strokes:["M5 12.6 9.8 17.4 19 7.2"]}};function Ot(r,e,t,i=1.8){let s=nm[r];if(!s)return"";let n=(s.strokes??[]).map(o=>`<path d="${o}" fill="none" stroke="${t}" stroke-width="${i}" stroke-linecap="round" stroke-linejoin="round"/>`).join(""),a=(s.fills??[]).map(o=>`<path d="${o}" fill="${t}"/>`).join("");return`<svg width="${e}" height="${e}" viewBox="0 0 24 24" aria-hidden="true">${a}${n}</svg>`}function Ns(r,e,t){return`<svg width="${r}" height="${r}" viewBox="0 0 32 32" aria-hidden="true">
43
43
  <path d="M12 3H29V20L20 29H3V12Z" fill="none" stroke="${e}" stroke-width="2.6" stroke-linejoin="round"/>
44
- <path d="M13 10L22.5 16L13 22Z" fill="${t}"/></svg>`}var ua={showProgressBar:!0,showTimeLabels:!0,showSeekButtons:!0,showVolumeButton:!0,showSpeedButton:!0,showQualityButton:!0,showAudioTrackButton:!0,showSubtitleButton:!0,showFullscreenButton:!0,showTitle:!0,showContentRatings:!0,controlsTimeoutMs:5e3,titleTimeoutMs:5e3,contentRatingsTimeoutMs:5e3,doubleClickToSeek:!0,showAdCueMarkers:!0,customActions:[],adBlockerPolicy:"notice",showRetryButton:!0,retryButtonLabel:"Retry",showUpNext:!0,upNextLeadSeconds:10,upNextText:"Next in {seconds}"};function Jg(r={}){return{showProgressBar:!1,showTimeLabels:!1,showSeekButtons:!1,showVolumeButton:!1,showSpeedButton:!1,showQualityButton:!1,showAudioTrackButton:!1,showSubtitleButton:!1,showFullscreenButton:!1,showAdCueMarkers:!1,...r}}var em={volume:"og_btn_volume",speed:"og_btn_speed",quality:"og_btn_quality",audio:"og_btn_audio",subs:"og_btn_subtitles",fs:"og_btn_fullscreen"},tm=["top-start","top-center","top-end","center-start","center","center-end","bottom-start","bottom-center","bottom-end"],im={ALL:"AL",SIX:"6",NINE:"9",TWELVE:"12",FOURTEEN:"14",SIXTEEN:"16",EIGHTEEN:"18"},sm={ALL:"#5FA85C",SIX:"#E8B812",NINE:"#6F58A8",TWELVE:"#E07A18",FOURTEEN:"#D9541E",SIXTEEN:"#C5271F",EIGHTEEN:"#7E120D"},Fs='fill="none" stroke="#fff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"',nm={VIOLENCE:`<path d="M8 11V5.6a1.3 1.3 0 0 1 2.6 0V10 M10.6 5V4.2a1.3 1.3 0 0 1 2.6 0V10 M13.2 5.4a1.3 1.3 0 0 1 2.6 0V10 M15.8 7.4a1.3 1.3 0 0 1 2.6 0v6a6 6 0 0 1-6 6h-.5a6 6 0 0 1-6-6v-1.6a1.5 1.5 0 0 1 2.1-1.37" ${Fs}/>`,FEAR:`<ellipse cx="12" cy="14" rx="3.2" ry="4" fill="#fff"/><circle cx="12" cy="8.6" r="1.9" fill="#fff"/>
45
- <path d="M9.4 12 5 9.4 M9 14.6H4.4 M9.6 16.6 6 19.6 M14.6 12 19 9.4 M15 14.6h4.6 M14.4 16.6 18 19.6" ${Fs}/>`,SEX:'<path d="M12 20.2 10.55 18.9C5.4 14.2 2 11.1 2 7.4 2 4.3 4.4 2 7.5 2c1.7 0 3.4.8 4.5 2.1C13.1 2.8 14.8 2 16.5 2 19.6 2 22 4.3 22 7.4c0 3.7-3.4 6.8-8.55 11.5Z" fill="#fff"/>',DISCRIMINATION:`<circle cx="8.4" cy="8" r="2.6" fill="#fff"/><path d="M3.6 18.6a4.8 4.8 0 0 1 9.6 0Z" fill="#fff"/>
44
+ <path d="M13 10L22.5 16L13 22Z" fill="${t}"/></svg>`}var ma={showProgressBar:!0,showTimeLabels:!0,showSeekButtons:!0,showVolumeButton:!0,showSpeedButton:!0,showQualityButton:!0,showAudioTrackButton:!0,showSubtitleButton:!0,showFullscreenButton:!0,showTitle:!0,showContentRatings:!0,controlsTimeoutMs:5e3,titleTimeoutMs:5e3,contentRatingsTimeoutMs:5e3,doubleClickToSeek:!0,showAdCueMarkers:!0,customActions:[],adBlockerPolicy:"notice",showRetryButton:!0,retryButtonLabel:"Retry",showUpNext:!0,upNextLeadSeconds:10,upNextText:"Next in {seconds}"};function rm(r={}){return{showProgressBar:!1,showTimeLabels:!1,showSeekButtons:!1,showVolumeButton:!1,showSpeedButton:!1,showQualityButton:!1,showAudioTrackButton:!1,showSubtitleButton:!1,showFullscreenButton:!1,showAdCueMarkers:!1,...r}}var am={volume:"og_btn_volume",speed:"og_btn_speed",quality:"og_btn_quality",audio:"og_btn_audio",subs:"og_btn_subtitles",fs:"og_btn_fullscreen"},om=["top-start","top-center","top-end","center-start","center","center-end","bottom-start","bottom-center","bottom-end"],lm={ALL:"AL",SIX:"6",NINE:"9",TWELVE:"12",FOURTEEN:"14",SIXTEEN:"16",EIGHTEEN:"18"},dm={ALL:"#5FA85C",SIX:"#E8B812",NINE:"#6F58A8",TWELVE:"#E07A18",FOURTEEN:"#D9541E",SIXTEEN:"#C5271F",EIGHTEEN:"#7E120D"},Bs='fill="none" stroke="#fff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"',cm={VIOLENCE:`<path d="M8 11V5.6a1.3 1.3 0 0 1 2.6 0V10 M10.6 5V4.2a1.3 1.3 0 0 1 2.6 0V10 M13.2 5.4a1.3 1.3 0 0 1 2.6 0V10 M15.8 7.4a1.3 1.3 0 0 1 2.6 0v6a6 6 0 0 1-6 6h-.5a6 6 0 0 1-6-6v-1.6a1.5 1.5 0 0 1 2.1-1.37" ${Bs}/>`,FEAR:`<ellipse cx="12" cy="14" rx="3.2" ry="4" fill="#fff"/><circle cx="12" cy="8.6" r="1.9" fill="#fff"/>
45
+ <path d="M9.4 12 5 9.4 M9 14.6H4.4 M9.6 16.6 6 19.6 M14.6 12 19 9.4 M15 14.6h4.6 M14.4 16.6 18 19.6" ${Bs}/>`,SEX:'<path d="M12 20.2 10.55 18.9C5.4 14.2 2 11.1 2 7.4 2 4.3 4.4 2 7.5 2c1.7 0 3.4.8 4.5 2.1C13.1 2.8 14.8 2 16.5 2 19.6 2 22 4.3 22 7.4c0 3.7-3.4 6.8-8.55 11.5Z" fill="#fff"/>',DISCRIMINATION:`<circle cx="8.4" cy="8" r="2.6" fill="#fff"/><path d="M3.6 18.6a4.8 4.8 0 0 1 9.6 0Z" fill="#fff"/>
46
46
  <circle cx="16.4" cy="8.6" r="2.1" fill="#fff" opacity=".7"/><path d="M12.9 18.6a4 4 0 0 1 7.5-1.4" fill="none" stroke="#fff" stroke-width="1.7" opacity=".7"/>
47
- <path d="M4.5 4.5 19.5 19.5" ${Fs}/>`,DRUGS_ALCOHOL:`<rect x="4.6" y="9.4" width="14.8" height="6.4" rx="3.2" transform="rotate(-38 12 12)" fill="none" stroke="#fff" stroke-width="1.7"/>
48
- <path d="M9.9 8.5 14.6 14.7" ${Fs}/>`,COARSE_LANGUAGE:`<path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2Z" fill="#fff"/>
49
- <path d="M12 5.6v5" stroke="#0E0E10" stroke-width="2.1" stroke-linecap="round"/><circle cx="12" cy="13.6" r="1.25" fill="#0E0E10"/>`},rm=[.25,.5,.75,1,1.25,1.5,2];function Ii(r){let e=Math.max(0,Math.floor(r/1e3)),t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=e%60;return t>0?`${t}:${String(i).padStart(2,"0")}:${String(s).padStart(2,"0")}`:`${i}:${String(s).padStart(2,"0")}`}var Ns=class extends HTMLElement{playerRef=null;cfg={...ua};root;controlsVisible=!0;hideTimer=null;bufferingTimer=null;scrubbing=!1;openMenu=null;titleShownGeneration=-1;ratingsShownGeneration=-1;ratingRowVisible=!1;lastSeenGeneration=-1;errored=!1;lastOverlayGeneration=-1;lastCueKey="";lastAdCueKey="";col={...ws};dimE={...xi};dimF={...Ms};overlayTimers=[];detachFns=[];constructor(){super(),this.root=this.attachShadow({mode:"open"})}get player(){return this.playerRef}set player(e){this.detach(),this.playerRef=e,e&&this.isConnected&&this.mount()}get config(){return this.cfg}set config(e){if((e.customActions?.length??0)>8)throw new Error(`At most 8 custom actions are supported (got ${e.customActions.length})`);this.cfg={...ua,...e},this.col={...ws,...e.colors??{}},this.dimE={...xi,...e.dimens??{}},this.dimF={...Ms,...e.dimens??{}},this.playerRef&&this.isConnected&&this.mount()}connectedCallback(){this.playerRef&&this.mount()}disconnectedCallback(){this.detach()}get dims(){return document.fullscreenElement===this?this.dimF:this.dimE}glyph(e,t){return{play:this.cfg.playIconSvg,pause:this.cfg.pauseIconSvg,replay:this.cfg.replayIconSvg,seekForward:this.cfg.seekForwardIconSvg,seekBack:this.cfg.seekBackwardIconSvg,fullscreenEnter:this.cfg.fullscreenEnterIconSvg,fullscreenExit:this.cfg.fullscreenExitIconSvg,subtitles:this.cfg.subtitlesIconSvg,audioTrack:this.cfg.audioTrackIconSvg,speed:this.cfg.speedIconSvg,quality:this.cfg.qualityIconSvg,volumeOn:this.cfg.volumeOnIconSvg,volumeMute:this.cfg.volumeMuteIconSvg}[e]??Ot(e,t,this.col.foreground)}mount(){this.detach();let e=this.playerRef,t=this.col,i=tm.map(s=>`<div class="ovl ovl-${s}" part="overlay-${s}" data-testid="og_overlay_${s.replace(/-/g,"_")}"><slot name="${s}"></slot></div>`).join("");this.root.innerHTML=`
47
+ <path d="M4.5 4.5 19.5 19.5" ${Bs}/>`,DRUGS_ALCOHOL:`<rect x="4.6" y="9.4" width="14.8" height="6.4" rx="3.2" transform="rotate(-38 12 12)" fill="none" stroke="#fff" stroke-width="1.7"/>
48
+ <path d="M9.9 8.5 14.6 14.7" ${Bs}/>`,COARSE_LANGUAGE:`<path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2Z" fill="#fff"/>
49
+ <path d="M12 5.6v5" stroke="#0E0E10" stroke-width="2.1" stroke-linecap="round"/><circle cx="12" cy="13.6" r="1.25" fill="#0E0E10"/>`},hm=[.25,.5,.75,1,1.25,1.5,2];function Ii(r){let e=Math.max(0,Math.floor(r/1e3)),t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=e%60;return t>0?`${t}:${String(i).padStart(2,"0")}:${String(s).padStart(2,"0")}`:`${i}:${String(s).padStart(2,"0")}`}var $s=class extends HTMLElement{playerRef=null;cfg={...ma};root;controlsVisible=!0;hideTimer=null;hidePoint=null;bufferingTimer=null;scrubbing=!1;openMenu=null;titleShownGeneration=-1;ratingsShownGeneration=-1;ratingRowVisible=!1;lastSeenGeneration=-1;errored=!1;lastOverlayGeneration=-1;lastCueKey="";lastAdCueKey="";col={...Os};dimE={...xi};dimF={...Fs};overlayTimers=[];detachFns=[];constructor(){super(),this.root=this.attachShadow({mode:"open"})}get player(){return this.playerRef}set player(e){this.detach(),this.playerRef=e,e&&this.isConnected&&this.mount()}get config(){return this.cfg}set config(e){if((e.customActions?.length??0)>8)throw new Error(`At most 8 custom actions are supported (got ${e.customActions.length})`);this.cfg={...ma,...e},this.col={...Os,...e.colors??{}},this.dimE={...xi,...e.dimens??{}},this.dimF={...Fs,...e.dimens??{}},this.playerRef&&this.isConnected&&this.mount()}connectedCallback(){this.playerRef&&this.mount()}disconnectedCallback(){this.detach()}get dims(){return document.fullscreenElement===this?this.dimF:this.dimE}glyph(e,t){return{play:this.cfg.playIconSvg,pause:this.cfg.pauseIconSvg,replay:this.cfg.replayIconSvg,seekForward:this.cfg.seekForwardIconSvg,seekBack:this.cfg.seekBackwardIconSvg,fullscreenEnter:this.cfg.fullscreenEnterIconSvg,fullscreenExit:this.cfg.fullscreenExitIconSvg,subtitles:this.cfg.subtitlesIconSvg,audioTrack:this.cfg.audioTrackIconSvg,speed:this.cfg.speedIconSvg,quality:this.cfg.qualityIconSvg,volumeOn:this.cfg.volumeOnIconSvg,volumeMute:this.cfg.volumeMuteIconSvg}[e]??Ot(e,t,this.col.foreground)}mount(){this.detach();let e=this.playerRef,t=this.col,i=om.map(s=>`<div class="ovl ovl-${s}" part="overlay-${s}" data-testid="og_overlay_${s.replace(/-/g,"_")}"><slot name="${s}"></slot></div>`).join("");this.root.innerHTML=`
50
50
  <style>${this.css()}</style>
51
51
  <style class="cuestyle"></style>
52
52
  <div class="stage" tabindex="0" data-testid="og_player">
@@ -56,7 +56,7 @@ Schedule: ${l.map(m=>Ue(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Remo
56
56
  <div class="title" data-testid="og_title" hidden></div>
57
57
  <div class="ratings" data-testid="og_ratings_row" hidden></div>
58
58
  <div class="watermark" hidden>
59
- ${Os(20,"rgba(255,255,255,0.72)",t.adAccent)}<span>OGPlayer</span>
59
+ ${Ns(20,"rgba(255,255,255,0.72)",t.adAccent)}<span>OGPlayer</span>
60
60
  </div>
61
61
  <div class="chrome" hidden>
62
62
  <div class="scrim scrim-top"></div>
@@ -90,9 +90,9 @@ Schedule: ${l.map(m=>Ue(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Remo
90
90
  <div class="abpanel">
91
91
  <span class="abtitle">Ads are blocked</span>
92
92
  <span class="abtext">This video is made available with ads, but your ad
93
- blocker prevented them from loading. Please allow ads for this site and
94
- reload the page.</span>
95
- <button class="abclose" aria-label="Dismiss">Continue anyway</button>
93
+ blocker prevented them from loading. Your video plays on without ads \u2014
94
+ please consider allowing ads for this site to support it.</span>
95
+ <button class="abclose" aria-label="Dismiss">Got it</button>
96
96
  </div>
97
97
  </div>
98
98
  <div class="buffering" data-testid="og_buffering" hidden><div class="dim"></div><div class="ring" hidden></div></div>
@@ -289,9 +289,8 @@ Schedule: ${l.map(m=>Ue(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Remo
289
289
  .fs .menu { min-width:260px; bottom:78px; }
290
290
  .fs .title { font-size:24px; }
291
291
  .fs .ratings .age, .fs .ratings .desc { width:36px; height:36px; font-size:16px; }
292
- `}buildButtons(){let e=this.q(".buttons");e.innerHTML="";let t=(n,a,o)=>{let l=document.createElement("button");return l.className=`bbtn b-${n}`,l.dataset.testid=em[n]??`og_btn_${n}`,l.innerHTML=this.glyph(a,this.dimE.iconSize),l.addEventListener("click",d=>{d.stopPropagation(),o(),this.armAutoHide()}),e.appendChild(l),l};this.cfg.showVolumeButton&&t("volume","volumeOn",()=>this.toggleMenu("volume")),this.cfg.showSpeedButton&&t("speed","speed",()=>this.toggleMenu("speed")),this.cfg.showQualityButton&&t("quality","quality",()=>this.toggleMenu("quality")),this.cfg.showAudioTrackButton&&t("audio","audioTrack",()=>this.toggleMenu("audio")),this.cfg.showSubtitleButton&&t("subs","subtitles",()=>this.toggleMenu("subs")),this.cfg.showFullscreenButton&&t("fs","fullscreenEnter",()=>this.toggleFullscreen());let i=this.q(".seekback"),s=this.q(".seekfwd");i.hidden=s.hidden=!this.cfg.showSeekButtons,this.q(".seekback .seeknum").textContent=String(Math.round((this.playerRef?.seekBackwardIncrementMs??1e4)/1e3)),this.q(".seekfwd .seeknum").textContent=String(Math.round((this.playerRef?.seekForwardIncrementMs??1e4)/1e3)),this.q(".scrub").hidden=!this.cfg.showProgressBar,this.q(".time").hidden=!this.cfg.showTimeLabels}buildTopEnd(){let e=this.q(".topend");e.innerHTML="",this.cfg.customActions.slice(0,8).forEach((t,i)=>{let s=document.createElement("button");s.className="abtn",s.dataset.testid=`og_custom_action_${i}`,s.setAttribute("aria-label",t.accessibilityLabel??`Custom action ${i+1}`),s.innerHTML=t.svg;let n=s.querySelector("svg");n&&(n.style.color=this.col.foreground,n.setAttribute("fill","currentColor")),s.addEventListener("click",a=>{a.stopPropagation(),t.onClick(),this.armAutoHide()}),e.appendChild(s)})}toggleMenu(e){if(this.openMenu===e){this.closeMenu();return}this.openMenu=e;let t=this.q(".menu");t.hidden=!1,t.classList.toggle("narrow",e==="volume"),t.innerHTML="";let i=this.playerRef,s=this.col,n=(a,o,l,d)=>{let c=document.createElement("div");c.className="mitem",c.dataset.testid="og_menu_item",c.innerHTML=`<span class="mcheck">${o?Ot("check",18,s.adAccent):""}</span>
293
- <span>${a}</span>${l?`<span class="msub">${l}</span>`:""}`,c.addEventListener("click",h=>{h.stopPropagation(),d(),this.closeMenu(),this.armAutoHide()}),t.appendChild(c)};if(e==="volume"){let a=document.createElement("div");a.className="mitem vol";let o=()=>this.glyph(i.isMuted||i.volume===0?"volumeMute":"volumeOn",22);a.innerHTML=`<button class="mmute" data-testid="og_btn_mute" aria-label="Mute">${o()}</button>
294
- <input type="range" data-testid="og_volume_slider" min="0" max="100" value="${i.isMuted?0:Math.round(i.volume*100)}">`;let l=a.querySelector("input"),d=a.querySelector(".mmute"),c=()=>{d.innerHTML=o(),this.syncButtons()};l.addEventListener("input",()=>{i.volume=Number(l.value)/100,i.isMuted&&Number(l.value)>0&&(i.isMuted=!1),c()}),l.addEventListener("click",h=>h.stopPropagation()),d.addEventListener("click",h=>{h.stopPropagation(),i.isMuted=!i.isMuted,l.value=String(i.isMuted?0:Math.round(i.volume*100)),c()}),t.appendChild(a)}else if(e==="speed")rm.forEach(a=>n(a===1?"Normal":`${a}\xD7`,i.playbackSpeed===a,null,()=>{i.playbackSpeed=a}));else if(e==="quality"){let a=i.videoQualities;a.length===0&&n("Auto",!0,"adaptive",()=>{}),a.forEach(o=>n(o.id==="auto"?"Auto":`${o.height}p`,o.isSelected,o.id==="auto"?"adaptive":`${Math.round(o.bitrate/1e3)} kbps`,()=>i.selectVideoQuality(o.id)))}else if(e==="audio")i.audioTracks.forEach(a=>n(a.label,a.isSelected,a.language||null,()=>i.selectAudioTrack(a.id))),i.audioTracks.length===0&&n("Default",!0,null,()=>{});else if(e==="subs"){let a=i.textTracks;n("Off",!a.some(o=>o.isSelected),null,()=>i.selectTextTrack(null)),a.forEach(o=>n(o.label,o.isSelected,o.language||null,()=>i.selectTextTrack(o.id)))}}closeMenu(){this.openMenu=null,this.q(".menu").hidden=!0}bind(){let e=this.playerRef,t=this.q(".stage"),i=d=>{if(!d.target.closest(".cbtn,.bbtn,.abtn,.menu,.scrub,.livechip")){if(this.openMenu){this.closeMenu();return}this.controlsVisible?this.hideControls():this.showControls()}};t.addEventListener("click",i),this.cfg.doubleClickToSeek&&t.addEventListener("dblclick",d=>{if(d.target.closest(".cbtn,.bbtn,.abtn,.menu,.scrub"))return;let c=t.getBoundingClientRect();d.clientX-c.left<c.width/2?e.seekBackward():e.seekForward()}),this.q(".playpause").addEventListener("click",d=>{d.stopPropagation(),e.isPlaying?e.pause():e.play(),this.armAutoHide()}),this.q(".seekback").addEventListener("click",d=>{d.stopPropagation(),e.seekBackward(),this.armAutoHide()}),this.q(".seekfwd").addEventListener("click",d=>{d.stopPropagation(),e.seekForward(),this.armAutoHide()}),this.q(".livechip").addEventListener("click",d=>{d.stopPropagation(),e.seekToLiveEdge(),this.armAutoHide()}),this.q(".adtransport").addEventListener("click",d=>{d.stopPropagation(),e.adPaused?e.play():e.pause()}),this.q(".upnext").addEventListener("click",d=>{d.stopPropagation(),e.skipToNext()}),this.bindScrub();let s={onStateChanged:d=>this.onState(d),onIsPlayingChanged:d=>{this.syncButtons(),this.armAutoHide(),d&&this.maybeShowOnceOverlays()},onError:d=>{let c=this.q(".errorovl");if(c.hidden=!1,c.dataset.gen=String(e.currentLoadGeneration),this.lastSeenGeneration=e.currentLoadGeneration,c.textContent="",this.cfg.renderErrorOverlay)c.classList.add("hostovl"),c.appendChild(this.cfg.renderErrorOverlay(d,()=>e.retry()));else{c.classList.remove("hostovl");let h=document.createElement("span");if(h.textContent=this.cfg.errorMessageProvider?.(d)??`Playback error ${d.code}`,this.cfg.errorTextStyle&&(h.style.cssText+=";"+this.cfg.errorTextStyle),c.appendChild(h),this.cfg.showRetryButton){let u=document.createElement("button");u.className="retry",u.dataset.testid="og_btn_error_retry",u.textContent=this.cfg.retryButtonLabel,this.cfg.retryButtonStyle&&(u.style.cssText+=";"+this.cfg.retryButtonStyle),u.addEventListener("click",f=>{f.stopPropagation(),e.retry()}),c.appendChild(u)}}this.q(".buffering").hidden=!0,this.bufferingTimer!==null&&(clearTimeout(this.bufferingTimer),this.bufferingTimer=null),this.errored=!0,this.hideControls()},onProgress:()=>{this.syncProgress(),this.syncUpNext()}};e.addListener(s),this.detachFns.push(()=>e.removeListener(s));let n=()=>{let d=document.fullscreenElement===this,c=d?this.dimF:this.dimE;this.q(".stage").classList.toggle("fs",d),this.style.setProperty("--edge",`${c.edgeInset}px`),this.style.setProperty("--rowh",`${c.bottomBarHeight}px`),this.style.setProperty("--rowpad",d?"8px":"4px");let h=this.q(".b-fs");h&&(h.innerHTML=this.glyph(d?"fullscreenExit":"fullscreenEnter",this.dimE.iconSize))};document.addEventListener("fullscreenchange",n),this.detachFns.push(()=>document.removeEventListener("fullscreenchange",n));let a=new ResizeObserver(()=>{this.applyCueSize(),this.playerRef?.notifyAdViewResize(this.clientWidth,this.clientHeight,document.fullscreenElement===this)});a.observe(this),this.detachFns.push(()=>a.disconnect()),e.onLicenseChanged(()=>this.syncWatermark());let o={onAdError:d=>{if(d.code!==902||this.cfg.adBlockerPolicy==="none")return;let c=this.q(".adblocknotice");c.dataset.gen=String(e.currentLoadGeneration),c.hidden=!1;let h=this.cfg.adBlockerPolicy==="block";c.classList.toggle("hard",h),this.q(".abclose").textContent=h?"I disabled it \u2014 reload":"Continue anyway",this.q(".abtext").textContent=h?"This video is only available with ads. Please disable your ad blocker for this site, then reload.":"This video is made available with ads, but your ad blocker prevented them from loading. Please allow ads for this site and reload the page.",h&&(this.q(".stage").classList.add("adblocked"),e.holdPlayback=!0,e.pause())}};e.addAdListener(o),this.detachFns.push(()=>e.removeAdListener(o)),this.q(".abclose").addEventListener("click",d=>{if(d.stopPropagation(),this.q(".adblocknotice").classList.contains("hard")){location.reload();return}this.q(".adblocknotice").hidden=!0});let l=window.setInterval(()=>this.syncPeriodic(),500);this.detachFns.push(()=>clearInterval(l))}bindScrub(){let e=this.playerRef,t=this.q(".scrub"),i=n=>{let a=t.getBoundingClientRect();return Math.min(1,Math.max(0,(n.clientX-a.left)/a.width))},s=()=>{let n=e.videoElement.seekable;return e.liveInfo&&n.length>0?[n.start(0)*1e3,n.end(n.length-1)*1e3]:[0,e.durationMs]};t.addEventListener("pointerdown",n=>{this.scrubbing=!0,t.classList.add("active"),t.setPointerCapture(n.pointerId),this.paintScrub(i(n)),this.showThumbPreview(i(n),s()),this.cancelAutoHide()}),t.addEventListener("pointermove",n=>{let a=i(n);this.scrubbing&&this.paintScrub(a),(this.scrubbing||n.pointerType==="mouse")&&this.showThumbPreview(a,s())}),t.addEventListener("pointerleave",()=>{this.scrubbing||this.hideThumbPreview()}),t.addEventListener("pointerup",n=>{if(!this.scrubbing)return;this.scrubbing=!1,t.classList.remove("active"),this.hideThumbPreview();let[a,o]=s();e.seekTo(a+i(n)*(o-a)),this.armAutoHide()})}thumbPreviewSeq=0;showThumbPreview(e,[t,i]){let s=this.playerRef,n=this.q(".thumbpreview"),a=t+e*(i-t);if(!s.hasThumbnails){if(!this.scrubbing){n.hidden=!0;return}n.hidden=!1,this.q(".tpimg").style.cssText="display:none",this.q(".tptime").textContent=Ii(a),this.placeThumbPreview(e);return}n.hidden=!1,this.placeThumbPreview(e),this.q(".tptime").textContent=Ii(a);let o=++this.thumbPreviewSeq;s.getThumbnail(a).then(l=>{if(o!==this.thumbPreviewSeq||!l)return;let d=this.q(".tpimg"),c=this.q(".tpframe");if(l.width>0){let h=Math.min(1,168/l.width);d.style.cssText=`display:block;width:${l.width*h}px;height:${l.height*h}px;`,c.style.cssText=`width:${l.width}px;height:${l.height}px;background-image:url("${l.url}");background-position:${-l.x}px ${-l.y}px;transform:scale(${h});`}else d.style.cssText="display:block;width:168px;height:94px;",c.style.cssText=`width:168px;height:94px;background-image:url("${l.url}");background-size:cover;background-position:center;`;this.placeThumbPreview(e)})}placeThumbPreview(e){let t=this.q(".thumbpreview").offsetWidth/2;this.q(".thumbpreview").style.left=t>0?`clamp(${t}px, ${e*100}%, calc(100% - ${t}px))`:`${e*100}%`}hideThumbPreview(){this.q(".thumbpreview").hidden=!0}paintScrub(e){this.q(".played").style.width=`${e*100}%`,this.q(".thumb").style.left=`${e*100}%`}onState(e){e==="BUFFERING"&&(this.q(".errorovl").hidden=!0,this.errored=!1);let t=this.q(".buffering"),i=this.q(".ring");e==="BUFFERING"?(t.hidden=!1,i.hidden=!0,this.bufferingTimer===null&&(this.bufferingTimer=window.setTimeout(()=>{i.hidden=!1},250))):(t.hidden=!0,this.bufferingTimer!==null&&(clearTimeout(this.bufferingTimer),this.bufferingTimer=null)),this.q(".endeddim").hidden=e!=="ENDED",this.syncButtons()}maybeShowOnceOverlays(){let e=this.playerRef,t=e.currentLoadGeneration,i=e.currentItem;if(!i)return;if(t!==this.lastOverlayGeneration){this.lastOverlayGeneration=t,this.overlayTimers.forEach(a=>clearTimeout(a)),this.overlayTimers=[],this.setRatingRow(!1);let n=this.q(".title");n.hidden=!0,n.style.top="12px",this.q(".ratings").hidden=!0}if(this.cfg.showTitle&&i.title&&this.titleShownGeneration!==t){this.titleShownGeneration=t;let n=this.q(".title");n.textContent=i.title,n.hidden=!1,n.style.opacity="1",this.overlayTimers.push(window.setTimeout(()=>{n.style.opacity="0"},this.cfg.titleTimeoutMs)),this.overlayTimers.push(window.setTimeout(()=>{n.hidden=!0},this.cfg.titleTimeoutMs+700))}let s=i.contentRatings??[];if(this.cfg.showContentRatings&&s.length>0&&this.ratingsShownGeneration!==t){this.ratingsShownGeneration=t;let n=this.q(".ratings");n.innerHTML=s.map(o=>this.ratingHtml(o)).join(""),n.hidden=!1,n.style.opacity="1",this.setRatingRow(!0),this.overlayTimers.push(window.setTimeout(()=>{n.style.opacity="0",this.setRatingRow(!1)},this.cfg.contentRatingsTimeoutMs)),this.overlayTimers.push(window.setTimeout(()=>{n.hidden=!0},this.cfg.contentRatingsTimeoutMs+700));let a=this.q(".title");a.style.top="53px",this.overlayTimers.push(window.setTimeout(()=>{a.style.top="12px"},this.cfg.contentRatingsTimeoutMs))}}ratingHtml(e){return"age"in e?`<span class="age" style="background:${sm[e.age]}">${im[e.age]}</span>`:"descriptor"in e?`<span class="desc"><svg viewBox="0 0 24 24" width="16" height="16">${nm[e.descriptor]??""}</svg></span>`:`<img src="${e.customIconUrl}" alt="">`}setRatingRow(e){this.ratingRowVisible=e,this.q(".topend").style.paddingTop=e?"48px":"8px",this.applyOverlayInsets()}applyOverlayInsets(){let e=this.controlsVisible&&this.ratingRowVisible,t=this.controlsVisible||this.ratingRowVisible,s=Math.min(e?104:t?64:0,this.clientHeight*.5),n=this.controlsVisible?Math.min(68,this.clientHeight*.3):0,a=this.q(".overlays");a.style.top=`${s}px`,a.style.bottom=`${n}px`,this.q(".watermark").style.transform=`translateX(-50%) translateY(${this.ratingRowVisible?43:0}px)`}showControls(){this.errored||(this.controlsVisible=!0,this.q(".chrome").hidden=!1,this.applyOverlayInsets(),this.armAutoHide())}hideControls(){this.controlsVisible=!1,this.q(".chrome").hidden=!0,this.closeMenu(),this.applyOverlayInsets()}armAutoHide(){this.cancelAutoHide(),this.playerRef?.isPlaying&&(this.hideTimer=window.setTimeout(()=>{this.openMenu===null&&!this.scrubbing?this.hideControls():this.armAutoHide()},this.cfg.controlsTimeoutMs))}cancelAutoHide(){this.hideTimer!==null&&(clearTimeout(this.hideTimer),this.hideTimer=null)}syncAll(){this.syncButtons(),this.syncProgress(),this.syncWatermark(),this.applyCueSize(),this.applyOverlayInsets()}syncButtons(){let e=this.playerRef,t=this.q(".playpause"),i=e.state==="ENDED"?"replay":e.isPlaying?"pause":"play";t.innerHTML=this.glyph(i,44),t.setAttribute("aria-label",i==="pause"?"Pause":"Play");let s=this.q(".b-volume");s&&(s.innerHTML=this.glyph(e.isMuted||e.volume===0?"volumeMute":"volumeOn",this.dimE.iconSize))}syncUpNext(){let e=this.playerRef,t=this.q(".upnext"),i=e.nextPlaylistItem,s=e.durationMs;if(!this.cfg.showUpNext||this.errored||e.isPlayingAd||!i||s<=0){t.hidden=!0;return}let n=s-e.currentPositionMs,a=Math.min(60,Math.max(1,this.cfg.upNextLeadSeconds))*1e3;if(n<=0||n>a){t.hidden=!0;return}t.textContent=this.cfg.upNextText.replace("{seconds}",String(Math.ceil(n/1e3))).replace("{title}",i.title??""),t.hidden=!1}syncProgress(){if(this.scrubbing)return;let e=this.playerRef,t=e.liveInfo,i=this.q(".time");if(t){let s=e.videoElement.seekable;if(s.length>0){let a=s.start(0),o=s.end(s.length-1),l=o>a?(e.videoElement.currentTime-a)/(o-a):1;this.paintScrub(Math.min(1,Math.max(0,l))),this.q(".buffered").style.width="0"}let n=t.latencyMs>12e3?` \u2212${Ii(t.latencyMs)}`:"";i.innerHTML=t.atLiveEdge?"":`<b>${n}</b>`}else{let s=e.durationMs,n=s>0?e.currentPositionMs/s:0;this.paintScrub(Math.min(1,n)),this.q(".buffered").style.width=`${s>0?Math.min(100,e.bufferedPositionMs/s*100):0}%`,i.innerHTML=`<b>${Ii(e.currentPositionMs)}</b> / ${Ii(s)}`,this.paintAdCues(s)}}paintAdCues(e){let t=this.playerRef,i=e>0&&this.cfg.showAdCueMarkers?t.adCuePoints.map(a=>a<0?1:Math.min(1,a*1e3/e)):[],s=i.map(a=>a.toFixed(3)).join(",");if(s===this.lastAdCueKey)return;this.lastAdCueKey=s;let n=this.q(".track");n.querySelectorAll(".cue").forEach(a=>a.remove());for(let a of i){let o=document.createElement("div");o.className="cue",o.style.left=`${a*100}%`,n.appendChild(o)}}syncPeriodic(){let e=this.playerRef;if(e.currentLoadGeneration!==this.lastSeenGeneration){this.lastSeenGeneration=e.currentLoadGeneration,this.q(".errorovl").hidden=!0,this.errored=!1;let c=this.q(".adblocknotice");c.dataset.gen!==String(e.currentLoadGeneration)&&(c.hidden=!0,this.q(".stage").classList.contains("adblocked")&&(this.q(".stage").classList.remove("adblocked"),e.holdPlayback=!1))}this.q(".stage").classList.contains("adblocked")&&e.isPlaying&&e.pause(),this.syncAdUi();let t=`${e.subtitleTextScale}|${e.subtitleStyle.textSizeFraction}|${e.subtitleStyle.foregroundColor}|${e.subtitleStyle.backgroundColor}|${e.subtitleStyle.edgeType}|${e.subtitleStyle.edgeColor}|${e.subtitleStyle.fontFamily}`;t!==this.lastCueKey&&(this.lastCueKey=t,this.applyCueSize());let i=e.liveInfo,s=this.q(".livechip");s.hidden=!i,i&&s.classList.toggle("behind",!i.atLiveEdge);let n=e.currentItem?.streamType??"VOD",a=n!=="LIVE",o=n!=="VOD";this.q(".scrub").hidden=!this.cfg.showProgressBar||!a,this.q(".time").hidden=!this.cfg.showTimeLabels||!a;let l=!this.cfg.showSeekButtons||!a;this.q(".seekback").hidden=l,this.q(".seekfwd").hidden=l;let d=this.root.querySelector(".b-speed");d&&(d.hidden=o||!this.cfg.showSpeedButton)}syncAdUi(){let e=this.playerRef,t=this.q(".stage");t.classList.toggle("adplaying",e.isPlayingAd),t.classList.toggle("adspending",e.adsPending);let i=this.q(".adchrome"),s=this.q(".adtransport"),n=e.adProgress;if(e.isPlayingAd&&n){i.hidden=!1,s.hidden=!1;let a=n.durationMs>0?Math.min(1,n.positionMs/n.durationMs):0;this.q(".adfill").style.width=`${a*100}%`,this.q(".adpod").textContent=n.adCount>1?`${n.adIndex}/${n.adCount}`:"";let o=Math.max(0,Math.ceil((n.durationMs-n.positionMs)/1e3));this.q(".adtime").textContent=`${Math.floor(o/60)}:${String(o%60).padStart(2,"0")}`,s.innerHTML=e.adPaused?this.cfg.adPlayIconSvg??Ot("play",34,this.col.foreground):this.cfg.adPauseIconSvg??Ot("pause",34,this.col.foreground),s.setAttribute("aria-label",e.adPaused?"Resume ad":"Pause ad")}else i.hidden=!0,s.hidden=!e.isPlayingAd,e.isPlayingAd&&(s.innerHTML=e.adPaused?this.cfg.adPlayIconSvg??Ot("play",34,this.col.foreground):this.cfg.adPauseIconSvg??Ot("pause",34,this.col.foreground))}syncWatermark(){this.q(".watermark").hidden=this.playerRef?.isLicensed??!1}applyCueSize(){let e=this.playerRef;if(!e)return;let t=this.clientHeight||0,i=Math.max(13,Math.min(t*e.subtitleStyle.textSizeFraction,44))*e.subtitleTextScale,s=e.subtitleStyle,n=s.edgeColor,a=s.edgeType==="OUTLINE"?`text-shadow:-1px -1px 0 ${n},1px -1px 0 ${n},-1px 1px 0 ${n},1px 1px 0 ${n};`:s.edgeType==="DROP_SHADOW"?`text-shadow:2px 2px 3px ${n};`:s.edgeType==="RAISED"?`text-shadow:0 -1px 0 ${n};`:s.edgeType==="DEPRESSED"?`text-shadow:0 1px 0 ${n};`:"",o=s.fontFamily?`font-family:${s.fontFamily};`:"";this.q(".cuestyle").textContent=`video::cue { background:${s.backgroundColor}; color:${s.foregroundColor}; font-size:${i.toFixed(1)}px; ${a}${o} }`}enterNativeVideoFullscreen(){let e=this.playerRef?.videoElement;return e?.webkitEnterFullscreen?(e.webkitEnterFullscreen(),!0):!1}enterFullscreen(){return typeof this.requestFullscreen=="function"?this.requestFullscreen():(this.enterNativeVideoFullscreen(),Promise.resolve())}exitFullscreen(){document.fullscreenElement===this&&document.exitFullscreen();let e=this.playerRef?.videoElement;e?.webkitDisplayingFullscreen&&e.webkitExitFullscreen?.()}toggleFullscreen(){document.fullscreenElement===this?this.cfg.onFullscreenExitRequest?this.cfg.onFullscreenExitRequest():document.exitFullscreen():typeof this.requestFullscreen=="function"?this.requestFullscreen():this.enterNativeVideoFullscreen()}detach(){this.detachFns.forEach(i=>i()),this.detachFns=[];let e=this.root.querySelector(".videohost"),t=this.playerRef?.videoElement;e&&t&&t.parentElement===e&&e.removeChild(t),this.overlayTimers.forEach(i=>clearTimeout(i)),this.overlayTimers=[],this.cancelAutoHide(),this.bufferingTimer!==null&&(clearTimeout(this.bufferingTimer),this.bufferingTimer=null)}};function fa(){customElements.get("og-player")||customElements.define("og-player",Ns)}var Bs={preloadAhead:1,keepBehind:1,loopItems:!0,contentFit:"FILL",showTitle:!1,showSubtitle:!1,showProgressBar:!0,showSponsoredBadge:!0,progressBarThickness:2,progressBarColor:"#FFFFFF",progressBarTrackColor:"rgba(255,255,255,0.25)",playIconSvg:null,textFontFamily:null,titleTextSize:16,subtitleTextSize:13,textBandColor:"transparent",textBandFraction:1/3,textBandTopMargin:16,paginationThreshold:2,maxItemDurationSeconds:0,licenseKey:null,errorMessageProvider:null},Li=class{constructor(e,t){this.config=e;this.callbacks=t;this.capacity=Math.min(3,e.preloadAhead+e.keepBehind+1)}items=[];entries=[];capacity;activeIndexValue=-1;released=!1;feedMuted=!1;skipped=new Set;licensedValue=null;get activeIndex(){return this.activeIndexValue}get isLicensed(){return this.licensedValue}get skippedIndices(){return this.skipped}updateItems(e){this.items=e,this.activeIndexValue>=0&&this.settle(Math.min(this.activeIndexValue,e.length-1))}playerAt(e){return this.entries.find(t=>t.index===e)?.player??null}setFeedMuted(e){this.feedMuted=e;let t=this.entries.find(i=>i.index===this.activeIndexValue);t&&(t.player.isMuted=this.primaryMuted(t.index))}settle(e){if(this.released||e<0||e>=this.items.length)return;let t=e-this.config.keepBehind,i=e+this.config.preloadAhead,s=this.activeIndexValue;if(e!==s){let o=this.entries.find(l=>l.index===s);o&&this.emitWatched(o),this.callbacks.onAnalyticsEvent?.({type:"VerticalFeedImpression",index:e,url:this.items[e].media.url})}this.activeIndexValue=e;let n=this.entryFor(e);if(n){let o=this.items[e];n.player.setBufferRole("ACTIVE"),n.player.setLooping(this.config.loopItems&&!o.isSponsored),n.player.isMuted=this.primaryMuted(e),o.secondaryMedia||n.player.play()}if(s!==e){let o=this.entries.find(l=>l.index===s);o&&s>=t&&s<=i&&this.demote(o)}for(let o of this.entries)o.index!==-1&&(o.index<t||o.index>i)&&this.recycle(o);for(let o of this.windowOrder(e,t,i))o>=0&&o<this.items.length&&!this.skipped.has(o)&&!this.entries.some(l=>l.index===o)&&this.entryFor(o);this.callbacks.onAssignmentsChanged?.(),this.callbacks.onActiveItemChanged?.(e);let a=this.items.length-1-e;a<=this.config.paginationThreshold&&this.callbacks.onNearEnd?.(a)}releaseAll(){if(this.released)return;let e=this.entries.find(t=>t.index===this.activeIndexValue);e&&this.emitWatched(e),this.released=!0;for(let t of this.entries)t.detach(),t.player.release();this.entries=[]}primaryMuted(e){let t=this.items[e];return t?.secondaryMedia&&(t.splitAudioSource??"PRIMARY")==="SECONDARY"?!0:this.feedMuted}windowOrder(e,t,i){let s=[];for(let n=1;n<=Math.max(e-t,i-e);n++)e+n<=i&&s.push(e+n),e-n>=t&&s.push(e-n);return s}entryFor(e){if(e<0||e>=this.items.length||this.skipped.has(e))return null;let t=this.entries.find(a=>a.index===e);if(t)return t;let i=this.entries.find(a=>a.index===-1)??this.createEntry();if(!i)return null;i.index=e,i.loopCount=0,i.watchTimeMs=0,i.lastPositionMs=0,i.durationChecked=!1;let s=this.items[e],n=e!==this.activeIndexValue;return i.player.setBufferRole(n?"STANDBY":"ACTIVE"),i.player.isMuted=n?!0:this.primaryMuted(e),i.player.setLooping(this.config.loopItems&&!s.isSponsored),i.player.load(s.media,{autoplay:!1}),i}createEntry(){if(this.entries.length>=this.capacity)return null;let e=new Mt({...this.config.licenseKey?{licenseKey:this.config.licenseKey}:{},fallbackToMutedAutoplay:!0});e.onLicenseChanged(n=>{this.licensedValue=n,this.callbacks.onAssignmentsChanged?.()});let t={player:e,index:-1,loopCount:0,watchTimeMs:0,lastPositionMs:0,durationChecked:!1,detach:()=>{}},i={onProgress:n=>{if(this.released||t.index!==this.activeIndexValue)return;let a=n-t.lastPositionMs;a>0&&a<=1e3&&(t.watchTimeMs+=a),a<-2e3&&t.player.isLooping&&(t.loopCount++,this.callbacks.onAnalyticsEvent?.({type:"VerticalFeedItemLooped",index:t.index,loopCount:t.loopCount})),t.lastPositionMs=n},onPlaybackCompleted:()=>{if(this.released||t.index<0)return;this.items[t.index]?.isSponsored&&t.index===this.activeIndexValue&&this.callbacks.onAdvanceRequested?.(t.index)},onError:n=>{this.released||t.index<0||(this.callbacks.onItemError?.(t.index,n),this.callbacks.onAnalyticsEvent?.({type:"Error",error:n}))}};e.addListener(i),e.addAnalyticsListener(n=>{n.type==="MutedAutoplayFallback"&&t.index===this.activeIndexValue&&this.callbacks.onAnalyticsEvent?.(n)});let s=()=>{if(this.released||t.durationChecked||t.index<0)return;t.durationChecked=!0;let n=this.config.maxItemDurationSeconds;if(n>0&&e.durationMs>n*1e3){let a=t.index;this.skipped.add(a),this.recycle(t),this.callbacks.onItemSkipped?.(a,"durationExceeded"),this.callbacks.onAssignmentsChanged?.()}};return e.videoElement.addEventListener("loadedmetadata",s),t.detach=()=>{e.removeListener(i),e.videoElement.removeEventListener("loadedmetadata",s)},this.entries.push(t),t}demote(e){e.player.pause(),e.player.isMuted=!0,e.player.setBufferRole("STANDBY"),e.player.seekTo(0)}recycle(e){e.index===this.activeIndexValue&&this.emitWatched(e),e.player.pause(),e.index=-1,e.player.videoElement.removeAttribute("src"),e.player.videoElement.load()}emitWatched(e){if(e.index<0||e.watchTimeMs<=0)return;let t=this.items[e.index];t&&(this.callbacks.onAnalyticsEvent?.({type:"VerticalFeedItemWatched",index:e.index,url:t.media.url,watchTimeMs:Math.round(e.watchTimeMs),loopCount:e.loopCount}),e.watchTimeMs=0)}};var $s=class extends HTMLElement{root;pool=null;itemsValue=[];cfg={...Bs};mutedValue=!1;intendedPage=0;observer=null;resizeObserver=null;tickTimer=null;itemErrors=new Map;secondary=null;secondaryFor=-1;secondaryDetach=null;singleTapTimer=null;scrubbing=!1;mounted=!1;sponsoredBadge=null;errorOverlay=null;onItemDoubleTapped=null;constructor(){super(),this.root=this.attachShadow({mode:"open"})}get items(){return this.itemsValue}set items(e){if(this.itemsValue=e??[],this.itemsValue.length===0){this.teardown(),this.root.innerHTML="";return}if(!this.mounted){this.isConnected&&this.mount();return}this.renderPages(),this.pool?.updateItems(this.itemsValue)}get config(){return this.cfg}set config(e){if(this.cfg={...Bs,...e},this.cfg.textBandFraction<.15||this.cfg.textBandFraction>.5)throw new Error("textBandFraction must be within 0.15\u20260.5");this.mounted&&this.itemsValue.length>0&&this.remount()}get muted(){return this.mutedValue}set muted(e){this.mutedValue=e,this.pool?.setFeedMuted(e),this.syncSecondaryAudio()}get currentIndex(){return this.intendedPage}connectedCallback(){!this.mounted&&this.itemsValue.length>0&&this.mount()}disconnectedCallback(){this.teardown()}mount(){this.teardown(),this.mounted=!0;let e=this.cfg,t=e.textFontFamily??"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";this.root.innerHTML=`<style>
292
+ `}buildButtons(){let e=this.q(".buttons");e.innerHTML="";let t=(n,a,o)=>{let l=document.createElement("button");return l.className=`bbtn b-${n}`,l.dataset.testid=am[n]??`og_btn_${n}`,l.innerHTML=this.glyph(a,this.dimE.iconSize),l.addEventListener("click",d=>{d.stopPropagation(),o(),this.armAutoHide()}),e.appendChild(l),l};this.cfg.showVolumeButton&&t("volume","volumeOn",()=>this.toggleMenu("volume")),this.cfg.showSpeedButton&&t("speed","speed",()=>this.toggleMenu("speed")),this.cfg.showQualityButton&&t("quality","quality",()=>this.toggleMenu("quality")),this.cfg.showAudioTrackButton&&t("audio","audioTrack",()=>this.toggleMenu("audio")),this.cfg.showSubtitleButton&&t("subs","subtitles",()=>this.toggleMenu("subs")),this.cfg.showFullscreenButton&&t("fs","fullscreenEnter",()=>this.toggleFullscreen());let i=this.q(".seekback"),s=this.q(".seekfwd");i.hidden=s.hidden=!this.cfg.showSeekButtons,this.q(".seekback .seeknum").textContent=String(Math.round((this.playerRef?.seekBackwardIncrementMs??1e4)/1e3)),this.q(".seekfwd .seeknum").textContent=String(Math.round((this.playerRef?.seekForwardIncrementMs??1e4)/1e3)),this.q(".scrub").hidden=!this.cfg.showProgressBar,this.q(".time").hidden=!this.cfg.showTimeLabels}buildTopEnd(){let e=this.q(".topend");e.innerHTML="",this.cfg.customActions.slice(0,8).forEach((t,i)=>{let s=document.createElement("button");s.className="abtn",s.dataset.testid=`og_custom_action_${i}`,s.setAttribute("aria-label",t.accessibilityLabel??`Custom action ${i+1}`),s.innerHTML=t.svg;let n=s.querySelector("svg");n&&(n.style.color=this.col.foreground,n.setAttribute("fill","currentColor")),s.addEventListener("click",a=>{a.stopPropagation(),t.onClick(),this.armAutoHide()}),e.appendChild(s)})}toggleMenu(e){if(this.openMenu===e){this.closeMenu();return}this.openMenu=e;let t=this.q(".menu");t.hidden=!1,t.classList.toggle("narrow",e==="volume"),t.innerHTML="";let i=this.playerRef,s=this.col,n=(a,o,l,d)=>{let c=document.createElement("div");c.className="mitem",c.dataset.testid="og_menu_item";let h=document.createElement("span");h.className="mcheck",h.innerHTML=o?Ot("check",18,s.adAccent):"";let u=document.createElement("span");if(u.textContent=a,c.append(h,u),l){let f=document.createElement("span");f.className="msub",f.textContent=l,c.appendChild(f)}c.addEventListener("click",f=>{f.stopPropagation(),d(),this.closeMenu(),this.armAutoHide()}),t.appendChild(c)};if(e==="volume"){let a=document.createElement("div");a.className="mitem vol";let o=()=>this.glyph(i.isMuted||i.volume===0?"volumeMute":"volumeOn",22);a.innerHTML=`<button class="mmute" data-testid="og_btn_mute" aria-label="Mute">${o()}</button>
293
+ <input type="range" data-testid="og_volume_slider" min="0" max="100" value="${i.isMuted?0:Math.round(i.volume*100)}">`;let l=a.querySelector("input"),d=a.querySelector(".mmute"),c=()=>{d.innerHTML=o(),this.syncButtons()};l.addEventListener("input",()=>{i.volume=Number(l.value)/100,i.isMuted&&Number(l.value)>0&&(i.isMuted=!1),c()}),l.addEventListener("click",h=>h.stopPropagation()),d.addEventListener("click",h=>{h.stopPropagation(),i.isMuted=!i.isMuted,l.value=String(i.isMuted?0:Math.round(i.volume*100)),c()}),t.appendChild(a)}else if(e==="speed")hm.forEach(a=>n(a===1?"Normal":`${a}\xD7`,i.playbackSpeed===a,null,()=>{i.playbackSpeed=a}));else if(e==="quality"){let a=i.videoQualities;a.length===0&&n("Auto",!0,"adaptive",()=>{}),a.forEach(o=>n(o.id==="auto"?"Auto":`${o.height}p`,o.isSelected,o.id==="auto"?"adaptive":`${Math.round(o.bitrate/1e3)} kbps`,()=>i.selectVideoQuality(o.id)))}else if(e==="audio")i.audioTracks.forEach(a=>n(a.label,a.isSelected,a.language||null,()=>i.selectAudioTrack(a.id))),i.audioTracks.length===0&&n("Default",!0,null,()=>{});else if(e==="subs"){let a=i.textTracks;n("Off",!a.some(o=>o.isSelected),null,()=>i.selectTextTrack(null)),a.forEach(o=>n(o.label,o.isSelected,o.language||null,()=>i.selectTextTrack(o.id)))}}closeMenu(){this.openMenu=null,this.q(".menu").hidden=!0}bind(){let e=this.playerRef,t=this.q(".stage"),i=u=>{if(!u.target.closest(".cbtn,.bbtn,.abtn,.menu,.scrub,.livechip")){if(this.openMenu){this.closeMenu();return}this.controlsVisible?(this.hidePoint={x:u.clientX,y:u.clientY},this.hideControls()):this.showControls()}};t.addEventListener("click",i),t.addEventListener("pointermove",u=>{if(u.pointerType==="mouse"){if(this.controlsVisible){this.armAutoHide();return}this.hidePoint&&Math.hypot(u.clientX-this.hidePoint.x,u.clientY-this.hidePoint.y)<8||this.showControls()}}),this.cfg.doubleClickToSeek&&t.addEventListener("dblclick",u=>{if(u.target.closest(".cbtn,.bbtn,.abtn,.menu,.scrub"))return;let f=t.getBoundingClientRect();u.clientX-f.left<f.width/2?e.seekBackward():e.seekForward()}),this.q(".playpause").addEventListener("click",u=>{u.stopPropagation(),e.isPlaying?e.pause():e.play(),this.armAutoHide()}),this.q(".seekback").addEventListener("click",u=>{u.stopPropagation(),e.seekBackward(),this.armAutoHide()}),this.q(".seekfwd").addEventListener("click",u=>{u.stopPropagation(),e.seekForward(),this.armAutoHide()}),this.q(".livechip").addEventListener("click",u=>{u.stopPropagation(),e.seekToLiveEdge(),this.armAutoHide()}),this.q(".adtransport").addEventListener("click",u=>{u.stopPropagation(),e.adPaused?e.play():e.pause()}),this.q(".upnext").addEventListener("click",u=>{u.stopPropagation(),e.skipToNext()}),this.bindScrub();let s={onStateChanged:u=>this.onState(u),onIsPlayingChanged:u=>{this.syncButtons(),this.armAutoHide(),u&&this.maybeShowOnceOverlays()},onError:u=>{let f=this.q(".errorovl");if(f.hidden=!1,f.dataset.gen=String(e.currentLoadGeneration),this.lastSeenGeneration=e.currentLoadGeneration,f.textContent="",this.cfg.renderErrorOverlay)f.classList.add("hostovl"),f.appendChild(this.cfg.renderErrorOverlay(u,()=>e.retry()));else{f.classList.remove("hostovl");let g=document.createElement("span");if(g.textContent=this.cfg.errorMessageProvider?.(u)??`Playback error ${u.code}`,this.cfg.errorTextStyle&&(g.style.cssText+=";"+this.cfg.errorTextStyle),f.appendChild(g),this.cfg.showRetryButton){let m=document.createElement("button");m.className="retry",m.dataset.testid="og_btn_error_retry",m.textContent=this.cfg.retryButtonLabel,this.cfg.retryButtonStyle&&(m.style.cssText+=";"+this.cfg.retryButtonStyle),m.addEventListener("click",p=>{p.stopPropagation(),e.retry()}),f.appendChild(m)}}this.q(".buffering").hidden=!0,this.bufferingTimer!==null&&(clearTimeout(this.bufferingTimer),this.bufferingTimer=null),this.errored=!0,this.hideControls()},onProgress:()=>{this.syncProgress(),this.syncUpNext()}};e.addListener(s),this.detachFns.push(()=>e.removeListener(s));let n=document.fullscreenElement===this,a=()=>{let u=document.fullscreenElement===this,f=u?this.dimF:this.dimE;this.q(".stage").classList.toggle("fs",u),this.style.setProperty("--edge",`${f.edgeInset}px`),this.style.setProperty("--rowh",`${f.bottomBarHeight}px`),this.style.setProperty("--rowpad",u?"8px":"4px");let g=this.q(".b-fs");g&&(g.innerHTML=this.glyph(u?"fullscreenExit":"fullscreenEnter",this.dimE.iconSize)),u!==n&&(n=u,e.emitViewAnalytics({type:"FullscreenChanged",isFullscreen:u}))};document.addEventListener("fullscreenchange",a),this.detachFns.push(()=>document.removeEventListener("fullscreenchange",a));let o=matchMedia("(orientation: portrait)"),l=()=>e.emitViewAnalytics({type:"OrientationChanged",orientation:o.matches?"PORTRAIT":"LANDSCAPE"});l(),o.addEventListener("change",l),this.detachFns.push(()=>o.removeEventListener("change",l));let d=new ResizeObserver(()=>{this.applyCueSize(),this.playerRef?.notifyAdViewResize(this.clientWidth,this.clientHeight,document.fullscreenElement===this)});d.observe(this),this.detachFns.push(()=>d.disconnect()),e.onLicenseChanged(()=>this.syncWatermark());let c={onAdError:u=>{if(u.code!==902||this.cfg.adBlockerPolicy==="none")return;let f=this.q(".adblocknotice");f.dataset.gen=String(e.currentLoadGeneration),f.hidden=!1;let g=this.cfg.adBlockerPolicy==="block";f.classList.toggle("hard",g),this.q(".abclose").textContent=g?"I disabled it \u2014 reload":"Got it",this.q(".abtext").textContent=g?"This video is only available with ads. Please disable your ad blocker for this site, then reload.":"This video is made available with ads, but your ad blocker prevented them from loading. Your video plays on without ads \u2014 please consider allowing ads for this site to support it.",g&&(this.q(".stage").classList.add("adblocked"),e.holdPlayback=!0,e.pause())}};e.addAdListener(c),this.detachFns.push(()=>e.removeAdListener(c)),this.q(".abclose").addEventListener("click",u=>{if(u.stopPropagation(),this.q(".adblocknotice").classList.contains("hard")){location.reload();return}this.q(".adblocknotice").hidden=!0});let h=window.setInterval(()=>this.syncPeriodic(),500);this.detachFns.push(()=>clearInterval(h))}bindScrub(){let e=this.playerRef,t=this.q(".scrub"),i=n=>{let a=t.getBoundingClientRect();return Math.min(1,Math.max(0,(n.clientX-a.left)/a.width))},s=()=>{let n=e.videoElement.seekable;return e.liveInfo&&n.length>0?[n.start(0)*1e3,n.end(n.length-1)*1e3]:[0,e.durationMs]};t.addEventListener("pointerdown",n=>{this.scrubbing=!0,t.classList.add("active"),t.setPointerCapture(n.pointerId),this.paintScrub(i(n)),this.showThumbPreview(i(n),s()),this.cancelAutoHide()}),t.addEventListener("pointermove",n=>{let a=i(n);this.scrubbing&&this.paintScrub(a),(this.scrubbing||n.pointerType==="mouse")&&this.showThumbPreview(a,s())}),t.addEventListener("pointerleave",()=>{this.scrubbing||this.hideThumbPreview()}),t.addEventListener("pointerup",n=>{if(!this.scrubbing)return;this.scrubbing=!1,t.classList.remove("active"),this.hideThumbPreview();let[a,o]=s();e.seekTo(a+i(n)*(o-a)),this.armAutoHide()})}thumbPreviewSeq=0;showThumbPreview(e,[t,i]){let s=this.playerRef,n=this.q(".thumbpreview"),a=t+e*(i-t);if(!s.hasThumbnails){if(!this.scrubbing){n.hidden=!0;return}n.hidden=!1,this.q(".tpimg").style.cssText="display:none",this.q(".tptime").textContent=Ii(a),this.placeThumbPreview(e);return}n.hidden=!1,this.placeThumbPreview(e),this.q(".tptime").textContent=Ii(a);let o=++this.thumbPreviewSeq;s.getThumbnail(a).then(l=>{if(o!==this.thumbPreviewSeq||!l)return;let d=this.q(".tpimg"),c=this.q(".tpframe");if(l.width>0){let h=Math.min(1,168/l.width);d.style.cssText=`display:block;width:${l.width*h}px;height:${l.height*h}px;`,c.style.cssText=`width:${l.width}px;height:${l.height}px;background-image:url("${l.url}");background-position:${-l.x}px ${-l.y}px;transform:scale(${h});`}else d.style.cssText="display:block;width:168px;height:94px;",c.style.cssText=`width:168px;height:94px;background-image:url("${l.url}");background-size:cover;background-position:center;`;this.placeThumbPreview(e)})}placeThumbPreview(e){let t=this.q(".thumbpreview").offsetWidth/2;this.q(".thumbpreview").style.left=t>0?`clamp(${t}px, ${e*100}%, calc(100% - ${t}px))`:`${e*100}%`}hideThumbPreview(){this.q(".thumbpreview").hidden=!0}paintScrub(e){this.q(".played").style.width=`${e*100}%`,this.q(".thumb").style.left=`${e*100}%`}onState(e){e==="BUFFERING"&&(this.q(".errorovl").hidden=!0,this.errored=!1);let t=this.q(".buffering"),i=this.q(".ring");e==="BUFFERING"?(t.hidden=!1,i.hidden=!0,this.bufferingTimer===null&&(this.bufferingTimer=window.setTimeout(()=>{i.hidden=!1},250))):(t.hidden=!0,this.bufferingTimer!==null&&(clearTimeout(this.bufferingTimer),this.bufferingTimer=null)),this.q(".endeddim").hidden=e!=="ENDED",this.syncButtons()}maybeShowOnceOverlays(){let e=this.playerRef,t=e.currentLoadGeneration,i=e.currentItem;if(!i)return;if(t!==this.lastOverlayGeneration){this.lastOverlayGeneration=t,this.overlayTimers.forEach(a=>clearTimeout(a)),this.overlayTimers=[],this.setRatingRow(!1);let n=this.q(".title");n.hidden=!0,n.style.top="12px",this.q(".ratings").hidden=!0}if(this.cfg.showTitle&&i.title&&this.titleShownGeneration!==t){this.titleShownGeneration=t;let n=this.q(".title");n.textContent=i.title,n.hidden=!1,n.style.opacity="1",this.overlayTimers.push(window.setTimeout(()=>{n.style.opacity="0"},this.cfg.titleTimeoutMs)),this.overlayTimers.push(window.setTimeout(()=>{n.hidden=!0},this.cfg.titleTimeoutMs+700))}let s=i.contentRatings??[];if(this.cfg.showContentRatings&&s.length>0&&this.ratingsShownGeneration!==t){this.ratingsShownGeneration=t;let n=this.q(".ratings");n.innerHTML="";for(let o of s)n.appendChild(this.ratingNode(o));n.hidden=!1,n.style.opacity="1",this.setRatingRow(!0),this.overlayTimers.push(window.setTimeout(()=>{n.style.opacity="0",this.setRatingRow(!1)},this.cfg.contentRatingsTimeoutMs)),this.overlayTimers.push(window.setTimeout(()=>{n.hidden=!0},this.cfg.contentRatingsTimeoutMs+700));let a=this.q(".title");a.style.top="53px",this.overlayTimers.push(window.setTimeout(()=>{a.style.top="12px"},this.cfg.contentRatingsTimeoutMs))}}ratingNode(e){if("age"in e){let i=document.createElement("span");return i.className="age",i.style.background=dm[e.age]??"",i.textContent=lm[e.age]??"",i}if("descriptor"in e){let i=document.createElement("span");return i.className="desc",i.innerHTML=`<svg viewBox="0 0 24 24" width="16" height="16">${cm[e.descriptor]??""}</svg>`,i}let t=document.createElement("img");return t.src=e.customIconUrl,t.alt="",t}setRatingRow(e){this.ratingRowVisible=e,this.q(".topend").style.paddingTop=e?"48px":"8px",this.applyOverlayInsets()}applyOverlayInsets(){let e=this.controlsVisible&&this.ratingRowVisible,t=this.controlsVisible||this.ratingRowVisible,s=Math.min(e?104:t?64:0,this.clientHeight*.5),n=this.controlsVisible?Math.min(68,this.clientHeight*.3):0,a=this.q(".overlays");a.style.top=`${s}px`,a.style.bottom=`${n}px`,this.q(".watermark").style.transform=`translateX(-50%) translateY(${this.ratingRowVisible?43:0}px)`}showControls(){this.errored||(this.hidePoint=null,this.controlsVisible=!0,this.q(".chrome").hidden=!1,this.applyOverlayInsets(),this.armAutoHide())}hideControls(){this.controlsVisible=!1,this.q(".chrome").hidden=!0,this.closeMenu(),this.applyOverlayInsets()}armAutoHide(){this.cancelAutoHide(),this.playerRef?.isPlaying&&(this.hideTimer=window.setTimeout(()=>{this.openMenu===null&&!this.scrubbing?this.hideControls():this.armAutoHide()},this.cfg.controlsTimeoutMs))}cancelAutoHide(){this.hideTimer!==null&&(clearTimeout(this.hideTimer),this.hideTimer=null)}syncAll(){this.syncButtons(),this.syncProgress(),this.syncWatermark(),this.applyCueSize(),this.applyOverlayInsets()}syncButtons(){let e=this.playerRef,t=this.q(".playpause"),i=e.state==="ENDED"?"replay":e.isPlaying?"pause":"play";t.innerHTML=this.glyph(i,44),t.setAttribute("aria-label",i==="pause"?"Pause":"Play");let s=this.q(".b-volume");s&&(s.innerHTML=this.glyph(e.isMuted||e.volume===0?"volumeMute":"volumeOn",this.dimE.iconSize))}syncUpNext(){let e=this.playerRef,t=this.q(".upnext"),i=e.nextPlaylistItem,s=e.durationMs;if(!this.cfg.showUpNext||this.errored||e.isPlayingAd||!i||s<=0){t.hidden=!0;return}let n=s-e.currentPositionMs,a=Math.min(60,Math.max(1,this.cfg.upNextLeadSeconds))*1e3;if(n<=0||n>a){t.hidden=!0;return}t.textContent=this.cfg.upNextText.replace("{seconds}",String(Math.ceil(n/1e3))).replace("{title}",i.title??""),t.hidden=!1}syncProgress(){if(this.scrubbing)return;let e=this.playerRef,t=e.liveInfo,i=this.q(".time");if(t){let s=e.videoElement.seekable;if(s.length>0){let a=s.start(0),o=s.end(s.length-1),l=o>a?(e.videoElement.currentTime-a)/(o-a):1;this.paintScrub(Math.min(1,Math.max(0,l))),this.q(".buffered").style.width="0"}let n=t.latencyMs>12e3?` \u2212${Ii(t.latencyMs)}`:"";i.innerHTML=t.atLiveEdge?"":`<b>${n}</b>`}else{let s=e.durationMs,n=s>0?e.currentPositionMs/s:0;this.paintScrub(Math.min(1,n)),this.q(".buffered").style.width=`${s>0?Math.min(100,e.bufferedPositionMs/s*100):0}%`,i.innerHTML=`<b>${Ii(e.currentPositionMs)}</b> / ${Ii(s)}`,this.paintAdCues(s)}}paintAdCues(e){let t=this.playerRef,i=e>0&&this.cfg.showAdCueMarkers?t.adCuePoints.map(a=>a<0?1:Math.min(1,a*1e3/e)):[],s=i.map(a=>a.toFixed(3)).join(",");if(s===this.lastAdCueKey)return;this.lastAdCueKey=s;let n=this.q(".track");n.querySelectorAll(".cue").forEach(a=>a.remove());for(let a of i){let o=document.createElement("div");o.className="cue",o.style.left=`${a*100}%`,n.appendChild(o)}}syncPeriodic(){let e=this.playerRef;if(e.currentLoadGeneration!==this.lastSeenGeneration){this.lastSeenGeneration=e.currentLoadGeneration,this.q(".errorovl").hidden=!0,this.errored=!1;let c=this.q(".adblocknotice");c.dataset.gen!==String(e.currentLoadGeneration)&&(c.hidden=!0,this.q(".stage").classList.contains("adblocked")&&(this.q(".stage").classList.remove("adblocked"),e.holdPlayback=!1))}this.q(".stage").classList.contains("adblocked")&&e.isPlaying&&e.pause(),this.syncAdUi();let t=`${e.subtitleTextScale}|${e.subtitleStyle.textSizeFraction}|${e.subtitleStyle.foregroundColor}|${e.subtitleStyle.backgroundColor}|${e.subtitleStyle.edgeType}|${e.subtitleStyle.edgeColor}|${e.subtitleStyle.fontFamily}`;t!==this.lastCueKey&&(this.lastCueKey=t,this.applyCueSize());let i=e.liveInfo,s=this.q(".livechip");s.hidden=!i,i&&s.classList.toggle("behind",!i.atLiveEdge);let n=e.currentItem?.streamType??"VOD",a=n!=="LIVE",o=n!=="VOD";this.q(".scrub").hidden=!this.cfg.showProgressBar||!a,this.q(".time").hidden=!this.cfg.showTimeLabels||!a;let l=!this.cfg.showSeekButtons||!a;this.q(".seekback").hidden=l,this.q(".seekfwd").hidden=l;let d=this.root.querySelector(".b-speed");d&&(d.hidden=o||!this.cfg.showSpeedButton)}syncAdUi(){let e=this.playerRef,t=this.q(".stage");t.classList.toggle("adplaying",e.isPlayingAd),t.classList.toggle("adspending",e.adsPending);let i=this.q(".adchrome"),s=this.q(".adtransport"),n=e.adProgress;if(e.isPlayingAd&&n){i.hidden=!1,s.hidden=!1;let a=n.durationMs>0?Math.min(1,n.positionMs/n.durationMs):0;this.q(".adfill").style.width=`${a*100}%`,this.q(".adpod").textContent=n.adCount>1?`${n.adIndex}/${n.adCount}`:"";let o=Math.max(0,Math.ceil((n.durationMs-n.positionMs)/1e3));this.q(".adtime").textContent=`${Math.floor(o/60)}:${String(o%60).padStart(2,"0")}`,s.innerHTML=e.adPaused?this.cfg.adPlayIconSvg??Ot("play",34,this.col.foreground):this.cfg.adPauseIconSvg??Ot("pause",34,this.col.foreground),s.setAttribute("aria-label",e.adPaused?"Resume ad":"Pause ad")}else i.hidden=!0,s.hidden=!e.isPlayingAd,e.isPlayingAd&&(s.innerHTML=e.adPaused?this.cfg.adPlayIconSvg??Ot("play",34,this.col.foreground):this.cfg.adPauseIconSvg??Ot("pause",34,this.col.foreground))}syncWatermark(){this.q(".watermark").hidden=this.playerRef?.isLicensed??!1}applyCueSize(){let e=this.playerRef;if(!e)return;let t=this.clientHeight||0,i=Math.max(13,Math.min(t*e.subtitleStyle.textSizeFraction,44))*e.subtitleTextScale,s=e.subtitleStyle,n=s.edgeColor,a=s.edgeType==="OUTLINE"?`text-shadow:-1px -1px 0 ${n},1px -1px 0 ${n},-1px 1px 0 ${n},1px 1px 0 ${n};`:s.edgeType==="DROP_SHADOW"?`text-shadow:2px 2px 3px ${n};`:s.edgeType==="RAISED"?`text-shadow:0 -1px 0 ${n};`:s.edgeType==="DEPRESSED"?`text-shadow:0 1px 0 ${n};`:"",o=s.fontFamily?`font-family:${s.fontFamily};`:"";this.q(".cuestyle").textContent=`video::cue { background:${s.backgroundColor}; color:${s.foregroundColor}; font-size:${i.toFixed(1)}px; ${a}${o} }`}enterNativeVideoFullscreen(){let e=this.playerRef?.videoElement;return e?.webkitEnterFullscreen?(e.webkitEnterFullscreen(),!0):!1}enterFullscreen(){return typeof this.requestFullscreen=="function"?this.requestFullscreen():(this.enterNativeVideoFullscreen(),Promise.resolve())}exitFullscreen(){document.fullscreenElement===this&&document.exitFullscreen();let e=this.playerRef?.videoElement;e?.webkitDisplayingFullscreen&&e.webkitExitFullscreen?.()}toggleFullscreen(){document.fullscreenElement===this?this.cfg.onFullscreenExitRequest?this.cfg.onFullscreenExitRequest():document.exitFullscreen():typeof this.requestFullscreen=="function"?this.requestFullscreen():this.enterNativeVideoFullscreen()}detach(){this.detachFns.forEach(i=>i()),this.detachFns=[];let e=this.root.querySelector(".videohost"),t=this.playerRef?.videoElement;e&&t&&t.parentElement===e&&e.removeChild(t),this.overlayTimers.forEach(i=>clearTimeout(i)),this.overlayTimers=[],this.cancelAutoHide(),this.bufferingTimer!==null&&(clearTimeout(this.bufferingTimer),this.bufferingTimer=null)}};function pa(){customElements.get("og-player")||customElements.define("og-player",$s)}var Us={preloadAhead:1,keepBehind:1,loopItems:!0,contentFit:"FILL",showTitle:!1,showSubtitle:!1,showProgressBar:!0,showSponsoredBadge:!0,progressBarThickness:2,progressBarColor:"#FFFFFF",progressBarTrackColor:"rgba(255,255,255,0.25)",playIconSvg:null,textFontFamily:null,titleTextSize:16,subtitleTextSize:13,textBandColor:"transparent",textBandFraction:1/3,textBandTopMargin:16,paginationThreshold:2,maxItemDurationSeconds:0,licenseKey:null,errorMessageProvider:null},Li=class{constructor(e,t){this.config=e;this.callbacks=t;this.capacity=Math.min(3,e.preloadAhead+e.keepBehind+1)}items=[];entries=[];capacity;activeIndexValue=-1;released=!1;feedMuted=!1;skippedItems=new Set;licensedValue=null;get activeIndex(){return this.activeIndexValue}get isLicensed(){return this.licensedValue}get skippedIndices(){let e=new Set;return this.items.forEach((t,i)=>{this.skippedItems.has(t)&&e.add(i)}),e}isSkipped(e){let t=this.items[e];return t!==void 0&&this.skippedItems.has(t)}updateItems(e){this.items=e,this.activeIndexValue>=0&&this.settle(Math.min(this.activeIndexValue,e.length-1))}playerAt(e){return this.isSkipped(e)?null:this.entries.find(t=>t.index===e)?.player??null}setFeedMuted(e){this.feedMuted=e;let t=this.entries.find(i=>i.index===this.activeIndexValue);t&&(t.player.isMuted=this.primaryMuted(t.index))}settle(e){if(this.released||e<0||e>=this.items.length)return;let t=e-this.config.keepBehind,i=e+this.config.preloadAhead,s=this.activeIndexValue;if(e!==s){let o=this.entries.find(l=>l.index===s);o&&this.emitWatched(o),this.callbacks.onAnalyticsEvent?.({type:"VerticalFeedImpression",index:e,url:this.items[e].media.url})}this.activeIndexValue=e;let n=this.entryFor(e);if(n){let o=this.items[e];n.player.setBufferRole("ACTIVE"),n.player.setLooping(this.config.loopItems&&!o.isSponsored),n.player.isMuted=this.primaryMuted(e),o.secondaryMedia||n.player.play()}if(s!==e){let o=this.entries.find(l=>l.index===s);o&&s>=t&&s<=i&&this.demote(o)}for(let o of this.entries)o.index!==-1&&(o.index<t||o.index>i)&&this.recycle(o);for(let o of this.windowOrder(e,t,i))o>=0&&o<this.items.length&&!this.isSkipped(o)&&!this.entries.some(l=>l.index===o)&&this.entryFor(o);this.callbacks.onAssignmentsChanged?.(),this.callbacks.onActiveItemChanged?.(e);let a=this.items.length-1-e;a<=this.config.paginationThreshold&&this.callbacks.onNearEnd?.(a)}releaseAll(){if(this.released)return;let e=this.entries.find(t=>t.index===this.activeIndexValue);e&&this.emitWatched(e),this.released=!0;for(let t of this.entries)t.detach(),t.player.release();this.entries=[],this.skippedItems.clear()}primaryMuted(e){let t=this.items[e];return t?.secondaryMedia&&(t.splitAudioSource??"PRIMARY")==="SECONDARY"?!0:this.feedMuted}windowOrder(e,t,i){let s=[];for(let n=1;n<=Math.max(e-t,i-e);n++)e+n<=i&&s.push(e+n),e-n>=t&&s.push(e-n);return s}entryFor(e){if(e<0||e>=this.items.length||this.isSkipped(e))return null;let t=this.entries.find(a=>a.index===e);if(t)return t;let i=this.entries.find(a=>a.index===-1)??this.createEntry();if(!i)return null;i.index=e,i.loopCount=0,i.watchTimeMs=0,i.lastPositionMs=0,i.durationChecked=!1;let s=this.items[e],n=e!==this.activeIndexValue;return i.player.setBufferRole(n?"STANDBY":"ACTIVE"),i.player.isMuted=n?!0:this.primaryMuted(e),i.player.setLooping(this.config.loopItems&&!s.isSponsored),i.player.load(s.media,{autoplay:!1}),i}createEntry(){if(this.entries.length>=this.capacity)return null;let e=new Mt({...this.config.licenseKey?{licenseKey:this.config.licenseKey}:{},fallbackToMutedAutoplay:!0});e.onLicenseChanged(n=>{this.licensedValue=n,this.callbacks.onAssignmentsChanged?.()});let t={player:e,index:-1,loopCount:0,watchTimeMs:0,lastPositionMs:0,durationChecked:!1,detach:()=>{}},i={onProgress:n=>{if(this.released||t.index!==this.activeIndexValue)return;let a=n-t.lastPositionMs;a>0&&a<=1e3&&(t.watchTimeMs+=a),a<-2e3&&t.player.isLooping&&(t.loopCount++,this.callbacks.onAnalyticsEvent?.({type:"VerticalFeedItemLooped",index:t.index,loopCount:t.loopCount})),t.lastPositionMs=n},onPlaybackCompleted:()=>{if(this.released||t.index<0)return;this.items[t.index]?.isSponsored&&t.index===this.activeIndexValue&&this.callbacks.onAdvanceRequested?.(t.index)},onError:n=>{this.released||t.index<0||(this.callbacks.onItemError?.(t.index,n),this.callbacks.onAnalyticsEvent?.({type:"Error",error:n}))}};e.addListener(i),e.addAnalyticsListener(n=>{n.type==="MutedAutoplayFallback"&&t.index===this.activeIndexValue&&this.callbacks.onAnalyticsEvent?.(n)});let s=()=>{if(this.released||t.durationChecked||t.index<0)return;t.durationChecked=!0;let n=this.config.maxItemDurationSeconds;if(n>0&&e.durationMs>n*1e3){let a=t.index,o=this.items[a];o&&this.skippedItems.add(o),this.recycle(t),this.callbacks.onItemSkipped?.(a,"durationExceeded"),this.callbacks.onAssignmentsChanged?.()}};return e.videoElement.addEventListener("loadedmetadata",s),t.detach=()=>{e.removeListener(i),e.videoElement.removeEventListener("loadedmetadata",s)},this.entries.push(t),t}demote(e){e.player.pause(),e.player.isMuted=!0,e.player.setBufferRole("STANDBY"),e.player.seekTo(0)}recycle(e){e.index===this.activeIndexValue&&this.emitWatched(e),e.player.pause(),e.index=-1,e.player.videoElement.removeAttribute("src"),e.player.videoElement.load()}emitWatched(e){if(e.index<0||e.watchTimeMs<=0)return;let t=this.items[e.index];t&&(this.callbacks.onAnalyticsEvent?.({type:"VerticalFeedItemWatched",index:e.index,url:t.media.url,watchTimeMs:Math.round(e.watchTimeMs),loopCount:e.loopCount}),e.watchTimeMs=0)}};var Gs=class extends HTMLElement{root;pool=null;itemsValue=[];cfg={...Us};mutedValue=!1;intendedPage=0;observer=null;resizeObserver=null;tickTimer=null;itemErrors=new Map;secondary=null;secondaryFor=-1;secondaryDetach=null;singleTapTimer=null;scrubbing=!1;mounted=!1;sponsoredBadge=null;errorOverlay=null;onItemDoubleTapped=null;constructor(){super(),this.root=this.attachShadow({mode:"open"})}get items(){return this.itemsValue}set items(e){if(this.itemsValue=e??[],this.itemsValue.length===0){this.teardown(),this.root.innerHTML="";return}if(!this.mounted){this.isConnected&&this.mount();return}this.renderPages(),this.pool?.updateItems(this.itemsValue)}get config(){return this.cfg}set config(e){if(this.cfg={...Us,...e},this.cfg.textBandFraction<.15||this.cfg.textBandFraction>.5)throw new Error("textBandFraction must be within 0.15\u20260.5");this.mounted&&this.itemsValue.length>0&&this.remount()}get muted(){return this.mutedValue}set muted(e){this.mutedValue=e,this.pool?.setFeedMuted(e),this.syncSecondaryAudio()}get currentIndex(){return this.intendedPage}connectedCallback(){!this.mounted&&this.itemsValue.length>0&&this.mount()}disconnectedCallback(){this.teardown()}mount(){this.teardown(),this.mounted=!0;let e=this.cfg,t=e.textFontFamily??"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";this.root.innerHTML=`<style>
295
294
  :host { display:block; position:relative; background:#000; overflow:hidden;
296
295
  width:100%; height:100%; }
297
296
  * { box-sizing:border-box; margin:0; }
@@ -370,4 +369,4 @@ Schedule: ${l.map(m=>Ue(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Remo
370
369
  font:600 13px ${t}; pointer-events:none; z-index:6; }
371
370
  </style>
372
371
  <div class="feed" part="feed" data-testid="og_feed"></div>
373
- <div class="watermark" hidden>${Os(20,"rgba(255,255,255,0.72)","#F6C445")}<span><b>OG</b>Player</span></div>`,this.pool=new Li(this.cfg,{onActiveItemChanged:s=>{let n=this.itemsValue[s];n&&this.dispatch("og-activeitemchanged",{index:s,item:n})},onNearEnd:s=>this.dispatch("og-nearend",{remaining:s}),onItemSkipped:(s,n)=>{this.dispatch("og-itemskipped",{index:s,reason:n}),s===this.intendedPage&&this.scrollToPage(s+1)},onItemError:(s,n)=>{this.itemErrors.set(s,n),this.dispatch("og-itemerror",{index:s,error:n}),this.renderActiveChrome()},onAnalyticsEvent:s=>{s.type==="MutedAutoplayFallback"&&(this.mutedValue=!0,this.dispatch("og-mutedfallback",{})),this.dispatch("og-analytics",{event:s})},onAssignmentsChanged:()=>{this.attachSurfaces(),this.syncWatermark()},onAdvanceRequested:s=>this.scrollToPage(s+1)}),this.pool.setFeedMuted(this.mutedValue),this.renderPages(),this.pool.updateItems(this.itemsValue);let i=this.q(".feed");this.observer=new IntersectionObserver(s=>{for(let n of s)if(n.intersectionRatio>=.6){let a=Number(n.target.dataset.index);a!==this.intendedPage&&(this.intendedPage=a,this.settle(a))}},{root:i,threshold:[.6]});for(let s of Array.from(i.children))this.observer.observe(s);this.resizeObserver=new ResizeObserver(()=>{i.scrollTop=this.intendedPage*i.clientHeight}),this.resizeObserver.observe(this),this.tickTimer=window.setInterval(()=>this.tick(),250),this.itemsValue.length>0&&this.settle(0)}remount(){let e=this.intendedPage;this.mount(),e>0&&this.scrollToPage(e,"instant")}teardown(){this.mounted=!1,this.observer?.disconnect(),this.observer=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.tickTimer!==null&&(clearInterval(this.tickTimer),this.tickTimer=null),this.singleTapTimer!==null&&(clearTimeout(this.singleTapTimer),this.singleTapTimer=null),this.releaseSecondary(),this.pool?.releaseAll(),this.pool=null,this.itemErrors.clear(),this.intendedPage=0}banded(e){return(e.textPlacement??"OVERLAY")!=="OVERLAY"&&(this.cfg.showTitle&&!!e.title||this.cfg.showSubtitle&&!!e.subtitle)}renderPages(){let e=this.q(".feed"),t=e.children.length;if(e.textContent="",this.itemsValue.forEach((i,s)=>{let n=document.createElement("section");n.className="page",n.dataset.index=String(s),n.dataset.testid=`og_feed_page_${s}`;let a=i.contentFit??this.cfg.contentFit;if(this.banded(i)){let o=document.createElement("div");if(o.className="band",(i.textPlacement??"OVERLAY")==="ABOVE_VIDEO"&&o.classList.add("top"),this.cfg.showTitle&&i.title){let d=document.createElement("div");d.className="t",d.textContent=i.title,o.appendChild(d)}if(this.cfg.showSubtitle&&i.subtitle){let d=document.createElement("div");d.className="s",d.textContent=i.subtitle,o.appendChild(d)}let l=this.makeRegion(i,a);(i.textPlacement??"OVERLAY")==="ABOVE_VIDEO"?n.append(o,l):n.append(l,o)}else if(i.secondaryMedia){let o=this.makeRegion(i,a);o.classList.add("half");let l=document.createElement("div");l.className="half secondhalf fit-"+a;let d=document.createElement("div");d.className="poster";let c=i.secondaryMedia.posterUrl;c&&(d.style.backgroundImage=`url("${c}")`),l.appendChild(d),n.append(o,l)}else n.appendChild(this.makeRegion(i,a));e.appendChild(n)}),this.observer){this.observer.disconnect();for(let i of Array.from(e.children))this.observer.observe(i)}t>0&&this.intendedPage<e.children.length&&(e.scrollTop=this.intendedPage*e.clientHeight),this.attachSurfaces(),this.renderActiveChrome()}makeRegion(e,t){let i=document.createElement("div");i.className="videoregion fit-"+t;let s=document.createElement("div");s.className="poster";let n=e.posterUrl??e.media.posterUrl;return n&&(s.style.backgroundImage=`url("${n}")`),i.appendChild(s),i}attachSurfaces(){if(!this.pool)return;let e=this.q(".feed");this.itemsValue.forEach((t,i)=>{let s=e.children[i];if(!s)return;let n=s.querySelector(".videoregion");if(!n)return;let a=this.pool.playerAt(i),o=n.querySelector("video");a?o!==a.videoElement&&(o?.remove(),n.appendChild(a.videoElement)):o?.remove()}),this.renderActiveChrome(),this.manageSecondary()}renderActiveChrome(){if(!this.pool)return;let e=this.q(".feed");for(let h of Array.from(this.root.querySelectorAll(".taplayer, .rail, .badge, .centre, .hairline, .hairpad, .overlaytext, .errorlayer")))h.remove();let t=this.intendedPage,i=this.itemsValue[t],s=e.children[t];if(!i||!s)return;let n=this.pool.playerAt(t),a=s.querySelector(".videoregion")??s,o=this.itemErrors.get(t);if(o&&n){let h=()=>{this.itemErrors.delete(t),n.retry(),this.renderActiveChrome()},u=document.createElement("div");if(u.className="errorlayer",this.errorOverlay)u.appendChild(this.errorOverlay(o,h));else{let f=document.createElement("div");f.className="errdefault";let g=document.createElement("div");g.className="m",g.textContent=this.cfg.errorMessageProvider?.(o)??`Playback error ${o.code}`;let m=document.createElement("button");m.textContent="Retry",m.addEventListener("click",h),f.append(g,m),u.appendChild(f)}s.appendChild(u);return}if(!n)return;let l=document.createElement("div");l.className="taplayer",l.addEventListener("click",()=>{let h=()=>{n.isPlaying?n.pause():n.play()};if(this.onItemDoubleTapped){if(this.singleTapTimer!==null)return;this.singleTapTimer=window.setTimeout(()=>{this.singleTapTimer=null,h()},300)}else h()}),l.addEventListener("dblclick",()=>{this.onItemDoubleTapped&&(this.singleTapTimer!==null&&(clearTimeout(this.singleTapTimer),this.singleTapTimer=null),this.onItemDoubleTapped(t,i),this.dispatch("og-itemdoubletapped",{index:t,item:i}))}),a.appendChild(l);let d=document.createElement("div");if(d.className="centre",a.appendChild(d),i.isSponsored){let h=document.createElement("div");if(h.className="badge",h.dataset.testid="og_feed_sponsored_badge",this.sponsoredBadge)h.appendChild(this.sponsoredBadge(i));else if(this.cfg.showSponsoredBadge){let u=document.createElement("span");u.className="chip",u.textContent="Sponsored",h.appendChild(u)}a.appendChild(h)}let c=(i.railActions??[]).slice(0,6);if(c.length>0){let h=!!i.secondaryMedia||(i.textPlacement??"OVERLAY")!=="OVERLAY",u=document.createElement("div");u.className=h?"rail railpage":"rail",u.dataset.testid="og_feed_rail",c.forEach((f,g)=>u.appendChild(this.railButton(f,g))),(h?s:a).appendChild(u)}if((i.textPlacement??"OVERLAY")==="OVERLAY"&&(this.cfg.showTitle&&i.title||this.cfg.showSubtitle&&i.subtitle)){let h=document.createElement("div");if(h.className="overlaytext",this.cfg.showTitle&&i.title){let u=document.createElement("div");u.className="t",u.textContent=i.title,h.appendChild(u)}if(this.cfg.showSubtitle&&i.subtitle){let u=document.createElement("div");u.className="s",u.textContent=i.subtitle,h.appendChild(u)}s.appendChild(h)}if(this.cfg.showProgressBar){let h=document.createElement("div");h.className="hairline",h.dataset.testid="og_feed_hairline";let u=document.createElement("div");u.className="fill",h.appendChild(u);let f=document.createElement("div");f.className="hairpad";let g=p=>{let v=h.getBoundingClientRect();if(v.width<=0||n.durationMs<=0)return;let T=Math.min(1,Math.max(0,(p-v.left)/v.width));u.style.width=`${T*100}%`,n.seekTo(T*n.durationMs)};f.addEventListener("pointerdown",p=>{this.scrubbing=!0,h.classList.add("scrubbing"),f.setPointerCapture(p.pointerId),g(p.clientX)}),f.addEventListener("pointermove",p=>{this.scrubbing&&g(p.clientX)});let m=()=>{this.scrubbing=!1,h.classList.remove("scrubbing")};f.addEventListener("pointerup",m),f.addEventListener("pointercancel",m),s.append(h,f)}this.tick()}railButton(e,t){let i=document.createElement("button");i.dataset.testid=`og_feed_rail_action_${t}`,e.isActive&&(i.className="active"),e.accessibilityLabel&&i.setAttribute("aria-label",e.accessibilityLabel);let s=document.createElement("span");if(s.className="ic",s.innerHTML=e.iconSvg,i.appendChild(s),e.label){let n=document.createElement("span");n.className="lbl",n.textContent=e.label,i.appendChild(n)}return i.addEventListener("click",n=>{n.stopPropagation(),e.onClick()}),i}tick(){if(!this.pool)return;let e=this.intendedPage,t=this.pool.playerAt(e),i=this.root.querySelector(".centre");if(!t||!i)return;let n=!!this.itemsValue[e]?.secondaryMedia&&this.secondaryFor===e&&this.secondary!==null&&this.secondary.state!=="READY"&&!t.isPlaying,a=t.videoElement.played.length>0,o=t.state==="BUFFERING",l=!t.isPlaying&&t.state==="READY"&&!n&&a,d="";l?d="glyph":(o||n)&&(d="spinner");let c=i.dataset.show??"";if(d!==c){if(i.dataset.show=d,i.textContent="",d==="glyph"){let h=document.createElement("div");h.className="glyph",h.innerHTML=this.cfg.playIconSvg??'<svg viewBox="0 0 24 24"><path d="M8 5.5v13l11-6.5z" fill="#fff"/></svg>',i.appendChild(h)}else if(d==="spinner"){let h=document.createElement("div");h.className="spinner",i.appendChild(h)}}if(!this.scrubbing){let h=this.root.querySelector(".hairline .fill");h&&t.durationMs>0&&(h.style.width=`${t.currentPositionMs/t.durationMs*100}%`)}}manageSecondary(){let e=this.intendedPage,t=this.itemsValue[e],i=this.pool?.playerAt(e)??null;if(!t?.secondaryMedia||!i){this.releaseSecondary();return}if(this.secondaryFor===e&&this.secondary)return;this.releaseSecondary();let a=this.q(".feed").children[e]?.querySelector(".secondhalf");if(!a)return;let o=new Mt({...this.cfg.licenseKey?{licenseKey:this.cfg.licenseKey}:{},fallbackToMutedAutoplay:!0});this.secondary=o,this.secondaryFor=e,o.setBufferRole("STANDBY"),o.setLooping(this.cfg.loopItems&&!t.isSponsored),o.isMuted=!0,o.load(t.secondaryMedia,{autoplay:!1}),a.appendChild(o.videoElement);let l=()=>{this.secondary!==o||this.intendedPage!==e||(o.setBufferRole("ACTIVE"),this.syncSecondaryAudio(),i.play(),o.play())},d={onStateChanged:h=>{h==="READY"&&l()}};o.addListener(d);let c={onPause:()=>o.pause(),onResume:()=>o.play(),onPlay:()=>o.play()};i.addListener(c),this.secondaryDetach=()=>{o.removeListener(d),i.removeListener(c)},o.state==="READY"&&l()}syncSecondaryAudio(){let e=this.itemsValue[this.secondaryFor];if(!this.secondary||!e)return;let t=(e.splitAudioSource??"PRIMARY")==="SECONDARY";this.secondary.isMuted=t?this.mutedValue:!0}releaseSecondary(){this.secondaryDetach?.(),this.secondaryDetach=null,this.secondary&&(this.secondary.videoElement.remove(),this.secondary.release()),this.secondary=null,this.secondaryFor=-1}settle(e){this.pool?.settle(e),this.renderActiveChrome(),this.manageSecondary()}scrollToPage(e,t="smooth"){if(e<0||e>=this.itemsValue.length)return;let i=this.q(".feed");this.intendedPage=e,i.scrollTo({top:e*i.clientHeight,behavior:t})}syncWatermark(){let e=this.root.querySelector(".watermark");e&&(e.hidden=this.pool?.isLicensed!==!1)}dispatch(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!1}))}q(e){return this.root.querySelector(e)}};function ga(){customElements.get("og-vertical-feed")||customElements.define("og-vertical-feed",$s)}var Wm="2026-08-28T20:43:51";fa();ga();export{fm as DEFAULT_TEXT_SIZE_FRACTION,ue as ErrorCodes,ha as FreewheelAdsProvider,da as ImaAdsProvider,Wm as OGPLAYER_BUILD,gm as OGPLAYER_VERSION,Mt as OGPlayer,Ns as OGPlayerElement,$s as OGVerticalFeedElement,Li as VerticalFeedPlayerPool,ws as defaultColors,wd as defaultSubtitleStyle,ua as defaultUIConfig,Bs as defaultVerticalFeedConfig,fa as defineOGPlayerElement,ga as defineOGVerticalFeedElement,xi as embeddedDimens,la as freewheelVmapTagUrl,Ms as fullscreenDimens,Jg as hidingAllControls,Ai as isFreewheelConfig,oa as verifyLicense};
372
+ <div class="watermark" hidden>${Ns(20,"rgba(255,255,255,0.72)","#F6C445")}<span><b>OG</b>Player</span></div>`,this.pool=new Li(this.cfg,{onActiveItemChanged:s=>{let n=this.itemsValue[s];n&&this.dispatch("og-activeitemchanged",{index:s,item:n})},onNearEnd:s=>this.dispatch("og-nearend",{remaining:s}),onItemSkipped:(s,n)=>{this.dispatch("og-itemskipped",{index:s,reason:n}),s===this.intendedPage&&this.scrollToPage(s+1)},onItemError:(s,n)=>{this.itemErrors.set(s,n),this.dispatch("og-itemerror",{index:s,error:n}),this.renderActiveChrome()},onAnalyticsEvent:s=>{s.type==="MutedAutoplayFallback"&&(this.mutedValue=!0,this.dispatch("og-mutedfallback",{})),this.dispatch("og-analytics",{event:s})},onAssignmentsChanged:()=>{this.attachSurfaces(),this.syncWatermark()},onAdvanceRequested:s=>this.scrollToPage(s+1)}),this.pool.setFeedMuted(this.mutedValue),this.renderPages(),this.pool.updateItems(this.itemsValue);let i=this.q(".feed");this.observer=new IntersectionObserver(s=>{for(let n of s)if(n.intersectionRatio>=.6){let a=Number(n.target.dataset.index);a!==this.intendedPage&&(this.intendedPage=a,this.settle(a))}},{root:i,threshold:[.6]});for(let s of Array.from(i.children))this.observer.observe(s);this.resizeObserver=new ResizeObserver(()=>{i.scrollTop=this.intendedPage*i.clientHeight}),this.resizeObserver.observe(this),this.tickTimer=window.setInterval(()=>this.tick(),250),this.itemsValue.length>0&&this.settle(0)}remount(){let e=this.intendedPage;this.mount(),e>0&&this.scrollToPage(e,"instant")}teardown(){this.mounted=!1,this.observer?.disconnect(),this.observer=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.tickTimer!==null&&(clearInterval(this.tickTimer),this.tickTimer=null),this.singleTapTimer!==null&&(clearTimeout(this.singleTapTimer),this.singleTapTimer=null),this.releaseSecondary(),this.pool?.releaseAll(),this.pool=null,this.itemErrors.clear(),this.intendedPage=0}banded(e){return(e.textPlacement??"OVERLAY")!=="OVERLAY"&&(this.cfg.showTitle&&!!e.title||this.cfg.showSubtitle&&!!e.subtitle)}renderPages(){let e=this.q(".feed"),t=e.children.length;if(e.textContent="",this.itemsValue.forEach((i,s)=>{let n=document.createElement("section");n.className="page",n.dataset.index=String(s),n.dataset.testid=`og_feed_page_${s}`;let a=i.contentFit??this.cfg.contentFit;if(this.banded(i)){let o=document.createElement("div");if(o.className="band",(i.textPlacement??"OVERLAY")==="ABOVE_VIDEO"&&o.classList.add("top"),this.cfg.showTitle&&i.title){let d=document.createElement("div");d.className="t",d.textContent=i.title,o.appendChild(d)}if(this.cfg.showSubtitle&&i.subtitle){let d=document.createElement("div");d.className="s",d.textContent=i.subtitle,o.appendChild(d)}let l=this.makeRegion(i,a);(i.textPlacement??"OVERLAY")==="ABOVE_VIDEO"?n.append(o,l):n.append(l,o)}else if(i.secondaryMedia){let o=this.makeRegion(i,a);o.classList.add("half");let l=document.createElement("div");l.className="half secondhalf fit-"+a;let d=document.createElement("div");d.className="poster";let c=i.secondaryMedia.posterUrl;c&&(d.style.backgroundImage=`url("${c}")`),l.appendChild(d),n.append(o,l)}else n.appendChild(this.makeRegion(i,a));e.appendChild(n)}),this.observer){this.observer.disconnect();for(let i of Array.from(e.children))this.observer.observe(i)}t>0&&this.intendedPage<e.children.length&&(e.scrollTop=this.intendedPage*e.clientHeight),this.attachSurfaces(),this.renderActiveChrome()}makeRegion(e,t){let i=document.createElement("div");i.className="videoregion fit-"+t;let s=document.createElement("div");s.className="poster";let n=e.posterUrl??e.media.posterUrl;return n&&(s.style.backgroundImage=`url("${n}")`),i.appendChild(s),i}attachSurfaces(){if(!this.pool)return;let e=this.q(".feed");this.itemsValue.forEach((t,i)=>{let s=e.children[i];if(!s)return;let n=s.querySelector(".videoregion");if(!n)return;let a=this.pool.playerAt(i),o=n.querySelector("video");a?o!==a.videoElement&&(o?.remove(),n.appendChild(a.videoElement)):o?.remove()}),this.renderActiveChrome(),this.manageSecondary()}renderActiveChrome(){if(!this.pool)return;let e=this.q(".feed");for(let h of Array.from(this.root.querySelectorAll(".taplayer, .rail, .badge, .centre, .hairline, .hairpad, .overlaytext, .errorlayer")))h.remove();let t=this.intendedPage,i=this.itemsValue[t],s=e.children[t];if(!i||!s)return;let n=this.pool.playerAt(t),a=s.querySelector(".videoregion")??s,o=this.itemErrors.get(t);if(o&&n){let h=()=>{this.itemErrors.delete(t),n.retry(),this.renderActiveChrome()},u=document.createElement("div");if(u.className="errorlayer",this.errorOverlay)u.appendChild(this.errorOverlay(o,h));else{let f=document.createElement("div");f.className="errdefault";let g=document.createElement("div");g.className="m",g.textContent=this.cfg.errorMessageProvider?.(o)??`Playback error ${o.code}`;let m=document.createElement("button");m.textContent="Retry",m.addEventListener("click",h),f.append(g,m),u.appendChild(f)}s.appendChild(u);return}if(!n)return;let l=document.createElement("div");l.className="taplayer",l.addEventListener("click",()=>{let h=()=>{n.isPlaying?n.pause():n.play()};if(this.onItemDoubleTapped){if(this.singleTapTimer!==null)return;this.singleTapTimer=window.setTimeout(()=>{this.singleTapTimer=null,h()},300)}else h()}),l.addEventListener("dblclick",()=>{this.onItemDoubleTapped&&(this.singleTapTimer!==null&&(clearTimeout(this.singleTapTimer),this.singleTapTimer=null),this.onItemDoubleTapped(t,i),this.dispatch("og-itemdoubletapped",{index:t,item:i}))}),a.appendChild(l);let d=document.createElement("div");if(d.className="centre",a.appendChild(d),i.isSponsored){let h=document.createElement("div");if(h.className="badge",h.dataset.testid="og_feed_sponsored_badge",this.sponsoredBadge)h.appendChild(this.sponsoredBadge(i));else if(this.cfg.showSponsoredBadge){let u=document.createElement("span");u.className="chip",u.textContent="Sponsored",h.appendChild(u)}a.appendChild(h)}let c=(i.railActions??[]).slice(0,6);if(c.length>0){let h=!!i.secondaryMedia||(i.textPlacement??"OVERLAY")!=="OVERLAY",u=document.createElement("div");u.className=h?"rail railpage":"rail",u.dataset.testid="og_feed_rail",c.forEach((f,g)=>u.appendChild(this.railButton(f,g))),(h?s:a).appendChild(u)}if((i.textPlacement??"OVERLAY")==="OVERLAY"&&(this.cfg.showTitle&&i.title||this.cfg.showSubtitle&&i.subtitle)){let h=document.createElement("div");if(h.className="overlaytext",this.cfg.showTitle&&i.title){let u=document.createElement("div");u.className="t",u.textContent=i.title,h.appendChild(u)}if(this.cfg.showSubtitle&&i.subtitle){let u=document.createElement("div");u.className="s",u.textContent=i.subtitle,h.appendChild(u)}s.appendChild(h)}if(this.cfg.showProgressBar){let h=document.createElement("div");h.className="hairline",h.dataset.testid="og_feed_hairline";let u=document.createElement("div");u.className="fill",h.appendChild(u);let f=document.createElement("div");f.className="hairpad";let g=p=>{let v=h.getBoundingClientRect();if(v.width<=0||n.durationMs<=0)return;let T=Math.min(1,Math.max(0,(p-v.left)/v.width));u.style.width=`${T*100}%`,n.seekTo(T*n.durationMs)};f.addEventListener("pointerdown",p=>{this.scrubbing=!0,h.classList.add("scrubbing"),f.setPointerCapture(p.pointerId),g(p.clientX)}),f.addEventListener("pointermove",p=>{this.scrubbing&&g(p.clientX)});let m=()=>{this.scrubbing=!1,h.classList.remove("scrubbing")};f.addEventListener("pointerup",m),f.addEventListener("pointercancel",m),s.append(h,f)}this.tick()}railButton(e,t){let i=document.createElement("button");i.dataset.testid=`og_feed_rail_action_${t}`,e.isActive&&(i.className="active"),e.accessibilityLabel&&i.setAttribute("aria-label",e.accessibilityLabel);let s=document.createElement("span");if(s.className="ic",s.innerHTML=e.iconSvg,i.appendChild(s),e.label){let n=document.createElement("span");n.className="lbl",n.textContent=e.label,i.appendChild(n)}return i.addEventListener("click",n=>{n.stopPropagation(),e.onClick()}),i}tick(){if(!this.pool)return;let e=this.intendedPage,t=this.pool.playerAt(e),i=this.root.querySelector(".centre");if(!t||!i)return;let n=!!this.itemsValue[e]?.secondaryMedia&&this.secondaryFor===e&&this.secondary!==null&&this.secondary.state!=="READY"&&!t.isPlaying,a=t.videoElement.played.length>0,o=t.state==="BUFFERING",l=!t.isPlaying&&t.state==="READY"&&!n&&a,d="";l?d="glyph":(o||n)&&(d="spinner");let c=i.dataset.show??"";if(d!==c){if(i.dataset.show=d,i.textContent="",d==="glyph"){let h=document.createElement("div");h.className="glyph",h.innerHTML=this.cfg.playIconSvg??'<svg viewBox="0 0 24 24"><path d="M8 5.5v13l11-6.5z" fill="#fff"/></svg>',i.appendChild(h)}else if(d==="spinner"){let h=document.createElement("div");h.className="spinner",i.appendChild(h)}}if(!this.scrubbing){let h=this.root.querySelector(".hairline .fill");h&&t.durationMs>0&&(h.style.width=`${t.currentPositionMs/t.durationMs*100}%`)}}manageSecondary(){let e=this.intendedPage,t=this.itemsValue[e],i=this.pool?.playerAt(e)??null;if(!t?.secondaryMedia||!i){this.releaseSecondary();return}if(this.secondaryFor===e&&this.secondary)return;this.releaseSecondary();let a=this.q(".feed").children[e]?.querySelector(".secondhalf");if(!a)return;let o=new Mt({...this.cfg.licenseKey?{licenseKey:this.cfg.licenseKey}:{},fallbackToMutedAutoplay:!0});this.secondary=o,this.secondaryFor=e,o.setBufferRole("STANDBY"),o.setLooping(this.cfg.loopItems&&!t.isSponsored),o.isMuted=!0,o.load(t.secondaryMedia,{autoplay:!1}),a.appendChild(o.videoElement);let l=()=>{this.secondary!==o||this.intendedPage!==e||(o.setBufferRole("ACTIVE"),this.syncSecondaryAudio(),i.play(),o.play())},d={onStateChanged:h=>{h==="READY"&&l()}};o.addListener(d);let c={onPause:()=>o.pause(),onResume:()=>o.play(),onPlay:()=>o.play()};i.addListener(c),this.secondaryDetach=()=>{o.removeListener(d),i.removeListener(c)},o.state==="READY"&&l()}syncSecondaryAudio(){let e=this.itemsValue[this.secondaryFor];if(!this.secondary||!e)return;let t=(e.splitAudioSource??"PRIMARY")==="SECONDARY";this.secondary.isMuted=t?this.mutedValue:!0}releaseSecondary(){this.secondaryDetach?.(),this.secondaryDetach=null,this.secondary&&(this.secondary.videoElement.remove(),this.secondary.release()),this.secondary=null,this.secondaryFor=-1}settle(e){this.pool?.settle(e),this.renderActiveChrome(),this.manageSecondary()}scrollToPage(e,t="smooth"){if(e<0||e>=this.itemsValue.length)return;let i=this.q(".feed");this.intendedPage=e,i.scrollTo({top:e*i.clientHeight,behavior:t})}syncWatermark(){let e=this.root.querySelector(".watermark");e&&(e.hidden=this.pool?.isLicensed!==!1)}dispatch(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!1}))}q(e){return this.root.querySelector(e)}};function ya(){customElements.get("og-vertical-feed")||customElements.define("og-vertical-feed",Gs)}var sp="2026-08-31T00:36:16";pa();ya();export{Em as DEFAULT_TEXT_SIZE_FRACTION,ue as ErrorCodes,ga as FreewheelAdsProvider,ua as ImaAdsProvider,sp as OGPLAYER_BUILD,Tm as OGPLAYER_VERSION,Mt as OGPlayer,$s as OGPlayerElement,Gs as OGVerticalFeedElement,Li as VerticalFeedPlayerPool,Os as defaultColors,Fd as defaultSubtitleStyle,ma as defaultUIConfig,Us as defaultVerticalFeedConfig,pa as defineOGPlayerElement,ya as defineOGVerticalFeedElement,xi as embeddedDimens,ha as freewheelVmapTagUrl,Fs as fullscreenDimens,rm as hidingAllControls,Ai as isFreewheelConfig,da as verifyLicense};